Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Calibrate native CPU sampling with the Mach timebase (#551)

Dee7c3d6315ce86
diff --git a/desktop/tool/native_benchmark/README.md b/desktop/tool/native_benchmark/README.md
index a40fccbbc..1b60c292a 100644
--- a/desktop/tool/native_benchmark/README.md
+++ b/desktop/tool/native_benchmark/README.md
@@ -56,6 +56,26 @@ Use the PID in the completed result's metadata. Hide the fixture through the app
normal controls and repeat with a new label/file for background idle. This sampler
reads `proc_pid_rusage` once per second: CPU deltas (100% means one core), physical
memory footprint, resident memory, interrupt/package-idle wakeups, and disk I/O.
+CPU counters are [Mach absolute ticks](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/task.c#L6391),
+converted with `mach_timebase_info`.
+Schema 2 records the raw ticks, timebase and process birth stamp; a replaced
+process fails the sample. Earlier schema 1 CPU percentages and seconds omitted
+that conversion and are invalid on machines whose timebase is not 1:1. Do not
+reuse them without the original machine's clock metadata. Memory, wakeup and
+disk counters use separate units and are unaffected.
+
+Calibrate the sampler before interpreting CPU results:
+
+```sh
+python3 tool/native_benchmark/test_process_usage.py
+```
+
+This compiles the sampler and compares a private busy worker against Python's
+independent `getrusage` CPU accounting. It also checks idle CPU and preservation
+of existing output, including a file created during sampling. It does not start
+or control any app or agent. The [October 1 calibration](../../../docs/performance/2026-10-01-resource-sampler-calibration.json)
+records the original failure and corrected measurements.
+
It does not control windows. Its totals cover that process, excluding daemon,
agent processes, and GPU energy. The fixture has no real network connections, so
its background cost cannot establish that the connected product has zero timers
diff --git a/desktop/tool/native_benchmark/process_usage.swift b/desktop/tool/native_benchmark/process_usage.swift
index 857bdad0f..7fc373f98 100644
--- a/desktop/tool/native_benchmark/process_usage.swift
+++ b/desktop/tool/native_benchmark/process_usage.swift
@@ -20,8 +20,9 @@ guard !FileManager.default.fileExists(atPath: args[4]) else {
struct Sample: Codable {
let elapsedSeconds: Double
- let userNanoseconds: UInt64
- let systemNanoseconds: UInt64
+ let processStartMachTicks: UInt64
+ let userMachTicks: UInt64
+ let systemMachTicks: UInt64
let physicalFootprintBytes: UInt64
let residentBytes: UInt64
let interruptWakeups: UInt64
@@ -30,6 +31,13 @@ struct Sample: Codable {
let diskWriteBytes: UInt64
}
+// proc_pid_rusage exposes task CPU time in Mach absolute ticks. On this
+// Apple Silicon host one tick is 125/3 ns; treating ticks as ns understated
+// CPU by 41.67x. Retain both the raw counters and their clock conversion.
+var timebase = mach_timebase_info_data_t()
+guard mach_timebase_info(&timebase) == KERN_SUCCESS, timebase.denom > 0 else {
+ fail("Could not read the Mach clock timebase")
+}
let began = ProcessInfo.processInfo.systemUptime
let startedAt = ISO8601DateFormatter().string(from: Date())
func sample() -> Sample {
@@ -42,8 +50,9 @@ func sample() -> Sample {
guard status == 0 else { fail("proc_pid_rusage failed (errno \(errno)); process may have exited") }
return Sample(
elapsedSeconds: ProcessInfo.processInfo.systemUptime - began,
- userNanoseconds: usage.ri_user_time,
- systemNanoseconds: usage.ri_system_time,
+ processStartMachTicks: usage.ri_proc_start_abstime,
+ userMachTicks: usage.ri_user_time,
+ systemMachTicks: usage.ri_system_time,
physicalFootprintBytes: usage.ri_phys_footprint,
residentBytes: usage.ri_resident_size,
interruptWakeups: usage.ri_interrupt_wkups,
@@ -53,16 +62,25 @@ func sample() -> Sample {
}
var samples = [sample()]
+FileHandle.standardError.write(Data("Sampling process \(target) for \(seconds) seconds\n".utf8))
for tick in 1...seconds {
let remaining = began + Double(tick) - ProcessInfo.processInfo.systemUptime
if remaining > 0 { Thread.sleep(forTimeInterval: remaining) }
- samples.append(sample())
+ let current = sample()
+ let previous = samples.last!
+ guard current.processStartMachTicks == previous.processStartMachTicks,
+ current.userMachTicks >= previous.userMachTicks,
+ current.systemMachTicks >= previous.systemMachTicks else {
+ fail("Process identity or CPU counters changed during sampling")
+ }
+ samples.append(current)
}
let first = samples.first!
let last = samples.last!
let elapsed = last.elapsedSeconds - first.elapsedSeconds
-let cpuSeconds = Double(last.userNanoseconds - first.userNanoseconds
- + last.systemNanoseconds - first.systemNanoseconds) / 1_000_000_000
+let cpuTicks = Double(last.userMachTicks - first.userMachTicks)
+ + Double(last.systemMachTicks - first.systemMachTicks)
+let cpuSeconds = cpuTicks * Double(timebase.numer) / Double(timebase.denom) / 1_000_000_000
let footprints = samples.map { Double($0.physicalFootprintBytes) / 1_048_576 }.sorted()
let summary: [String: Any] = [
"elapsedSeconds": elapsed,
@@ -79,16 +97,26 @@ let summary: [String: Any] = [
]
let encodedSamples = try JSONEncoder().encode(samples)
let output: [String: Any] = [
- "schema": 1, "success": true, "label": args[3], "pid": target,
+ "schema": 2, "success": true, "label": args[3], "pid": target,
"startedAt": startedAt, "os": ProcessInfo.processInfo.operatingSystemVersionString,
- "boundary": "proc_pid_rusage for this process only; CPU 100% = one core; excludes daemon, agents, and GPU energy",
+ "boundary": "proc_pid_rusage for this process only; CPU 100% = one core; excludes other processes and GPU energy",
+ "cpuClock": ["unit": "mach_absolute_time", "timebaseNumer": timebase.numer, "timebaseDenom": timebase.denom] as [String: Any],
"sampleIntervalSeconds": 1, "summary": summary,
"samples": try JSONSerialization.jsonObject(with: encodedSamples),
]
let data = try JSONSerialization.data(withJSONObject: output, options: [.prettyPrinted, .sortedKeys])
-guard FileManager.default.createFile(atPath: args[4], contents: data,
- attributes: [.posixPermissions: 0o600]) else {
- fail("Could not write result")
+// Another sample may have chosen this filename after our startup check.
+// Reserve it exclusively, so completing later cannot overwrite its evidence.
+let descriptor = open(args[4], O_WRONLY | O_CREAT | O_EXCL, mode_t(0o600))
+guard descriptor >= 0 else {
+ fail("Could not create fresh output (errno \(errno)); existing evidence is preserved")
+}
+let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
+do {
+ try handle.write(contentsOf: data)
+ try handle.close()
+} catch {
+ fail("Could not write result: \(error)")
}
let summaryData = try JSONSerialization.data(withJSONObject: summary, options: [.sortedKeys])
print(String(data: summaryData, encoding: .utf8)!)
diff --git a/desktop/tool/native_benchmark/test_process_usage.py b/desktop/tool/native_benchmark/test_process_usage.py
new file mode 100644
index 000000000..62036e701
--- /dev/null
+++ b/desktop/tool/native_benchmark/test_process_usage.py
@@ -0,0 +1,143 @@
+"""Calibrate the macOS sampler against an independent getrusage CPU counter.
+
+Runs only private Python workers; no app, agent, or existing process is controlled.
+Run: python3 tool/native_benchmark/test_process_usage.py
+"""
+import json
+import os
+from pathlib import Path
+import select
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+SAMPLER_SOURCE = Path(__file__).with_name("process_usage.swift")
+WORKER = r"""
+import json, resource, sys, time
+sys.stdin.readline() # Start only after the sampler has its first counter.
+before = resource.getrusage(resource.RUSAGE_SELF)
+start = time.monotonic()
+if sys.argv[1] == 'busy':
+ while time.monotonic() - start < 3:
+ pass
+else:
+ time.sleep(3)
+after = resource.getrusage(resource.RUSAGE_SELF)
+print(json.dumps({
+ 'cpuSeconds': after.ru_utime + after.ru_stime - before.ru_utime - before.ru_stime,
+ 'workWallSeconds': time.monotonic() - start,
+}), flush=True)
+sys.stdin.read() # Stay alive until the sampler finishes.
+"""
+
+
[email protected](sys.platform == "darwin", "proc_pid_rusage is macOS-only")
+class ProcessUsageTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.temp = tempfile.TemporaryDirectory(prefix="harness-resource-calibration-")
+ cls.root = Path(cls.temp.name)
+ cls.sampler = cls.root / "process-usage"
+ subprocess.run(
+ ["xcrun", "swiftc", str(SAMPLER_SOURCE), "-o", str(cls.sampler)],
+ check=True, capture_output=True, text=True, timeout=60,
+ )
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.temp.cleanup()
+
+ def measure(self, mode):
+ output = self.root / f"{mode}.json"
+ worker = subprocess.Popen(
+ [sys.executable, "-u", "-c", WORKER, mode],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True,
+ )
+ sampler = subprocess.Popen(
+ [str(self.sampler), str(worker.pid), "5", mode, str(output)],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ try:
+ self.wait_for_start(sampler)
+ worker.stdin.write("start\n")
+ worker.stdin.flush()
+ _, sampler_error = sampler.communicate(timeout=12)
+ self.assertEqual(sampler.returncode, 0, sampler_error)
+ stdout, stderr = worker.communicate(timeout=5)
+ self.assertEqual(worker.returncode, 0, stderr)
+ independent = json.loads(stdout)
+ measured = json.loads(output.read_text())
+ self.assertEqual(output.stat().st_mode & 0o777, 0o600)
+ print(json.dumps({"mode": mode, "independent": independent,
+ "measured": measured["summary"],
+ "cpuClock": measured.get("cpuClock")}), flush=True)
+ return independent, measured
+ finally:
+ if sampler.poll() is None:
+ sampler.kill()
+ sampler.communicate(timeout=5)
+ if worker.poll() is None:
+ worker.kill()
+ worker.communicate(timeout=5)
+
+ def wait_for_start(self, sampler):
+ readable, _, _ = select.select([sampler.stderr], [], [], 5)
+ self.assertTrue(readable, "Sampler did not confirm its first counter")
+ self.assertTrue(sampler.stderr.readline().startswith("Sampling process "))
+
+ def test_busy_cpu_matches_getrusage(self):
+ independent, measured = self.measure("busy")
+ actual = independent["cpuSeconds"]
+ self.assertGreater(actual, 0.5, "Host must permit a useful calibration workload")
+ # Allow worker startup and small differences at the sampling boundary.
+ # This compares independent kernel APIs, not the sampler's own conversion.
+ self.assertAlmostEqual(measured["summary"]["cpuSeconds"], actual,
+ delta=max(0.05, actual * 0.1))
+ self.assertEqual(measured["schema"], 2)
+ self.assertEqual(measured["cpuClock"]["unit"], "mach_absolute_time")
+ self.assertGreater(measured["cpuClock"]["timebaseDenom"], 0)
+ self.assertTrue(all(sample["processStartMachTicks"] ==
+ measured["samples"][0]["processStartMachTicks"]
+ for sample in measured["samples"]))
+ self.assertNotIn("userNanoseconds", measured["samples"][0])
+
+ def test_sleeping_worker_has_little_cpu(self):
+ independent, measured = self.measure("idle")
+ self.assertLess(independent["cpuSeconds"], 0.05)
+ self.assertLess(measured["summary"]["cpuSeconds"], 0.2)
+
+ def test_existing_output_is_preserved(self):
+ output = self.root / "preserved.json"
+ output.write_text("existing evidence\n")
+ result = subprocess.run(
+ [str(self.sampler), str(os.getpid()), "5", "existing", str(output)],
+ capture_output=True, text=True, timeout=5,
+ )
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Output already exists", result.stderr)
+ self.assertEqual(output.read_text(), "existing evidence\n")
+
+ def test_output_created_during_sampling_is_preserved(self):
+ output = self.root / "concurrent.json"
+ sampler = subprocess.Popen(
+ [str(self.sampler), str(os.getpid()), "5", "concurrent", str(output)],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ try:
+ self.wait_for_start(sampler)
+ output.write_text("other sample's evidence\n")
+ _, stderr = sampler.communicate(timeout=8)
+ self.assertNotEqual(sampler.returncode, 0)
+ self.assertIn("existing evidence is preserved", stderr)
+ self.assertEqual(output.read_text(), "other sample's evidence\n")
+ finally:
+ if sampler.poll() is None:
+ sampler.kill()
+ sampler.communicate(timeout=5)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/docs/performance/2026-09-23-core-experiences.md b/docs/performance/2026-09-23-core-experiences.md
index 7bde13ae1..20c064ccf 100644
--- a/docs/performance/2026-09-23-core-experiences.md
+++ b/docs/performance/2026-09-23-core-experiences.md
@@ -160,22 +160,33 @@ is consistently fast.
## Desktop process resources
+**CPU correction, October 1:** the original sampler treated Mach CPU ticks as
+nanoseconds. A controlled workload on the current Apple Silicon host showed
+0.072 seconds reported for 2.998 seconds of CPU work (a 125/3 clock scale).
+The CPU figures previously in this table are withdrawn. Those older files did
+not record their timebase, so no retrospective CPU estimates are substituted.
+Raw artifacts remain intact; memory, wakeup, disk and interaction-timing
+measurements use independent counters and are unaffected. The corrected sampler
+records its clock and has an independent native calibration test; the
+[calibration evidence](2026-10-01-resource-sampler-calibration.json) includes the
+original failure and corrected results.
+
Each row is one 30-second sample after the timing sweep. Memory is the median
-physical footprint; CPU 100% means one core. Foreground fixtures were activated
+physical footprint. Foreground fixtures were activated
through application controls; background fixtures were explicitly hidden. These
are snapshots, not a memory-leak study. The one-terminal process remained idle
longer before sampling than the other fixtures.
-| Fixture / state | CPU, one core | Footprint median / peak | Interrupt wakeups/s |
-|---|---:|---:|---:|
-| core-1-background-idle | 0.08% | 217.3 / 223.7 MiB | 12.1 |
-| core-1-foreground-idle | 0.08% | 212.8 / 223.5 MiB | 11.5 |
-| core-16-background-idle | 0.10% | 306.1 / 311.5 MiB | 13.8 |
-| core-16-foreground-idle | 0.09% | 304.4 / 311.4 MiB | 12.9 |
-| core-16-full-background-output | 1.79% | 960.3 / 970.2 MiB | 180.1 |
-| core-16-full-foreground-output | 1.28% | 956.7 / 968.0 MiB | 140.6 |
-| core-48-background-idle | 0.08% | 558.5 / 564.0 MiB | 13.5 |
-| core-48-foreground-idle | 0.10% | 559.2 / 596.1 MiB | 16.0 |
+| Fixture / state | Footprint median / peak | Interrupt wakeups/s |
+|---|---:|---:|
+| core-1-background-idle | 217.3 / 223.7 MiB | 12.1 |
+| core-1-foreground-idle | 212.8 / 223.5 MiB | 11.5 |
+| core-16-background-idle | 306.1 / 311.5 MiB | 13.8 |
+| core-16-foreground-idle | 304.4 / 311.4 MiB | 12.9 |
+| core-16-full-background-output | 960.3 / 970.2 MiB | 180.1 |
+| core-16-full-foreground-output | 956.7 / 968.0 MiB | 140.6 |
+| core-48-background-idle | 558.5 / 564.0 MiB | 13.5 |
+| core-48-foreground-idle | 559.2 / 596.1 MiB | 16.0 |
The **212.8 MiB** one-terminal foreground result is entirely the desktop fixture
process. It includes the app, terminal parsing/rendering, scrollback, and benchmark
@@ -365,8 +376,8 @@ them, but its 30 samples per action are insufficient for a stable p99.
The full-scrollback streaming resource sample includes the 20 Hz producer and a
ten-second diagnostic counter write. Its [load counters](2026-09-23-data/full-scrollback-resource-load.json)
record actual decoded bytes and elapsed time. The idle fixtures have neither
-producer nor diagnostic timer. Comparing their CPU percentages therefore
-compares different workloads; it is not a before/after optimization result.
+producer nor diagnostic timer. Even with a corrected CPU sampler, comparing
+these states compares different workloads; it is not a before/after optimization result.
Remote typing depends on the route. A reported `p2p` mode is the daemon's label;
we did not collect the ICE candidate pair and cannot infer that it was a direct
diff --git a/docs/performance/2026-10-01-resource-sampler-calibration.json b/docs/performance/2026-10-01-resource-sampler-calibration.json
new file mode 100644
index 000000000..0e254acf4
--- /dev/null
+++ b/docs/performance/2026-10-01-resource-sampler-calibration.json
@@ -0,0 +1,103 @@
+{
+ "schema": 1,
+ "recordedAt": "2026-10-01T14:25:16.810358+00:00",
+ "platform": {
+ "system": "Darwin",
+ "version": "26.6.2",
+ "machine": "arm64"
+ },
+ "baselineCommit": "6ad3c2077ebfcf2f2b87f319ca42600a3ef56b5b",
+ "correctedSourceSha256": "996bdaef9acb5d7a1214cdabe309052178923a8a651259dcbab44c768f3c8541",
+ "scope": "Native measurement-tool calibration only; no app performance improvement is claimed. Independent CPU is Python getrusage for its measured work; the sampler interval may also include worker startup.",
+ "before": [
+ {
+ "mode": "busy",
+ "independent": {
+ "cpuSeconds": 2.9652439999999998,
+ "workWallSeconds": 3.000027707996196
+ },
+ "measured": {
+ "cpuPercentOneCore": 1.4230064170113295,
+ "cpuSeconds": 0.071171695,
+ "diskReadBytes": 0,
+ "diskWriteBytes": 0,
+ "elapsedSeconds": 5.001502041675849,
+ "interruptWakeupsPerSecond": 0,
+ "packageIdleWakeupsPerSecond": 0,
+ "physicalFootprintMiBEnd": 6.969207763671875,
+ "physicalFootprintMiBMedian": 6.969207763671875,
+ "physicalFootprintMiBPeak": 6.969207763671875,
+ "physicalFootprintMiBStart": 6.969207763671875
+ },
+ "cpuClock": null
+ }
+ ],
+ "after": [
+ {
+ "mode": "busy",
+ "independent": {
+ "cpuSeconds": 2.9960419999999996,
+ "workWallSeconds": 3.0000122919882415
+ },
+ "measured": {
+ "cpuPercentOneCore": 59.91842945300833,
+ "cpuSeconds": 2.99612175,
+ "diskReadBytes": 0,
+ "diskWriteBytes": 0,
+ "elapsedSeconds": 5.000334249998559,
+ "interruptWakeupsPerSecond": 0,
+ "packageIdleWakeupsPerSecond": 0,
+ "physicalFootprintMiBEnd": 6.891059875488281,
+ "physicalFootprintMiBMedian": 6.891059875488281,
+ "physicalFootprintMiBPeak": 6.891059875488281,
+ "physicalFootprintMiBStart": 6.891059875488281
+ },
+ "cpuClock": {
+ "timebaseDenom": 3,
+ "timebaseNumer": 125,
+ "unit": "mach_absolute_time"
+ }
+ },
+ {
+ "mode": "idle",
+ "independent": {
+ "cpuSeconds": 4.4999999999999034e-05,
+ "workWallSeconds": 3.0050897499895655
+ },
+ "measured": {
+ "cpuPercentOneCore": 0.27397346293193237,
+ "cpuSeconds": 0.01370725,
+ "diskReadBytes": 0,
+ "diskWriteBytes": 0,
+ "elapsedSeconds": 5.003130541663268,
+ "interruptWakeupsPerSecond": 0.19987485668674052,
+ "packageIdleWakeupsPerSecond": 0,
+ "physicalFootprintMiBEnd": 6.875434875488281,
+ "physicalFootprintMiBMedian": 6.875434875488281,
+ "physicalFootprintMiBPeak": 6.875434875488281,
+ "physicalFootprintMiBStart": 0.2188873291015625
+ },
+ "cpuClock": {
+ "timebaseDenom": 3,
+ "timebaseNumer": 125,
+ "unit": "mach_absolute_time"
+ }
+ }
+ ],
+ "validation": {
+ "originalFailsSameBusyCalibration": true,
+ "correctedTestsPassed": 4,
+ "covers": [
+ "CPU agreement with independent getrusage",
+ "sleeping-worker CPU",
+ "existing-output preservation",
+ "concurrent-output preservation",
+ "schema 2 clock and process-birth metadata",
+ "output permissions 0600"
+ ],
+ "originalRegressionTestsFailAsExpected": 2,
+ "workloadStart": "Worker begins only after the sampler reports its first counter; no fixed startup sleep."
+ },
+ "historicalPolicy": "Preserve older raw artifacts; withdraw old CPU percentages without recorded timebase rather than guessing a conversion.",
+ "baselineAdaptation": "Only a stderr readiness marker was added to the original sampler so the controlled worker could wait for its first counter. Its original CPU calculation and output writer were preserved."
+}