Skip to content

feat(stats): report cpuUtilization in the machine-readable formats - #2146

Merged
jglogan merged 5 commits into
apple:mainfrom
guanchzhou:stats-json-cpu-percent
Oct 30, 2026
Merged

jglogan merged 5 commits into
apple:mainfrom
guanchzhou:stats-json-cpu-percent

Conversation

@guanchzhou

@guanchzhou guanchzhou commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2144

container stats already samples twice, sleeping two seconds between samples, and computes CPU usage from the pair for its table. Output.render received only stats2, so json, yaml and toml consumers paid that latency and got back neither the derived value nor the earlier sample needed to compute it. Getting CPU usage from the CLI meant invoking the command twice and diffing cpuUsageUsec by hand.

Change

A StatsReport payload for the non-table formats: the latest sample plus cpuUtilization, the fraction of one core used between the two samples (1.0 is one fully used core, 2.5 is two and a half). Percentages are a presentation concern, so only the table renders one (cpuUtilization * 100); machine-readable consumers get the raw fraction and format it themselves.

ContainerResource.ContainerStats is documented as modelling a single sample, and a rate is not a property of one sample, so the derived value lives in the command rather than widening that type. The wire shape of the existing fields is unchanged; cpuUtilization is additive.

calculateCPUUtilization(cpuUsage1:cpuUsage2:timeInterval:) replaces calculateCPUPercent and returns the fraction. Each container's two samples are timestamped with ContinuousClock, and the utilization divides by the measured delta rather than the nominal two-second sleep, so request latency between samples no longer skews the result. If the second sample fails there is no interval to divide by, and the value is reported as unavailable (-- in the table, omitted from json) rather than as 0.

The StatsReport documentation and docs/resource-usage.md describe the new field.

Verification, end to end with this build

A container allocated two CPUs running two busy loops:

$ .build/debug/container stats --no-stream stats2146
Container ID  Cpu %    Memory Usage         Net Rx/Tx             Block I/O            Pids
stats2146     199.98%  2.50 MiB / 1.00 GiB  16.02 KiB / 0.59 KiB  1.60 MiB / 0.00 KiB  3

$ .build/debug/container stats --format json --no-stream stats2146
[{"blockReadBytes":1679360,"blockWriteBytes":0,"cpuUsageUsec":11660531,"cpuUtilization":2.0004153297179847,"id":"stats2146","memoryLimitBytes":1073741824,"memoryUsageBytes":2617344,"networkRxBytes":12744,"networkTxBytes":602,"numProcesses":3}]

Unit tests cover the calculation (one core, four cores, a non-nominal interval, no change, counter decrease) and the json, yaml and toml encodings, including TOML's [[items]] wrapper for top-level arrays. swift test --filter 'CalculateCPUUtilizationTests|StatsReportEncodingTests' passes 10 tests in 2 suites, and make swift-fmt-check is clean.

Left for your call

stats1 is still dropped. Emitting both samples would let a consumer compute other rates (network and block I/O per second) the same way. I kept this PR to the one value the table already shows; say the word if the fuller shape is preferable.

Environment: macOS 27.0 (Tahoe), Apple silicon, Swift 6.4.

Per CONTRIBUTING: I used AI assistance while investigating and drafting this, and I can explain and justify every line.

container stats already samples twice, sleeping two seconds between samples,
and computes a CPU percentage from the pair for its table. Only the second
sample was rendered for json, yaml and toml, so a consumer paid that latency
and received neither the percentage nor the earlier sample needed to derive it.
Getting a CPU percentage from the CLI meant invoking the command twice and
diffing cpuUsageUsec by hand.

Adds a StatsReport payload for the non-table formats: the latest sample plus
the derived percentage. ContainerResource.ContainerStats models a single sample
and a rate is not a property of one sample, so the derived value lives in the
command rather than widening that type.

The two-second interval is now a single constant. collectStats sleeps for it
and the percentage divides by it, so the two must agree; they were separate
literals before.

@kavix kavix left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this, @guanchzhou! Adding cpuPercent to the machine-readable output is a useful improvement, and consolidating the hardcoded 2-second sleep into sampleInterval also helps prevent sampling drift.

A few small suggestions that could improve maintainability

  1. Deduplicate CPU calculation
    Consider moving cpuPercent into a computed property on StatsSnapshot. This would allow both StatsReport and statsTable to share the same calculation logic and avoid duplication.
  2. Avoid field duplication in StatsReport
    Rather than manually mirroring all properties from ContainerResource.ContainerStats (and potentially missing fields added in the future), consider wrapping stats2 directly and implementing a custom encode(to:). This would make the implementation more resilient to future changes.
  3. Add test coverage
    Please consider adding or updating unit/snapshot tests to verify that --format json includes the expected cpuPercent field.

@guanchzhou

Copy link
Copy Markdown
Contributor Author

Thanks @kavix — took all three.

  1. cpuPercent is now a computed property on StatsSnapshot. The table and StatsReport both read it.

  2. StatsReport wraps the latest sample instead of copying its fields, and encode(to:) flattens through one keyed container. I didn't call stats.encode(to:) and then add cpuPercent on a second container: that works for JSON and YAML, but TOMLEncoder resets encoder.value on each container(keyedBy:), so the sample fields would disappear from toml output.

  3. Unit tests cover the formula and the flattened json/yaml/toml shape. The existing --format json CLI tests now require cpuPercent.

@kavix kavix left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Review asked for one calculation, no field mirroring on StatsReport,
and tests that json carries cpuPercent. TOMLEncoder cannot merge two
keyed containers, so encode flattens the wrapped sample in one pass.
sujay2306

This comment was marked as off-topic.

@guanchzhou

Copy link
Copy Markdown
Contributor Author

@katiewasnothere, could you take a look at this one when you have time? It addresses the earlier review feedback and has been unchanged since 30 August. Happy to rebase if needed.

@jglogan jglogan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@guanchzhou Thanks! This seems reasonable; only thing I'm suggestion is to report fractional utilization in JSON, and do the percentage presentation for the tabular result only.

/// - cpuUsage2: CPU usage from the second sample
/// - timeInterval: Wall-clock interval between samples
/// - Returns: CPU percentage where 100% = one fully utilized core
static func calculateCPUPercent(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's call this calculateCPUUtilization that returns the fractional utilization of the CPU, with 1.0 representing full utilization of one core.

Percentages are a presentation concern - compute those for tabular output but the JSON output should only have cpuUtilization, and the caller can decide how to format the raw data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update the StatsReport docc and the PR text for the modification as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9b43c1d. calculateCPUUtilization returns the fraction of one core (1.0 = one fully used core). JSON, YAML and TOML carry only cpuUtilization; the table multiplies by 100 for Cpu %.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the StatsReport doc comment, the PR title and description, and docs/resource-usage.md, which now shows cpuUtilization in the JSON example and explains the unit.

return ContainerStats.calculateCPUPercent(
cpuUsage1: .microseconds(first),
cpuUsage2: .microseconds(second),
timeInterval: ContainerStats.sampleInterval

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could make this a little more accurate by recording ContinuousClock.Instant times for both samples and using the delta instead of the constant here.

I wouldn't require it for this PR; might be more suitable for a follow-on issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folded this in rather than leaving a follow-on. Each container's two samples are timestamped with ContinuousClock and the utilization divides by the measured delta. If the second sample fails there is no interval, so the value is reported as unavailable instead of 0.

…vals

Per review, the machine-readable formats carry `cpuUtilization`, a
fraction of one core (1.0 is one fully used core), and only the table
renders a percentage. `calculateCPUPercent` becomes
`calculateCPUUtilization`.

Each container's two samples are now timestamped with ContinuousClock,
and the utilization divides by the measured delta instead of the
nominal two-second sleep. When the second sample fails there is no
interval, so the value is reported as unavailable rather than 0.

Update the StatsReport documentation and docs/resource-usage.md.

Signed-off-by: Andrey Maltsev <[email protected]>
@guanchzhou guanchzhou changed the title feat(stats): report cpuPercent in the machine-readable formats feat(stats): report cpuUtilization in the machine-readable formats Oct 30, 2026

@jglogan jglogan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The elapsed time enhancement looks good. Could you add a test case to cover the nil path?

@@ -156,48 +156,57 @@ extension Application {
fileprivate struct StatsSnapshot {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you give this internal visibility and add a unit test for the nil case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 111396e. StatsSnapshot and StatsReport.init(snapshot:) are internal now, and the new StatsSnapshotTests suite covers the nil cases: no second sample (zero interval), and missing cpuUsageUsec in either sample. It also checks that the measured interval is used and that StatsReport(snapshot:) leaves cpuUtilization out of the JSON when it is nil.

Give StatsSnapshot internal visibility and add unit tests for the
cases where cpuUtilization is nil.

Signed-off-by: Andrey Maltsev <[email protected]>
testStatsAllContainers reads stats for every running container, so the
cpuUtilization assertion also covered containers from tests running in
parallel. One of those can stop between the two samples and correctly
report no utilization. Limit the assertion to the two containers the
test creates.

Signed-off-by: Andrey Maltsev <[email protected]>
@github-actions

Copy link
Copy Markdown

Code Coverage

Tier Line Coverage
Unit 22.96%
Integration 69.37%
Combined 78.07%

@jglogan
jglogan merged commit af7c439 into apple:main Oct 30, 2026
3 checks passed
@guanchzhou
guanchzhou deleted the stats-json-cpu-percent branch November 1, 2026 13:31
henrywang added a commit to henrywang/Berthly that referenced this pull request Nov 12, 2026
…tats (#241)

Closes #235.

## Why

Berthly's Overview CPU figure was a percentage of all host cores.
`container stats` and `docker stats` use a percentage of one core. On a
10-core Mac, a container saturating one core read 10% in Berthly and
100% in the terminal. container 1.7.1 made the CLI's unit explicit:
`cpuUtilization` in JSON/YAML/TOML output is a fraction of one core
(apple/container#2146). Decision in #235: match the CLI.

## Changes

- `ContainerStatsMath.cpuPercent` returns CPU-time delta / wall-clock
interval × 100. That's the CLI's `calculateCPUUtilization` × 100, and it
is not divided by host cores or by the container's cpus.
- The `cores:` parameter is gone from `cpuPercent` and
`ContainerStatsDeltaTracker.sample`. The live stats stream no longer
reads `processorCount`.
- No view change: the Overview card's sparkline has no fixed y-domain,
so values above 100% draw correctly, and the card shows
`"\(Int(cpu))%"`.
- Mock values (8–24%) are unchanged.
- Tests:
  - Per-core expectations (`2e6 µs / 1s = 200%`).
- A new test pinning the CLI's formula (`750_000 µs / 2s = 37.5%`, which
the CLI table prints as `37.50%`).
- The zero-cores clamp test is dropped, since there's no core count any
more.

## Testing

- `swiftlint lint --strict`: clean
- BerthlyTests: 622 passed
- Real daemon (container 1.7.1): a `--cpus 2` alpine container running
two busy loops shows `199.97%` in `container stats` (`cpuUtilization`
1.998). Berthly's formula now gives the same ~200%; before, it gave ~20%
on a 10-core host. No E2E test covers the Overview card's number.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
andrewkomkov added a commit to getgantry/gantry that referenced this pull request Nov 12, 2026
Apple container **1.7.1** is out. The previously tracked version is
`1.6.1`.

Upstream notes: https://github.com/apple/container/releases/tag/1.7.1. A
copy is in `docs/upstream/apple-container-1.7.1.md`.

Most of the 1.7.1 support is already on main from PR #57
(`specs/001-apple-container-1-7-1`) and PR #50 (clusters). This PR adds
no code. It adds the 1.7.1 features to the README and records the live
check in spec 001.

## Review checklist

- [x] New or changed CLI flags Gantry should surface: `cluster run
--shared-image-store` and `--workers count=,cpus=,memory=` came in PR
#50. The `run`, `create`, `machine` and `build` commands have no new
flags in 1.7.1.
- [x] Changed `--format json` shapes the DockerKit apple transport
decodes: only `stats` changed (`cpuUtilization`).
`AppleContainerJSON.statsBody` uses it, with the counter math as
fallback
(`Packages/DockerKit/Sources/DockerKit/AppleContainer/AppleContainerJSON.swift:653`).
The live output matches the test fixture. `container ls --format json`
did not change.
- [x] Fixed upstream bugs Gantry currently works around: none. The
BuildKit fixes (#2428, #2414) need no change in Gantry. The "Builder
image is outdated" card covers the new builder shim 0.13.3
(`AppleBuilderStatus.imageUpdate`).
- [x] `ContainerTooling.recommendedVersion` and feature gates:
`recommendedVersion = "1.7.1"`
(`Packages/AppCore/Sources/AppCore/ContainerTooling.swift:18`). The DNS
defaults are gated on 1.7.0 (`containerDNSDefaultsVersion`, line 46).
- [x] MCP tools and App Intents that expose the affected commands:
`container_stats` uses the same DockerKit decoder. `apple_set_property`
accepts lists for the DNS keys (PR #57). No App Intent shows the changed
commands.
- [x] README and CHANGELOG entries for whatever is adopted: the
CHANGELOG has the #57 and #50 lines. This PR adds the 1.7.1 features to
the README.

## Adopted (on main, checked again on CLI 1.7.1)

- Stats `cpuUtilization` (#2146). The old calculation stays as fallback
for 1.6.1.
- `[container.dns]` defaults in `config.toml` (#1614): a list editor in
System Properties, gated on 1.7.0.
- Recommended kernel (#2447): Gantry has no kernel version of its own.
It runs `system kernel set --recommended`.
- Cluster changes (#2437, #2448, #2451, #2462) came in PR #50. The
notice for missing or stopped cluster services came in PR #57.
- Builder shim 0.13.3: the outdated builder card.

## Not adopted, and why

- #2412 Time Machine exclusion, #2443 containerization 0.54.0, #2458
package size, #2470 copy blobs, #2416 bootstrapper, #2477 test library:
internal changes. Gantry has nothing to show for them.
- #2457, #2459, #2433, #2413: upstream docs and examples only.

## Checks

- `swift test` in DockerKit: 324 tests passed. AppCore
`AppleContainer171` tests: 19 passed.
- `scripts/check-localization.py`: 0 problems in 28 languages. This PR
adds no strings.
- Debug build on CLI 1.7.1: a busy test container shows 98 % CPU. The
CLI reports `cpuUtilization` 1.0 for it.
- The Builder card shows 0.13.2 to 0.13.3 in light and dark mode. System
Properties shows `[container.dns]`. The cluster list shows one row for
each cluster.
- Open (T035 in spec 001): two items had no check in the app. These are
the DNS list editor sheet and the cluster services notice. The editor
needs a click. The notice needs a broken cluster setup.

---

<details><summary>Upstream release notes</summary>

## Highlights

⌨️ denotes breaking CLI changes.

👩‍💻 denotes breaking API changes.

- Core
- [`container stats` now reports `cpuUtilization` in JSON, YAML, and
TOML output](apple/container#2146)
- [Image snapshots and container filesystems are now excluded from Time
Machine backups](apple/container#2412)
- [Default Kata kernel is now 4.3.1
(`vmlinux-6.18.56-208-debug`)](apple/container#2447)
- [Updated Containerization to
0.54.0](apple/container#2443)
- Networking
- [Default DNS nameservers, search domains, and options can now be set
in `config.toml`](apple/container#1614)
- Build
- [Fixed `container build` failures with newer
BuildKit](apple/container#2428) and [missing
build context for steps that need the full
context](apple/container#2414)
- Kubernetes
- ⌨️ [New `--shared-image-store` option on `container cluster run` to
use the `container` image store from cluster nodes; removed the
`load-image` subcommand](apple/container#2437)
- ⌨️ [`container cluster ls` now shows one row per cluster; use
`--nodes` for the per-node
view](apple/container#2451)
- ⌨️ [Container lifecycle commands no longer operate on cluster
nodes](apple/container#2462)
- [Worker node CPU and memory can now be set with `--workers
count=<n>,cpus=<n>,memory=<size>`](apple/container#2448)

## What's Changed
* Send an :authority on the builder gRPC connection by @jglogan in
apple/container#2428
* Adds `container cluster` example. by @jglogan in
apple/container#2433
* Update container-builder-shim to 0.13.3. by @jglogan in
apple/container#2434
* use macos 27 runners by @madrob in
apple/container#2436
* Fix empty followpaths handling in BuildFSSync by @onlyarnav in
apple/container#2414
* Document container clean in the reclaim disk space guide by
@lucasbrito-wdt in apple/container#2413
* Bump to use containerization 0.54.0 by @adityaramani in
apple/container#2443
* feat(stats): report cpuUtilization in the machine-readable formats by
@guanchzhou in apple/container#2146
* [k8s plugin] Create a cluster bootstrapper by @katiewasnothere in
apple/container#2416
* Update recommended kernel to kata 4.3.1 release
vmlinux-6.18.56-208-debug by @katiewasnothere in
apple/container#2447
* Add TOML configuration for default DNS nameservers, search, options by
@0xMH in apple/container#1614
* Add the ability to share container's image store with container
cluster by @crosbymichael in
apple/container#2437
* Reduce install package size and install footprint. by @jglogan in
apple/container#2458
* Add reference to apple/container-examples and remove examples/ out of
this repo by @michaelzhang114 in
apple/container#2457
* Create container-core-clusters XPC service by @adityaramani in
apple/container#2451
* Exclude recreatable container data from Time Machine by @abdullahtas0
in apple/container#2412
* Clean the `cluster-shim` build files with `make clean` by @dkovba in
apple/container#2463
* Quiet the `cluster-shim` build output and show the swift progress in
place by @dkovba in apple/container#2461
* Do not allow high level container lifecycle commands to operate on
cluster nodes by @katiewasnothere in
apple/container#2462
* Switch to copy blobs by @crosbymichael in
apple/container#2470
* Add option to set cpus and memory resources for worker nodes of
cluster by @katiewasnothere in
apple/container#2448
* Removed bug-report-how-to.md as this info is now consolidated in
CONTRIBUTING.md by @michaelzhang114 in
apple/container#2459
* Move HostStoreServer into a library so tests don't link the executable
by @katiewasnothere in apple/container#2477

## New Contributors
* @madrob made their first contribution in
apple/container#2436
* @onlyarnav made their first contribution in
apple/container#2414
* @lucasbrito-wdt made their first contribution in
apple/container#2413
* @abdullahtas0 made their first contribution in
apple/container#2412

**Full Changelog**:
apple/container@1.6.1...1.7.1

</details>

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: andrewkomkov <[email protected]>
@guanchzhou guanchzhou mentioned this pull request Nov 25, 2026
3 of 7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Request]: container stats --format json omits the CPU percentage it already computes

4 participants