From 732b1cdf31a72cf29bf285d3697235947223a900 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 09:02:05 +0000 Subject: [PATCH 1/2] test(ui-sdk,ui-backend-claude,ui-react): replace slice-4 real-time waits with deterministic signals (#3332) - worker-steps-event-loop: hold the status request open instead of sleeping 150 ms and 200 ms around a lost supervisor. - maintenance-worker-kill-child: the non-leader thread reports running for two counted polls instead of until a 10 ms timer. - Claude worker-cleanup and worker-stdio-release: observe the state handle's real close, or poll for the release request, then one macrotask, instead of 20-50 ms windows. - ui-react runtime-hook-phases: wait for the exit and stderr records instead of 20 ms. - State in source why native-identity-inspector, geo routing and the zero-delay heartbeat timers keep real time. Refs #3332 Co-Authored-By: Claude Opus 5.5 --- packages/geo/tests/routing.test.ts | 7 +++- .../tests/worker-cleanup.test.ts | 12 +++++-- .../tests/worker-stdio-release.test.ts | 8 +++-- .../tests/runtime-hook-phases.test.ts | 6 +++- .../tests/maintenance-worker-kill-child.ts | 16 +++++---- .../tests/native-identity-inspector.test.ts | 3 ++ .../tests/worker-steps-event-loop.test.ts | 33 +++++++++++-------- 7 files changed, 59 insertions(+), 26 deletions(-) diff --git a/packages/geo/tests/routing.test.ts b/packages/geo/tests/routing.test.ts index cf74b3ecfe..c8f2eea258 100644 --- a/packages/geo/tests/routing.test.ts +++ b/packages/geo/tests/routing.test.ts @@ -26,7 +26,12 @@ const footDemo="https://routing.openstreetmap.de/routed-foot/route/v1"; const footUrls=[dataset("foot").url,footDemo].map(endpoint=>endpoint+ "/driving/20.71,38.36;20.72,38.37?geometries=geojson&overview=full&steps=false&alternatives=false"); -/** Instance-local latency observation; retain the real fsync/rename writer. */ +/** + * Instance-local latency observation; retain the real fsync/rename writer. + * Kept real time (#3332): the second admission write runs after dispatch, while + * the transport's real deadline timer is armed, so the latency itself is the + * stimulus. A barrier would order the steps but spend none of that deadline. + */ function delayAdmissionWrites(geo: GeoClient, delayMs: number, admissionDir: string) { const instrumented = (geo as unknown as {transport: {writeAtomic(path: string, value: unknown): Promise}}).transport; const original = instrumented.writeAtomic; diff --git a/packages/ui-backend-claude/tests/worker-cleanup.test.ts b/packages/ui-backend-claude/tests/worker-cleanup.test.ts index fd6c73a98e..880db3f1d2 100644 --- a/packages/ui-backend-claude/tests/worker-cleanup.test.ts +++ b/packages/ui-backend-claude/tests/worker-cleanup.test.ts @@ -22,7 +22,7 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai mkdirSync(brain); mkdirSync(saved); mkdirSync(home); writeFileSync(join(saved, "settings.json"), "{}"); const sandbox = prepareWorkerSandbox(brain, { home, profile: "governed", areas: [] }); const original = internal.launchAgentWorkerAsync; - let gate = Promise.withResolvers(), closing = Promise.withResolvers(); + let gate = Promise.withResolvers(), closing = Promise.withResolvers(), stateClosed = Promise.withResolvers(); const retries: Array<() => Promise> = []; // The real worker and handles; only the turn temp's awaited close is held at a gate. const launch = spyOn(internal, "launchAgentWorkerAsync").mockImplementation(async input => { @@ -31,6 +31,9 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai retries.push(close); turnTemp.close = () => { throw new Error("CLAUDE_SYNC_TURN_TEMP_CLOSE_ON_AN_ASYNC_LAUNCH"); }; turnTemp.closeAsync = async () => { closing.resolve(); await gate.promise; await close(); }; + // The state handle's real close runs beside the held one; its completion is observed, not waited out. + const state = worker.state!, closeState = state.closeAsync.bind(state); + state.closeAsync = async () => { await closeState(); stateClosed.resolve(); }; return worker; }); const turn = async (ledger: ReturnType) => { @@ -45,13 +48,16 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai const confirmed = createStateLedger(); const finished = turn(confirmed); await closing.promise; - await Bun.sleep(20); + // Everything the release awaits besides the held gate has completed, and one + // macrotask runs any continuation of it: only the gate now holds the release. + await stateClosed.promise; + await new Promise(resolve => setTimeout(resolve, 0)); expect(confirmed.live, "CLAUDE_RESERVATION_HELD_WHILE_CLOSE_PENDING").toBe(1); gate.resolve(); await finished; expect(confirmed.live, "CLAUDE_CONFIRMED_CLOSE_RELEASES_RESERVATION").toBe(0); - gate = Promise.withResolvers(); closing = Promise.withResolvers(); + gate = Promise.withResolvers(); closing = Promise.withResolvers(); stateClosed = Promise.withResolvers(); const refused = createStateLedger(); const refusing = turn(refused); await closing.promise; diff --git a/packages/ui-backend-claude/tests/worker-stdio-release.test.ts b/packages/ui-backend-claude/tests/worker-stdio-release.test.ts index 531c4a4963..29a56c5993 100644 --- a/packages/ui-backend-claude/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-claude/tests/worker-stdio-release.test.ts @@ -59,7 +59,7 @@ test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worke test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worker reports its exit before its stdio release, and settles after it", async () => { const { fifos, spawner, spawn } = fixture(); const release = Promise.withResolvers(); - let releasing = false; + let releasing = false as boolean; const workers = spawner(worker => { const real = worker.released.bind(worker); worker.released = () => { releasing = true; return release.promise.then(real); }; @@ -76,7 +76,11 @@ test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worke child.stdout.on("data", chunk => { output += String(chunk); }); await once(child.stdout, "end"); expect(output, "POST_EXIT_DRAIN_COMPLETES").toBe("Ithaca"); - await Bun.sleep(50); + // The release has been requested; one macrotask then runs any settlement + // that does not wait for it, since the held release is all that remains. + // The test's own timeout bounds this condition. + while (!releasing) await Bun.sleep(1); + await new Promise(resolve => setTimeout(resolve, 0)); expect({ releasing, settled }, "SETTLEMENT_WAITS_FOR_RELEASE").toEqual({ releasing: true, settled: false }); release.resolve(); await finished; diff --git a/packages/ui-react/tests/runtime-hook-phases.test.ts b/packages/ui-react/tests/runtime-hook-phases.test.ts index 093a137249..895b79e027 100644 --- a/packages/ui-react/tests/runtime-hook-phases.test.ts +++ b/packages/ui-react/tests/runtime-hook-phases.test.ts @@ -39,7 +39,11 @@ test("pending output remains distinguishable from a completed channel", async () let complete = false; const observation = hook.child("package-build", { pid: 42, stdout: heldOutput, stderr: new ReadableStream({ start(controller) { controller.close(); } }), exited: Promise.resolve(0) }).then(() => { complete = true; }); - await Bun.sleep(20); + // The exit and the closed stderr are observed, and one macrotask later the + // held stdout is the only thing the completion can still be waiting on. + // The test's own timeout bounds this condition. + while (!(records.some((r) => r.event === "exit") && records.some((r) => r.event === "stderr-complete"))) await Bun.sleep(1); + await new Promise((resolve) => setTimeout(resolve, 0)); expect(records.some((r) => r.event === "exit")).toBe(true); expect(records.some((r) => r.event === "stderr-complete")).toBe(true); expect(records.some((r) => r.event === "stdout-complete")).toBe(false); diff --git a/packages/ui-sdk/tests/maintenance-worker-kill-child.ts b/packages/ui-sdk/tests/maintenance-worker-kill-child.ts index 465c3013ca..a2d464247e 100644 --- a/packages/ui-sdk/tests/maintenance-worker-kill-child.ts +++ b/packages/ui-sdk/tests/maintenance-worker-kill-child.ts @@ -226,6 +226,8 @@ async function settled(f: Awaited>) { if (f.o.child) expect(await until(() => !alive(f.o.child!), 1000), "OWNED_CHILD_MUST_STOP").toBe(true); } +// The zero-delay `heartbeat` timer is the observation (#3332): it fires only if +// stop confirmation yields to the event loop instead of spinning on it. test("snapshot fork ordering: first signal follows real fork acknowledgement", async () => { const f = await fixture(); let heartbeat = false; const { worker, signals } = observed(f, () => injectFork(f)); @@ -262,20 +264,22 @@ test("missing children file uses real PPid fallback", async () => { }); test("every thread must confirm stop before the snapshot", async () => { - const f = await fixture(true); injectFork(f); bind(f.outer); let heartbeat = false, nonleaderRead = false, prematureSnapshot = false; + const f = await fixture(true); injectFork(f); bind(f.outer); let nonleaderRead = false, prematureSnapshot = false; + // A non-leader thread reports itself running for its first two polls, then + // its real stopped state; counted, so no timer decides when it confirms. + let unconfirmedReads = 2, lastReadUnconfirmed = false; const original = fs.readFileSync; const spy = spyOn(fs, "readFileSync").mockImplementation(((path: unknown, ...args: unknown[]) => { const name = String(path); const value = Reflect.apply(original, fs, [path, ...args]); if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/stat") && name !== `/proc/${f.outer.pid}/task/${f.outer.pid}/stat`) { - nonleaderRead = true; - if (!heartbeat && typeof value === "string") return value.replace(/\) [Tt] /, ") S "); + nonleaderRead = true; lastReadUnconfirmed = false; + if (unconfirmedReads > 0 && typeof value === "string") { unconfirmedReads--; lastReadUnconfirmed = true; return value.replace(/\) [Tt] /, ") S "); } } - if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/children") && !heartbeat) prematureSnapshot = true; + if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/children") && lastReadUnconfirmed) prematureSnapshot = true; return value; }) as typeof fs.readFileSync); restores.push(() => spy.mockRestore()); - setTimeout(() => { heartbeat = true; }, 10); cancellation.killWorker(f.outer); await settled(f); await complete(f.outer); - expect(nonleaderRead && !prematureSnapshot, "ALL_THREADS_CONFIRMED_BEFORE_SNAPSHOT").toBe(true); + expect(nonleaderRead && !prematureSnapshot && unconfirmedReads === 0, "ALL_THREADS_CONFIRMED_BEFORE_SNAPSHOT").toBe(true); }); test("empty outer terminates and a fork request while stopped cannot create a child", async () => { diff --git a/packages/ui-sdk/tests/native-identity-inspector.test.ts b/packages/ui-sdk/tests/native-identity-inspector.test.ts index d5512a94e1..03268e8a1f 100644 --- a/packages/ui-sdk/tests/native-identity-inspector.test.ts +++ b/packages/ui-sdk/tests/native-identity-inspector.test.ts @@ -82,6 +82,9 @@ test("an interrupted or timed-out inspection is unknown and the next one starts // Opening a FIFO for reading blocks until a writer appears: the loop program waits. await expect(inspect.run("loop", fifo), "NATIVE_INSPECTOR_TIMEOUT_UNKNOWN").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("operation timeout exceeded") }); const controller = new AbortController(), pending = inspect.run("loop", fifo, controller.signal); + // Kept real time (#3332): the abort must land while the interpreter is blocked + // in the kernel's FIFO open. Nothing portable reports that state (the wait + // channel is not readable on every host), so the run gets 100 ms to reach it. setTimeout(() => controller.abort(new Error("Odysseus stopped the inspection")), 100); await expect(pending, "NATIVE_INSPECTOR_ABORT_UNKNOWN").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("Odysseus stopped the inspection") }); expect(lastLine((await inspect.run("root", root)).errors)).toBe("RuntimeError: not a subvolume root"); diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index e53171d421..c59a8cdffd 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -205,21 +205,28 @@ test("an exit settles only once its release has, and a failed supervision is ref }); test("a supervisor lost while a status request is outstanding refuses once and ignores the late answer", async () => { - const requests = statusRequests([{ exited: true, code: 0 }], 150); + // The request is held open, so it is outstanding by construction rather + // than by a sleep shorter than its reply. + const entered = Promise.withResolvers(), reply = Promise.withResolvers(), answered = Promise.withResolvers(); + let requests = 0; + const status = () => workerStep(() => { throw new Error("IDENTITY_STATUS_MUST_NOT_BLOCK"); }, async () => { + entered.resolve(); await reply.promise; requests++; + setTimeout(answered.resolve, 0); // after the late answer's own continuation has run + return { exited: true, code: 0 }; + }); const owner = supervision(); let lose!: (code: number) => void; - try { - const exit = identityWorkerExit(requests.status, new Promise(resolve => { lose = resolve; }), owner.hooks); - await Bun.sleep(150); - expect(requests.seen.requests, "IDENTITY_REQUEST_OUTSTANDING").toBe(0); - lose(1); - const refusal = await exit.catch((error: unknown) => error); - expect((refusal as WorkerHostError).requirement).toBe("worker_identity_supervisor_lost (1)"); - await Bun.sleep(200); - expect(requests.seen.requests).toBe(1); - // The late answer neither settles again nor releases the broker a second time. - expect(owner.state()).toEqual({ finished: true, released: 0 }); - } finally { requests.stop(); } + const exit = identityWorkerExit(status, new Promise(resolve => { lose = resolve; }), owner.hooks); + await entered.promise; + expect(requests, "IDENTITY_REQUEST_OUTSTANDING").toBe(0); + lose(1); + const refusal = await exit.catch((error: unknown) => error); + expect((refusal as WorkerHostError).requirement).toBe("worker_identity_supervisor_lost (1)"); + reply.resolve(); + await answered.promise; + expect(requests).toBe(1); + // The late answer neither settles again nor releases the broker a second time. + expect(owner.state()).toEqual({ finished: true, released: 0 }); }); test("a separate-UID maintenance launch waits for its helper worker with the event loop free", async () => { From 67c52d1efeaf307ad7b7232328d552ccd36adf25 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 09:02:05 +0000 Subject: [PATCH 2/2] test(root): replace slice-5 real-time waits and record slices 4 and 5 (#3332) - build-concurrency: the optional dependency's compiler holds until a peer finished and its slot was refilled, instead of sleeping 500 ms. - planning-observer: the sampler posts `ready` after its first reading instead of the observer waiting one 250 ms interval. - docs/process/test-waits.md records the slice 4 and 5 families. Refs #3332 Co-Authored-By: Claude Opus 5.5 --- docs/process/test-waits.md | 7 +++++++ tests/build-concurrency.test.ts | 21 +++++++++++++++++++-- tests/helpers/planning-observer.ts | 13 ++++++++++--- tests/helpers/planning-sampler.ts | 2 ++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 2f7fbd5b91..4801bda5ce 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -116,6 +116,13 @@ any reclassification and its mutation receipts. | `chat-lifecycle.test.ts` and `writer-gate-offloop.test.ts`, work queued behind a held writer | The retirement, or the host downgrade, is posted to the real write worker before the racing step | A `Worker.prototype.postMessage` observer replaces 20–50 ms sleeps and fixed timers; the descriptor is restored after each case. | | `write-worker.test.ts`, app writes against a running procedure | The worker is inside the held procedure before the app writes | The probe sets an `entered` flag that the test awaits with `Atomics.waitAsync`, instead of sleeping 20–50 ms. | | `native-brain-leases.test.ts`, `storage-offloop.test.ts` and `turn-egress.test.ts` | A lost reply after a newer release started; failures settled before close; a pending taint | The newer release's arrival, one macrotask after the synchronous tick, and a bounded taint poll replace fixed 20–100 ms waits. | +| `worker-steps-event-loop.test.ts`, a supervisor lost during a status request | The request is outstanding when the supervisor is lost; its late answer neither settles again nor releases the broker | The status step is held open, so the request is outstanding by construction. The test releases it and awaits its answer, instead of sleeping 150 ms and then 200 ms. | +| `maintenance-worker-kill-child.ts`, every thread confirms its stop | A non-leader thread that reports itself running delays the snapshot until it confirms | The thread reports running for exactly two polls, instead of until a 10 ms timer fires. The zero-delay heartbeat timers in the fork-ordering cases are the observation: they prove that stop confirmation yields. | +| Claude `worker-cleanup.test.ts` and `worker-stdio-release.test.ts`, reservation and settlement held | The reservation stays charged, and settlement waits, while only the held close or release remains | The state handle's real close is observed, or the release request is polled for. One macrotask then runs any continuation, instead of 20–50 ms windows. | +| ui-react `runtime-hook-phases.test.ts`, pending output | Exit and stderr completion are reported while stdout is held | A condition on those two records, then one macrotask, replaces a 20 ms window. | +| Root `build-concurrency.test.ts`, optional dependency before its consumer | A consumer never compiles before its optional dependency, despite a peer cycle | The dependency's compiler wrapper holds until a peer has finished and its slot has been refilled, instead of sleeping 500 ms. A consumer started in that slot compiles, and fails, while the dependency is held. | +| Root `helpers/planning-observer.ts`, first sampler reading | The sampler has a reading before the observed call blocks the main thread | The sampler posts `ready` after its first reading. The observer awaits that message, instead of one 250 ms interval, with the existing stop budget as its failure maximum. | +| Kept real time, reason in source | `native-identity-inspector` abort during a blocking FIFO open; geo `routing` admission-write latency while the transport deadline is armed; the delayed-fsync spies in `native-observation-storage`, `transcript-archive` and `native-observation-settlement` (event-loop liveness under slow IO) | The inspector's blocked state has no portable signal. The geo latency and fsync delays are the stimulus itself. | ## Continuity settling boundaries diff --git a/tests/build-concurrency.test.ts b/tests/build-concurrency.test.ts index 4882b8f604..e31b9212c6 100644 --- a/tests/build-concurrency.test.ts +++ b/tests/build-concurrency.test.ts @@ -132,11 +132,28 @@ async function successfulBuild(storageFailure?: StorageFailure) { } mkdirSync(join(root, "node_modules/.bin"), { recursive: true }); const wrapper = join(root, "node_modules/.bin/tsc"); + // The optional dependency holds until a peer has finished and its slot has + // been refilled. Correct order refills it with the other peer; a consumer + // started there instead compiles, and fails, before the dependency's output + // exists. Both peers are ready from the start, so with two jobs a correct + // order never waits on the consumer. writeFileSync(wrapper, `#!${process.execPath} -const args=process.argv.slice(2); -if(args.some(arg=>arg.includes("/z-dependency/"))) await Bun.sleep(500); +import { existsSync, writeFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +const args=process.argv.slice(2), name=basename(dirname(args[args.indexOf("-p")+1])); +const marker=(package_,state)=>join(${JSON.stringify(root)},package_+"-"+state); +writeFileSync(marker(name,"started"),""); +if(name==="z-dependency"){ + const peers=["b-peer","c-peer"]; + // Bounded by the owning test process: once it is gone, this hold ends. + while(!(peers.some(peer=>existsSync(marker(peer,"done"))) && (peers.every(peer=>existsSync(marker(peer,"started"))) || existsSync(marker("a-consumer","done"))))){ + if(!existsSync("/proc/${process.pid}")){console.error("NO_PEER_SLOT_REFILLED_BEFORE_THE_DEPENDENCY");process.exit(3);} + await Bun.sleep(5); + } +} const compiler=Bun.spawn([process.execPath,${JSON.stringify(join(repo, "node_modules/typescript/bin/tsc"))},...args],{stdout:"inherit",stderr:"inherit"}); process.exitCode=await compiler.exited; +writeFileSync(marker(name,"done"),String(process.exitCode)); `); chmodSync(wrapper, 0o755); for (const name of ["a-consumer", "b-peer", "c-peer", "z-dependency"]) { diff --git a/tests/helpers/planning-observer.ts b/tests/helpers/planning-observer.ts index 54ad8a7acc..09d39c4828 100644 --- a/tests/helpers/planning-observer.ts +++ b/tests/helpers/planning-observer.ts @@ -71,9 +71,16 @@ export async function observePlanning(root: string, label: string, call: () = let sampler: Worker | undefined; try { sampler = new Worker(new URL("./planning-sampler.ts", import.meta.url), { workerData: { mainTid: process.pid, ...PLANNING_OBSERVER_LIMITS } }); - // Let the sampler take its first reading before the call blocks this thread. - await new Promise(resolve => setTimeout(resolve, PLANNING_OBSERVER_LIMITS.intervalMs)); - } catch (error) { incomplete.push(`sampler did not start: ${String(error)}`); sampler = undefined; } + // The sampler reports its first reading before the call blocks this thread. + const started = sampler; + let timer: ReturnType | undefined; + try { + await new Promise((resolve, reject) => { + started.once("message", () => resolve()); started.once("error", reject); + timer = setTimeout(() => reject(new Error(`no first reading within ${PLANNING_OBSERVER_LIMITS.stopMs} ms`)), PLANNING_OBSERVER_LIMITS.stopMs); + }); + } finally { clearTimeout(timer); } + } catch (error) { incomplete.push(`sampler did not start: ${String(error)}`); void sampler?.terminate(); sampler = undefined; } const before = { at: performance.now(), cpu: process.cpuUsage(), children: childrenCpuMs(), main: mainSchedstat(), pressure: pressureUs(), load: loadAverage() }; let outcome: PlanningRecord["outcome"] = "returned"; let result: T | undefined; diff --git a/tests/helpers/planning-sampler.ts b/tests/helpers/planning-sampler.ts index 0150c52a4f..3de8e66536 100644 --- a/tests/helpers/planning-sampler.ts +++ b/tests/helpers/planning-sampler.ts @@ -51,6 +51,8 @@ const sample = () => { }; sample(); const timer = setInterval(sample, intervalMs); +// The first reading is taken: the observer may now block its thread. +parentPort!.postMessage("ready"); parentPort!.once("message", () => { clearInterval(timer);