feat: add attributions for device vitals #1333
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #1333"
general
weight: 0.35
nachoBonafonte
TL;DR
Watch recording: https://app.revyl.ai/sessions/report?token=ab143429-8648-40c6-b551-77bc16e32b3b
Summary
This PR adds
Vitals, which stamps the process's CPU use and memory footprint, the battery charge and the current thread on every span and log record. It started from AwsOtelSwift'sAwsDeviceKitManager.process.cpu.utilization, from 0 to 1, with its numeratorprocess.cpu.used_timeand denominatorprocess.cpu.available_time.process.memory.usageis the physical footprint in bytes, the figure iOS limits, not the resident size.hw.battery.chargecomes fromUIDevice, orWKInterfaceDeviceon watchOS, and is left off while the battery state is unknown. The module has no third-party dependency. By default the module turns on battery monitoring, once;VitalsConfig(enablesBatteryMonitoring: false)leaves that to the app.thread.idandthread.is_maindescribe the thread that starts the span or emits the record.ResourceExtensiongainsprocess.pid, on the resource.thread.idandprocess.pidare upstream attributes. The others, some of which upstream defines only as metrics, live in the federated semconv registry atdevelopmentstability, as in #1275.The HackerNews demo shows the readings in its Settings tab and enables its CPU and memory tests.
No code is copied or adapted from DeviceKit, so no license notice is added. Earlier revisions called its
batteryLevel; none copied it. I compared the branch against DeviceKit atfab82bd9for its battery-state, low-power and thermal-state mappings, model tables and helpers. The battery comes fromUIDeviceandWKInterfaceDevice, and the CPU, memory and thread readings from Darwin calls DeviceKit doesn't make. The demo's load test readsProcessInfo.thermalStatedirectly.NOTICEstays unchanged.Testing
| Run | Result |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
swift test --enable-all-traits, macOS and Linux | Passes on macOS and in Linux Docker (Swift 6.4.3);VitalsTestspasses 62 tests on an iOS 26.5 simulator || iPhone 16 Pro Max (iOS 27.2.1), by hand, per the README | Battery matched
UIDevice; CPU, memory and thread readings checked against known load and raw system calls. Taken with DeviceKit, before it was dropped; not rerun || Integration tests | New assertions on CPU, memory, thread,
process.pidand the simulator's missing battery; pass on an iOS 26.5 simulator |Limitations
1. CPU is absent until the first window passes, and from the first reading after more than a minute without one (or twice
cpuExpiration, if longer). It describes the time before the span, not the span.2. Off the main thread, the battery reading is the last one taken on the main thread, and is absent until there is one. The simulator, macOS and tvOS have none.
3. An async function can resume on another thread, so the thread attributes say where a span began, not where it ran.
4. Records about the past, such as a crash reported on the next launch, carry current readings. The demo keeps them from Vitals; https://github.com/open-telemetry/opentelemetry-swift/issues/1337 tracks caching tracked attributes for crash reports.
5. No one has measured battery on watchOS or visionOS hardware, and Mac Catalyst only builds. Linux is not built.
Checklist
swift test --enable-all-traitspasses locallyTests/IntegrationTestsare updated. Anything that adds, removes orrenames a span, log record, event name, or attribute emitted by an
instrumentation (
Sources/Instrumentation/) must be exercised byIntegrationTestScenarioinExamples/HackerNewsDemoand asserted onin
Tests/IntegrationTests/Assertions. Runmake integ-tests-iostoverify, and see
Tests/IntegrationTests/README.md.---
---
Vitals
Status: experimental. Names may change in any release. The attributes are at
developmentstability in this repository's federated registry.The
VitalsManager* class reads how hard the app is working the device: the process's CPU use, its memory footprint, and the battery charge. Two processors stamp the readings, and the current thread, on every span and log record, so a slow request can be told apart from a slow request on a busy phone.!A timeline of five spans. The first, half a second in, carries memory and battery but no CPU. The second, at 2 seconds, carries a CPU reading of 2 seconds used of 8 available, 0.25, for the two seconds before it. The third, half a second later, carries the same cached readings. The fourth comes after the app was suspended until 100 seconds; its CPU window is over a minute long, so it carries no CPU. The fifth, a second later, carries 3 seconds of 4, 0.75, for that second.
!Each attribute, the reading behind it, the call that reading makes and the module the call comes from. CPU time used comes from getrusage, and CPU time available from mach_continuous_time and ProcessInfo; utilization is computed from them. Memory comes from task_info. Battery comes from UIKit, or WatchKit on watchOS. The thread comes from pthread_threadid_np and pthread_main_np.
Register both processors, ahead of the exporter:
Registering a manager is optional. The processors create a default one at the first span or record, but CPU is measured from when the manager is created.
Set how long each reading is reused, in seconds, with the configuration:
Instance properties
Each is
nil, and its attribute left off, when there is no reading. No value stands in for a missing one.<dl>
<dt><code>cpu</code> <em>Read only</em></dt>
<dd>A <code>CPUReading</code>: the process's CPU use over one window. Its properties are below.</dd>
<dt><code>cpuUtilization</code> <em>Read only</em></dt>
<dd>Shorthand for <code>cpu?.utilization</code>.</dd>
<dt><code>memoryUsage</code> <em>Read only</em></dt>
<dd>The process's physical footprint, in bytes. Stamped as <code>process.memory.usage</code>.</dd>
<dt><code>batteryCharge</code> <em>Read only</em></dt>
<dd>The fraction of the device's battery charge that remains, from 0 to 1. Stamped as <code>hw.battery.charge</code>.</dd>
</dl>
CPUReading<dl>
<dt><code>utilization</code> <em>Read only</em></dt>
<dd><code>usedTime</code> over <code>availableTime</code>, from 0 to 1. Stamped as <code>process.cpu.utilization</code>.</dd>
<dt><code>usedTime</code> <em>Read only</em></dt>
<dd>The numerator: CPU time the process used in the window, in seconds. Stamped as <code>process.cpu.used_time</code>.</dd>
<dt><code>availableTime</code> <em>Read only</em></dt>
<dd>The denominator: the window's length times the active processors, in seconds. Stamped as <code>process.cpu.available_time</code>.</dd>
</dl>
VitalsConfig<dl>
<dt><code>cpu</code>, <code>memory</code>, <code>battery</code></dt>
<dd>Whether to take each reading. Default <code>true</code>.</dd>
<dt><code>thread</code></dt>
<dd>Whether to stamp the current thread. Default <code>true</code>.</dd>
<dt><code>enablesBatteryMonitoring</code></dt>
<dd>Whether to turn on battery monitoring, once, if it is off. Default <code>true</code>.</dd>
<dt><code>cpuExpiration</code></dt>
<dd>Seconds a CPU reading is reused, and the least length of the next window. Default 1, least 0.1.</dd>
<dt><code>memoryExpiration</code></dt>
<dd>Seconds a memory reading is reused. Default 1.</dd>
<dt><code>batteryExpiration</code></dt>
<dd>Seconds a battery reading is reused. Default 1.</dd>
</dl>
A negative or undefined expiration counts as zero, which takes a new memory or battery reading every time.
Stamping
A span takes the readings current when it starts, a log record those current when it is emitted. An attribute already there is left alone, and the others are still added, except that the three CPU attributes go together: if one is there, none is added. The two thread attributes do the same.
No group is added that would take a span or record past its attribute count limit: the span's
SpanLimits, or theLogLimitspassed toVitalsLogRecordProcessor(nextProcessor:vitalsManager:logLimits:). A log record can't tell a processor its limits, so pass the ones the logger provider was built with. Groups that fit are added in the order CPU, thread, memory, battery.Readings are taken on demand, and each is shared by all the telemetry until it expires. No timer runs. On an iPhone 16 Pro Max (iOS 27.2.1), in a release build, returning cached readings costs about 0.09 µs, a new memory reading 1.0 µs, a new battery reading 1.2 µs, and starting and ending a span 1.9 µs, against 1.1 µs without the processor. The thread attributes account for about 0.5 µs of that. Apple warns that
task_info, the source of the memory reading, "is an expensive call".process.cpu.<dl>
<dt>Scope</dt>
<dd>This process, all its threads, including those that have ended. Not the device: another app's load doesn't show.</dd>
<dt>Value</dt>
<dd>CPU time used since the last measurement, divided by the elapsed time and the number of active processors. One core kept busy on a six-core phone reads 0.17, not 1.</dd>
<dt>Gaps</dt>
<dd>Absent until the first window, of a second or <code>cpuExpiration</code> if shorter, has passed, and from the first reading after more than a minute, or twice <code>cpuExpiration</code> if longer, without one, whose average would be mostly idle or suspended time. It describes the time before the span, not the span. All cores count alike, fast or slow.</dd>
<dt>Opting out</dt>
<dd><code>VitalsConfig(cpu: false)</code></dd>
</dl>
| Step | How | Source |
| ----------------- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| CPU time |
CLOCK_PROCESS_CPUTIME_ID|man clock_gettime: "the amount of CPU (in user- or kernel-mode) used by the calling process" || Elapsed time |
CLOCK_MONOTONIC_RAW|man clock_gettime: likeCLOCK_MONOTONIC, which "will continue to increment while the system is asleep" || Active processors |
activeProcessorCount| "The number of active processing cores available on the computer" || Ended threads | Counted | Not documented; unit test on macOS and in the simulators |
The module doesn't add up
thread_infoovertask_threads, as many CPU readers do. That hands back a Mach port for each thread, which must be released, misses threads that have ended, and took ten times as long on the same Mac with 18 threads.process.memory.usage<dl>
<dt>Scope</dt>
<dd>This process.</dd>
<dt>Value</dt>
<dd>The <code>phys_footprint</code> of <code>task_info</code>, in bytes, not the resident size. Resident size counts clean pages, such as mapped files, that the system can discard.</dd>
<dt>Gaps</dt>
<dd>Says nothing about the limit. <a href="https://developer.apple.com/documentation/os/os_proc_available_memory"><code>os_proc_available_memory</code></a> returns what is left of it.</dd>
<dt>Opting out</dt>
<dd><code>VitalsConfig(memory: false)</code></dd>
</dl>
| Step | How | Source |
| ------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| What a footprint is | — |
os_proc_available_memory: "the data that you allocated in RAM, and that must stay in RAM (or the equivalent) at all times" || Why the footprint | The app's limit is on it | Same page: "the current memory limit minus the memory footprint of your app" |
| Reading it |
TASK_VM_INFO| Not documented: the field is inmach/task_info.h, with no description || Dirty pages in, clean out | Not counted until written | Reducing your app's memory use: "Dirty memory contributes to the memory-use metric". Unit test on macOS and the iOS simulator |
hw.battery.charge<dl>
<dt>Scope</dt>
<dd>The device.</dd>
<dt>Value</dt>
<dd>The <code>batteryLevel</code> of <code>UIDevice</code>, or of <code>WKInterfaceDevice</code> on watchOS, rounded to thousandths. None while the battery state is unknown or the level is negative, as both are while monitoring is off.</dd>
<dt>Detection</dt>
<dd>Read on the main thread, where the class must be used. Telemetry on the main thread reads it at once. Elsewhere it takes the last reading, if that is at most a minute old, or twice <code>batteryExpiration</code> if longer, and asks the main thread for another without waiting, since waiting could deadlock. While one request waits, telemetry makes no other, even with a <code>batteryExpiration</code> of zero.</dd>
<dt>Battery monitoring</dt>
<dd>At the first reading, if monitoring is off, it is turned on. It is never turned on again, and never off. If the app turns it off later, readings stop. The module can't tell an app that turned monitoring off before that from one that never touched it.</dd>
<dt>Gaps</dt>
<dd>None in the simulator, on macOS or on tvOS. Off the main thread, absent at first and after that age without telemetry. Whether a level is available as soon as monitoring is on is not documented; it was on an iPhone 16 Pro Max. If not, the next reading, once this one expires, has it. Apple's level is coarse: don't <a href="https://developer.apple.com/documentation/uikit/uidevice/batteryleveldidchangenotification">"calculate battery drainage rate"</a> from it.</dd>
<dt>Opting out</dt>
<dd><code>VitalsConfig(battery: false)</code>, or <code>VitalsConfig(enablesBatteryMonitoring: false)</code> to read the charge only while the app monitors it.</dd>
</dl>
| Step | How | Source |
| ----------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Monitoring is off | By default |
isBatteryMonitoringEnabled: "The default value of this property isfalse" || Level |
batteryLevel|batteryLevel: "ranges from 0.0 (fully discharged) to 1.0 (100% charged)" || No reading | −1 |
batteryLevel: "If battery monitoring is not enabled […] the value of this property is –1.0" || watchOS |
WKInterfaceDevice, the same way |batteryLevel: "a value between 0.0 (0% charge) and 1.0 (100% charge)" || Simulator | −1 | Not documented; unit tests |
thread.*<dl>
<dt>Scope</dt>
<dd>The thread that starts the span or emits the log record.</dd>
<dt>Value</dt>
<dd><code>thread.id</code> is the system-wide identifier of the thread, and <code>thread.is_main</code> whether it is the main thread. Both are read at each stamping, so neither expires. <code>thread.id</code> and the <code>process.pid</code> on the <a href="https://github.com/williazz/opentelemetry-swift/blob/feat/devicekit/Sources/Instrumentation/SDKResourceExtension/README.md">resource</a> come from the same process, except on a record about an earlier one.</dd>
<dt>Gaps</dt>
<dd>An async function can resume on another thread after an <code>await</code>, so the attributes say where a span began, not where it ran. A queue is not a thread: several can share one. A thread name is not stamped, because dispatch threads had none in a test. If another processor hands records on to a thread of its own before this one, they carry that thread.</dd>
<dt>Opting out</dt>
<dd><code>VitalsConfig(thread: false)</code></dd>
</dl>
| Step | How | Source |
| ---------- | --------------------- | ----------------------------------------------------------------------------------------------------------- |
| Identifier |
pthread_threadid_np|man pthread_threadid_np: "the system-wide unique integral ID"; unit test againstTHREAD_IDENTIFIER_INFO|| Main |
pthread_main_np|man pthread_main_np: "returns 1 if the calling thread is the initial thread" |Dependencies
Drawn above. The process and thread readings are in
Device.swift, the battery reading inBatteryReader.swift.| Attribute | Depends on | Kind | Swift module | Source |
| ------------------------------ | --------------------------------------------------------------------------------------- | ------------ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
process.cpu.used_time|clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID), which callsgetrusage(RUSAGE_SELF)| System call |Darwin| Apple Libc source ||
process.cpu.available_time|clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW), which callsmach_continuous_time()| Mach time |Darwin| Apple Libc source || |
ProcessInfo.activeProcessorCount| Framework |Foundation|activeProcessorCount||
process.cpu.utilization| The two above | Computed | — | — ||
process.memory.usage|task_info(TASK_VM_INFO), fieldphys_footprint| Mach call |Darwin| XNUtask.defs; the field, not documented ||
hw.battery.charge|UIDevice: state, level and monitoring, on iOS, Catalyst and visionOS | Framework |UIKit|UIDevice|| |
WKInterfaceDevice, the same, on watchOS | Framework |WatchKit|WKInterfaceDevice|| |
DispatchQueue.main, off the main thread | Framework |Dispatch|DispatchQueue||
thread.id|pthread_threadid_np| pthread call |Darwin|man pthread_threadid_np||
thread.is_main|pthread_main_np| pthread call |Darwin|man pthread_main_np||
process.pid, on the resource |ProcessInfo.processIdentifier| Framework |Foundation|processIdentifier; inResourceExtension, not this module |Every attribute also needs
OpenTelemetryApi,OpenTelemetrySdkandInstrumentationSemanticConventions. The module has no third-party dependency.Records about the past
The processors stamp what is true now, so a record about an earlier time carries the wrong readings: a crash reported on the next launch, a MetricKit payload, a span given a start time in the past, such as an
app.startorapp.resume. Set the attributes on such a record, or keep it from these processors. The HackerNews demo keeps the launch spans and crash reports from them by instrumentation scope.Metrics carry no readings. A metric of these would be aggregated across devices; stamped on a span, a reading keeps its session and its moment.
Instance methods
VitalsManager<dl>
<dt><code>init(configuration:)</code></dt>
<dd>Starts the first CPU window. Reads nothing else, and leaves battery monitoring alone, until the first span, record or property read.</dd>
</dl>
VitalsConfig<dl>
<dt><code>init(cpu:memory:battery:thread:enablesBatteryMonitoring:cpuExpiration:memoryExpiration:batteryExpiration:)</code></dt>
<dd>Every argument has a default. A reading that is off is never taken.</dd>
</dl>
VitalsManagerProvider<dl>
<dt><code>register(vitalsManager:)</code> <em>Static</em></dt>
<dd>Shares a manager, such as one with a configuration. Processors read it at each span or record, so one registered later still reaches them.</dd>
<dt><code>getInstance()</code> <em>Static</em></dt>
<dd>Returns the shared manager, creating a default one on first use.</dd>
</dl>
Specifications
Upstream defines three of these names as metrics, not attributes, so the federated registry defines attributes with the same names, meanings and units. It also defines the other two CPU names and
thread.is_main, which upstream lacks.thread.idis an upstream attribute.| Name | Type | Unit | Upstream metric | Difference |
| ---------------------------- | ------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
|
process.cpu.utilization| double |1| Gauge: "Difference in process.cpu.time since the last measurement, divided by the elapsed time and number of CPUs available to the process" | Nocpu.mode: user and system time together ||
process.cpu.used_time| double |s| None |process.cpu.timeis cumulative; this covers one window ||
process.cpu.available_time| double |s| None | The denominator ofprocess.cpu.utilization||
process.memory.usage| int |By| UpDownCounter: "The amount of physical memory in use" | Apple's footprint, which counts compressed memory ||
hw.battery.charge| double |1| Gauge: "Remaining fraction of battery charge" | Nohw.id, as there is one battery ||
thread.id| int | — | None: an attribute, "Current 'managed' thread ID (as opposed to OS thread ID)" | The OS identifier, as Swift has no managed one ||
thread.is_main| boolean | — | None | Federated |OpenTelemetry Android has no CPU reading. It puts
battery.percent, from 0 to 100, andheap.free, the free Java heap, on crash reports only. Neither is used here: the first differs in unit from the upstream name, and the second has no Apple counterpart.Compatibility
| Platform | Minimum | CPU | Memory | Battery | Tested on |
| ------------ | ------- | :-: | :----: | :-----: | -------------------------------------------------------------------------------- |
| iOS, iPadOS | 15 | ✓ | ✓ | ✓ | iPhone simulator: unit tests; HackerNews demo export. iPhone 16 Pro Max: by hand |
| macOS | 12 | ✓ | ✓ | — | Unit tests |
| tvOS | 15 | ✓ | ✓ | — | Simulator: unit tests |
| watchOS | 8 | ✓ | ✓ | ✓ | Simulator: unit tests |
| visionOS | 1 | ✓ | ✓ | ✓ | Simulator: unit tests |
| Mac Catalyst | 15 | ✓ | ✓ | ✓ | Builds only |
| Linux | — | — | — | — | Not built |
On an iPhone 16 Pro Max (iOS 27.2.1), charging, the battery reading matched
UIDevice, and the CPU, memory and thread readings were checked against known load and raw system calls. The watchOS and visionOS battery readings have been seen only from a fake device in unit tests, since the simulators have none.See also
UIDeviceand Reducing your app's memory useAwsDeviceKitManager: the design this module started from, which stamps CPU in cores, resident memory in MB and the same battery attribute