Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: loop-lag bounds read the thread's CPU, not the wall clock (sync-pass-shared-budget-6712 flake)
garrytane4ec4528ee15
diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.tsindex 1492e18c56..cf5f39b32e 100644--- a/test/helpers/cpu-time.ts+++ b/test/helpers/cpu-time.ts@@ -1,3 +1,28 @@+/** The calling thread's CPU time, in milliseconds from an arbitrary origin. */+export function threadCpuNow(): number {+ const used = process.threadCpuUsage();+ return (used.user + used.system) / 1000;+}++/** A synchronous stretch of `ms` of thread CPU: work a loaded VM can delay but not lengthen or shorten. */+export function spinCpuMs(ms: number): void {+ const end = threadCpuNow() + ms;+ while (threadCpuNow() < end) { /* a stretch the loop cannot break */ }+}++/**+ * Event-loop lag as the thread's own work: the most CPU the calling thread ran between two runs of a `intervalMs`+ * timer (and after the last one, when `stop` is called). A bound on it measures how long code held the loop. Wall+ * time between ticks also counts what a loaded VM adds while the thread is off the CPU: run-queue waits, and sleeps+ * on a starved helper thread or on a spawned child that has not reached exec yet. On a 4-vCPU CI shard a 60 ms+ * stretch read 133 ms that way (#6712 PR 4b, test/sync-pass-shared-budget-6712.test.ts).+ */+export function watchLoopLag(intervalMs = 5): { stop(): { maxLag: number; ticks: number } } {+ let last = threadCpuNow(), maxLag = 0, ticks = 0;+ const timer = setInterval(() => { const now = threadCpuNow(); maxLag = Math.max(maxLag, now - last); last = now; ticks++; }, intervalMs);+ return { stop: () => { clearInterval(timer); return { maxLag: Math.max(maxLag, threadCpuNow() - last), ticks }; } };+}+/*** CPU time of a synchronous call on the calling thread, in milliseconds. A bound or scaling ratio over CPU time* measures the work rather than how long the scheduler made it wait, so load on a shared CI VM does not move it.diff --git a/test/loop-lag-cpu-clock.test.ts b/test/loop-lag-cpu-clock.test.tsnew file mode 100644index 0000000000..5a23aeb066--- /dev/null+++ b/test/loop-lag-cpu-clock.test.ts@@ -0,0 +1,42 @@+/**+ * #6712 PR 4b flake: the loop-lag bounds (test/sync-pass-shared-budget-6712.test.ts, test/sync-pass-loop-lag-6712.test.ts)+ * read wall time between timer runs, so a loaded CI VM that kept the thread off the CPU counted as code holding the loop:+ * a forced 60 ms stretch read 133 ms against the 100 ms bound on a 4-vCPU shard. Pinned to one core with three CPU hogs,+ * the shared-budget test read 156-257 ms; per-gap schedstat showed the excess as run-queue wait plus sleeps behind a+ * spawned Git that had not reached exec, with the thread's own CPU at 61-69 ms. `watchLoopLag` reads the thread's CPU.+ *+ * Forced probe (deterministic): the thread sleeps 150 ms with a timer due (`Atomics.wait`, as it does on a run queue+ * or behind a child's exec). The wall clock reads it as 150 ms of lag; the CPU clock does not. The CPU clock still sees a+ * stretch of work, and two stretches in one turn, the regression the bounds exist to catch.+ */+import { expect, test } from 'bun:test';+import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';++/** The bound the loop-lag tests hold. */+const MAX_LAG_MS = 100;+const turn = () => new Promise<void>(resolve => setTimeout(resolve, 20));+const offCpu = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);++test('a thread kept off the CPU with a timer due is not lag; the wall clock reads it as lag', async () => {+ const lag = watchLoopLag();+ let last = performance.now(), wallLag = 0;+ const wall = setInterval(() => { const now = performance.now(); wallLag = Math.max(wallLag, now - last - 5); last = now; }, 5);+ await turn();+ offCpu(150);+ await turn();+ clearInterval(wall);+ expect(Math.round(wallLag)).toBeGreaterThanOrEqual(MAX_LAG_MS + 40);+ expect(Math.round(lag.stop().maxLag)).toBeLessThan(MAX_LAG_MS);+});++test('a stretch of work is lag on the CPU clock, and two stretches in one turn add up', async () => {+ const one = watchLoopLag();+ await turn(); spinCpuMs(60); await turn();+ const single = one.stop();+ expect(single.ticks).toBeGreaterThan(0);+ expect(Math.round(single.maxLag)).toBeGreaterThanOrEqual(60);+ expect(Math.round(single.maxLag)).toBeLessThan(MAX_LAG_MS);+ const two = watchLoopLag();+ await turn(); spinCpuMs(60); spinCpuMs(60); await turn();+ expect(Math.round(two.stop().maxLag)).toBeGreaterThanOrEqual(120);+});diff --git a/test/sync-pass-loop-lag-6712.test.ts b/test/sync-pass-loop-lag-6712.test.tsindex 9cbd989b53..900d33b0ab 100644--- a/test/sync-pass-loop-lag-6712.test.ts+++ b/test/sync-pass-loop-lag-6712.test.ts@@ -12,6 +12,7 @@ import { describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { watchLoopLag } from './helpers/cpu-time.ts';import { managedBrain } from './helpers/managed-brain.ts';const PATHS = 60_000;@@ -34,16 +35,15 @@ describe('#6712 PR 4b ruling 4: a level read yields to the event loop', () => {test(`reading and classifying a ${PATHS}-path level never blocks a timer for ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {// A pass resolves its context once, before its rounds; each round's level read is what this times.const context = await resolveManagedSyncContext(engine, { sourceId: 'default', noPull: true, dryRun: true });- let last = performance.now(), maxLag = 0, ticks = 0;- const timer = setInterval(() => { const now = performance.now(); maxLag = Math.max(maxLag, now - last - 5); last = now; ticks++; }, 5);+ // Lag as the thread's own CPU between timer runs (the stretch that ends the read counts too): the stretches the read+ // holds, not what a loaded VM adds while the thread is off the CPU.let level: Awaited<ReturnType<typeof readShadowLevel>>;+ let maxLag = 0, ticks = 0;+ const lag = watchLoopLag();try {- last = performance.now();level = await readShadowLevel(engine, { sourceId: 'default', context });} finally {- // The stretch that ends the read counts too: the timer never got to fire after it.- maxLag = Math.max(maxLag, performance.now() - last - 5);- clearInterval(timer);+ ({ maxLag, ticks } = lag.stop());}expect(level!.paths.length).toBe(PATHS);expect(ticks).toBeGreaterThan(0);diff --git a/test/sync-pass-shared-budget-6712.test.ts b/test/sync-pass-shared-budget-6712.test.tsindex 97f7664b1b..d15c84efb5 100644--- a/test/sync-pass-shared-budget-6712.test.ts+++ b/test/sync-pass-shared-budget-6712.test.ts@@ -25,6 +25,7 @@ import { readIndexLevel } from '../src/core/persistence/sync-git-stream.ts';import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';import { managedBrain } from './helpers/managed-brain.ts';import { testBackends } from './helpers/test-backends.ts';@@ -40,7 +41,6 @@ const setup = ({ root }: { root: string }) => {for (let i = 0; i < NOTES; i++) writeFileSync(join(root, `notes/n${i}.md`), `---\ntype: concept\ntitle: notes/n${i}\n---\n\nNote ${i}.\n`);git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');};-const busy = (ms: number) => { const end = performance.now() + ms; while (performance.now() < end) { /* a stretch the loop cannot break */ } };afterEach(() => installFaultHook(undefined));@@ -64,19 +64,18 @@ for (const backend of testBackends()) {const chunk = new Promise<void>(resolve => { open = resolve; });const seen = { chunk: false, result: false, take: false };installFaultHook(async (point, detail) => {- if (point === 'sync:level_chunk' && detail.read === 'ls-files' && !seen.chunk) { seen.chunk = true; open(); busy(STRETCH_MS); }+ if (point === 'sync:level_chunk' && detail.read === 'ls-files' && !seen.chunk) { seen.chunk = true; open(); spinCpuMs(STRETCH_MS); }if (point === 'sync:level_result' && !seen.result) { seen.result = true; await Promise.race([chunk, new Promise(resolve => setTimeout(resolve, 10_000))]); }- if (point === 'sync:level_take' && !seen.take) { seen.take = true; busy(STRETCH_MS); }+ if (point === 'sync:level_take' && !seen.take) { seen.take = true; spinCpuMs(STRETCH_MS); }});- let last = performance.now(), maxLag = 0;- const timer = setInterval(() => { const now = performance.now(); maxLag = Math.max(maxLag, now - last - 5); last = now; }, 5);+ // Lag as the thread's own CPU between timer runs: the stretches the read holds, not what a loaded VM adds.let level: Awaited<ReturnType<typeof readShadowLevel>>;+ let maxLag = 0;+ const lag = watchLoopLag();try {- last = performance.now();level = await readShadowLevel(engine, { sourceId: 'default', context });} finally {- maxLag = Math.max(maxLag, performance.now() - last - 5);- clearInterval(timer);+ maxLag = lag.stop().maxLag;installFaultHook(undefined);}expect(seen).toEqual({ chunk: true, result: true, take: true });