Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(progress): the cpu_ms idle bound is asserted on a window the hypervisor did not steal from (the guest bills host steal to the current thread)
garrytan06d9ebd9d6b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6c7d8cd2c..847ac19255 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes- **Flake fix: `test/doctor-pglite-datadir.test.ts` case (c) stages its stale `postmaster.pid` with a provably dead PID.** The case wrote the fixed PID 99999; on a busy gate VM (`pid_max` 4194304) that number can belong to a live process, and the live-postmaster guard in `validatePgliteLayout` then refuses the directory, so the verdict read `unsupported-layout` instead of `wal-corruption-likely` (GBRA-89's finding). The PID now comes from a child that was spawned and reaped (`test/helpers/dead-pid.ts`, the helper four other tests already carried inline). Forced probe (the case writes a live PID, which is what CI saw): 3/3 fail before with exactly that verdict, 16/16 after. The assertion is unchanged.+- **Flake fix: `test/progress.test.ts` asserts its `cpu_ms` idle bound on a window the hypervisor did not steal from.** The case blocks the thread for 200 ms and expects under 100 ms of thread CPU; one CI run billed 268 ms. The guest kernels CI runs on (Ubuntu generic, no `CONFIG_PARAVIRT_TIME_ACCOUNTING`) charge vCPU time the host steals to whichever thread is current, so a steal burst beginning right after the wait wakes lands in that thread's CPU clock; the failing runner had lost 28 % of its CPU to steal over the job. The test now reads the VM-wide steal counter (`/proc/stat`) around the window and re-measures, at most five times, until a window with zero steal; the `< 100` bound is unchanged and is asserted on that window, a machine without `/proc/stat` asserts the first window as before, and the failure message carries the steal per attempt. Nested-VM proof of the mechanism: a guest thread spinning 1,500 ms of wall time under a host CPU quota read 1,500 ms of thread CPU while the guest recorded 1,700 ms of steal; the same quota during an `Atomics.wait` read 1.3 ms. Forced probe (a preload that applies the kernel's observable behaviour, a 268 ms CPU-clock jump plus the matching steal advance, once at the wake): the old test fails 3/3 at 269–271 ms, the fixed test passes 3/3 on its second window, and the control with the same jump and no steal (real work) still fails. `docs/progress-events.md` says `cpu_ms` includes stolen time under such a hypervisor.- **Diagnostic: `test/cli-exit-drain.test.ts` failure messages carry each stream's end state and event order.** One run (38352625321) read 0 of 100 stdout bytes while the exit code and the sibling cases were fine, and the message could not tell a stream closed under its reader from one that ended cleanly empty; it now records `readableEnded`/`destroyed`/`errored` for both streams and the order of `end`, `close` and `exit` events. No assertion changed; the three cases still assert the same bytes.## [0.60.211.0] - 2026-10-13diff --git a/docs/progress-events.md b/docs/progress-events.mdindex 79cd7506cf..8c694ef35e 100644--- a/docs/progress-events.md+++ b/docs/progress-events.md@@ -98,6 +98,10 @@ Fields:gave the CPU to other work, and it excludes work on runtime helper threads(garbage collection, JIT) and in other processes (a Postgres server, aprovider). The scale tier's import-rate gate times PGLite imports with it.+ Under a hypervisor whose guest kernel does not subtract steal time (Ubuntu's+ generic kernels), it also includes vCPU time the host took away while this+ thread was current, so on an oversubscribed VM it can exceed the thread's+ real work.- `total` — total items, if known. Omitted when the scan doesn't have atotal up front (e.g. a streaming iterator).- `pct` — `done/total * 100`, one decimal. Omitted when `total` is unknown.diff --git a/test/progress.test.ts b/test/progress.test.tsindex f2a83857e6..f9440c3a0a 100644--- a/test/progress.test.ts+++ b/test/progress.test.ts@@ -1,5 +1,6 @@import { describe, test, expect } from 'bun:test';import { spawn, type ChildProcessByStdio } from 'node:child_process';+import { readFileSync } from 'node:fs';import { join } from 'node:path';import { PassThrough, type Readable } from 'node:stream';import { createProgress, startHeartbeat, __liveReporterCountForTest, __signalHandlerInstalledForTest } from '../src/core/progress.ts';@@ -150,23 +151,50 @@ describe('progress reporter', () => {});test('json tick cpu_ms counts CPU work since the phase started, not time spent waiting', () => {- const { stream, read } = sink(false);- const p = createProgress({ mode: 'json', stream, minIntervalMs: 0, minItems: 1 });- p.start('import.files', 3);+ // Under a hypervisor whose guest kernel lacks CONFIG_PARAVIRT_TIME_ACCOUNTING (Ubuntu's generic kernels, the CI+ // runners included), vCPU time the host steals is billed to whichever thread was current, so a steal burst that+ // starts right after the wait wakes lands in this thread's CPU clock (run 38467234783: 268 ms billed inside a+ // 200 ms wait on a runner with 28 % steal). Such a window is an invalid instrument reading, not CPU work: the+ // measurement is repeated until the VM-wide steal counter did not move across it, and the bound below is+ // asserted only on that window. Without /proc/stat (macOS) the first window is asserted as before.+ const stealJiffies = (): number | null => {+ try {+ const cpuLine = readFileSync('/proc/stat', 'utf8').split('\n')[0] ?? '';+ const fields = cpuLine.trim().split(/\s+/);+ return fields[0] === 'cpu' && fields.length > 8 ? Number(fields[8]) : null;+ } catch {+ return null;+ }+ };const cpuMs = () => { const u = process.threadCpuUsage(); return (u.user + u.system) / 1000; };- const spinUntil = cpuMs() + 60;- while (cpuMs() < spinUntil) { /* burn 60 ms of CPU */ }- p.tick(1);- const usageBefore = process.resourceUsage();- const cpuBeforeWait = cpuMs();- // Block the thread for 200 ms without yielding: an await would let other queued main-thread work (an earlier- // test's timer, a GC pause) run and be billed to the phase, and the test means "the thread sat idle".- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);- const cpuInWait = cpuMs() - cpuBeforeWait;- const usageAfter = process.resourceUsage();- p.tick(1);- p.finish();- const [, worked, waited] = parseJsonl(read()) as Array<{ cpu_ms: number; elapsed_ms: number }>;+ const measure = () => {+ const { stream, read } = sink(false);+ const p = createProgress({ mode: 'json', stream, minIntervalMs: 0, minItems: 1 });+ p.start('import.files', 3);+ const spinUntil = cpuMs() + 60;+ while (cpuMs() < spinUntil) { /* burn 60 ms of CPU */ }+ p.tick(1);+ const stealBefore = stealJiffies();+ const usageBefore = process.resourceUsage();+ const cpuBeforeWait = cpuMs();+ // Block the thread for 200 ms without yielding: an await would let other queued main-thread work (an earlier+ // test's timer, a GC pause) run and be billed to the phase, and the test means "the thread sat idle".+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);+ const cpuInWait = cpuMs() - cpuBeforeWait;+ const usageAfter = process.resourceUsage();+ p.tick(1);+ p.finish();+ const stealAfter = stealJiffies();+ const [, worked, waited] = parseJsonl(read()) as Array<{ cpu_ms: number; elapsed_ms: number }>;+ const stealMs = stealBefore === null || stealAfter === null ? null : (stealAfter - stealBefore) * 10;+ return { worked, waited, cpuInWait, usageBefore, usageAfter, stealMs };+ };+ const attempts: ReturnType<typeof measure>[] = [];+ for (let attempt = 0; attempt < 5; attempt++) {+ attempts.push(measure());+ if (attempts[attempts.length - 1]!.stealMs === null || attempts[attempts.length - 1]!.stealMs === 0) break;+ }+ const { worked, waited, cpuInWait, usageBefore, usageAfter, stealMs } = attempts[attempts.length - 1]!;expect(worked.cpu_ms).toBeGreaterThanOrEqual(60);expect(waited.elapsed_ms - worked.elapsed_ms).toBeGreaterThanOrEqual(190);const waitedCpuMs = waited.cpu_ms - worked.cpu_ms;@@ -177,7 +205,9 @@ describe('progress reporter', () => {`process during the wait: ${usageAfter.minorPageFault - usageBefore.minorPageFault} minor and ` +`${usageAfter.majorPageFault - usageBefore.majorPageFault} major page faults, ` +`${usageAfter.involuntaryContextSwitches - usageBefore.involuntaryContextSwitches} involuntary context switches, ` +- `${((usageAfter.userCPUTime + usageAfter.systemCPUTime - usageBefore.userCPUTime - usageBefore.systemCPUTime) / 1000).toFixed(1)} ms CPU on all threads`,+ `${((usageAfter.userCPUTime + usageAfter.systemCPUTime - usageBefore.userCPUTime - usageBefore.systemCPUTime) / 1000).toFixed(1)} ms CPU on all threads; ` ++ `hypervisor steal across the window: ${stealMs === null ? 'unknown (no /proc/stat)' : `${stealMs} ms`}` ++ `${attempts.length > 1 ? ` (attempt ${attempts.length} of 5; steal per attempt: ${attempts.map((a) => `${a.stealMs} ms`).join(', ')})` : ''}`,).toBeLessThan(100);});