← Back to Pull requests

feat: add attributions for device vitals #1333

Closed
unknown closed this pull request without merging on Dec 03, 2026 18:38 UTC
View on GitHub
unknown unknown commented on Nov 30, 2026 20:46 UTC
Author

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's AwsDeviceKitManager.

  • CPU is one measurement in three attributes: process.cpu.utilization, from 0 to 1, with its numerator process.cpu.used_time and denominator process.cpu.available_time.

  • process.memory.usage is the physical footprint in bytes, the figure iOS limits, not the resident size.

  • hw.battery.charge comes from UIDevice, or WKInterfaceDevice on 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.id and thread.is_main describe the thread that starts the span or emits the record.

  • Readings are taken on demand and reused until they expire, one second by default. No timer runs. A reading that is unavailable leaves its attribute off.

  • ResourceExtension gains process.pid, on the resource.
  • thread.id and process.pid are upstream attributes. The others, some of which upstream defines only as metrics, live in the federated semconv registry at development stability, 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 at fab82bd9 for its battery-state, low-power and thermal-state mappings, model tables and helpers. The battery comes from UIDevice and WKInterfaceDevice, and the CPU, memory and thread readings from Darwin calls DeviceKit doesn't make. The demo's load test reads ProcessInfo.thermalState directly. NOTICE stays unchanged.

    Testing

    | Run | Result |
    | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
    | swift test --enable-all-traits, macOS and Linux | Passes on macOS and in Linux Docker (Swift 6.4.3); VitalsTests passes 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.pid and 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-traits passes locally

  • Unit tests added or updated for the change

  • Instrumentation and event changes only: the integration tests in

  • Tests/IntegrationTests are updated. Anything that adds, removes or
    renames a span, log record, event name, or attribute emitted by an
    instrumentation (Sources/Instrumentation/) must be exercised by
    IntegrationTestScenario in Examples/HackerNewsDemo and asserted on
    in Tests/IntegrationTests/Assertions. Run make integ-tests-ios to
    verify, and see Tests/IntegrationTests/README.md.
  • Documentation updated (README, doc comments) where behavior changed
  • ---

    See docs Sources/Instrumentation/Vitals/README.md.

    ---

    Vitals

    Status: experimental. Names may change in any release. The attributes are at development stability 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:

    import Vitals
    
    VitalsManagerProvider.register(vitalsManager: VitalsManager())
    
    let tracerProvider = TracerProviderBuilder()
      .add(spanProcessor: VitalsSpanProcessor())
      .add(spanProcessor: BatchSpanProcessor(spanExporter: spanExporter))
      .build()
    let loggerProvider = LoggerProviderBuilder()
      .with(processors: [
        VitalsLogRecordProcessor(nextProcessor: BatchLogRecordProcessor(logRecordExporter: logExporter))
      ])
      .build()
    

    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.

    [!NOTE]

    By default this module turns on battery monitoring, a setting of the whole app, once. Apple advises to "enable battery monitoring or proximity sensing only when you need it". Pass VitalsConfig(enablesBatteryMonitoring: false) to leave the setting to the app, or VitalsConfig(battery: false) to leave the battery out.

    Set how long each reading is reused, in seconds, with the configuration:

    VitalsConfig(cpuExpiration: 5, memoryExpiration: 1, batteryExpiration: 60)
    

    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 the LogLimits passed to VitalsLogRecordProcessor(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: like CLOCK_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_info over task_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 in mach/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 is false" |
    | 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 against THREAD_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 in BatteryReader.swift.

    | Attribute | Depends on | Kind | Swift module | Source |
    | ------------------------------ | --------------------------------------------------------------------------------------- | ------------ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
    | process.cpu.used_time | clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID), which calls getrusage(RUSAGE_SELF) | System call | Darwin | Apple Libc source |
    | process.cpu.available_time | clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW), which calls mach_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), field phys_footprint | Mach call | Darwin | XNU task.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; in ResourceExtension, not this module |

    Every attribute also needs OpenTelemetryApi, OpenTelemetrySdk and InstrumentationSemanticConventions. 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.start or app.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.id is 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" | No cpu.mode: user and system time together |
    | process.cpu.used_time | double | s | None | process.cpu.time is cumulative; this covers one window |
    | process.cpu.available_time | double | s | None | The denominator of process.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" | No hw.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, and heap.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

  • Sessions: the other processors that stamp every span and log record

  • MetricKit: the system's own aggregated CPU and memory metrics

  • Resource extension: the device model and OS

  • UIDevice and Reducing your app's memory use

  • AwsOtelSwift AwsDeviceKitManager: the design this module started from, which stamps CPU in cores, resident memory in MB and the same battery attribute
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: nachoBonafonte Review duration: 4191m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%