From e658129d7ca8776a4f4b191cf1ff6bc9475b84e6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 12:05:19 +0000 Subject: [PATCH] test: justify or replace the remaining non-ui-server negative-observation waits (#3332 slice 6) Replaced with deterministic signals: - Claude worker-event-loop 135: abort listeners run inside abort(); one macrotask, then the grace exit code and output prove survival. - Pi worker-stdio-release 113: the withheld release is the last teardown step; one macrotask after the call. - ui-sdk worker-steps-event-loop 139: the awaited status form waits for an actual 1 ms tick; 180: one macrotask after the in-memory refusal. Kept with the reason in source: Claude worker-event-loop 115, Pi early-cancel-lifecycle 215, Pi worker-stdio-release 67 (stimulus), ui-sdk identity-broker-qualification.native 494/497/519/540, worker-steps-event-loop 136 and the settledWithin helper, build-concurrency 80 (now starting only after the failing compiler has exited) and test-invocation-lifetime 205. Refs #3332 Co-Authored-By: Claude Opus 5.5 --- .../tests/worker-event-loop.test.ts | 10 ++++++- .../tests/early-cancel-lifecycle.test.ts | 4 +++ .../tests/worker-stdio-release.test.ts | 10 ++++++- .../identity-broker-qualification.native.ts | 8 ++++++ .../tests/worker-steps-event-loop.test.ts | 26 ++++++++++++++++--- tests/build-concurrency.test.ts | 9 +++++++ tests/test-invocation-lifetime.test.ts | 1 + 7 files changed, 62 insertions(+), 6 deletions(-) diff --git a/packages/ui-backend-claude/tests/worker-event-loop.test.ts b/packages/ui-backend-claude/tests/worker-event-loop.test.ts index dbfb3ec4b4..20e8f8cabb 100644 --- a/packages/ui-backend-claude/tests/worker-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/worker-event-loop.test.ts @@ -112,6 +112,11 @@ test.skipIf(!native)("a started worker's failed lifecycle stays handled until th signal: new AbortController().signal } as never); child.on("error", () => {}); child.stdout.resume(); child.stdin.end(); await new Promise(done => child.once("exit", done)); + // Kept real time: a negative observation. The facade's exit is emitted + // before the lifecycle settles; its rejection follows only once the state + // handle's broker close and the FIFO release finish on Bun's IO pool, and + // nothing outside the turn exposes that settlement. Awaiting it would + // attach the very handler whose absence this test checks. await Bun.sleep(50); expect(unhandled, "WORKER_LIFECYCLE_FAILURE_HANDLED_BEFORE_FINISH").toEqual([]); await expect(spawner.finish()).rejects.toThrow("scope freezer refused"); @@ -132,7 +137,10 @@ test.skipIf(!native)("a turn abort leaves a running worker to the SDK's own clos const exit = new Promise(done => child.once("exit", (code: number | null) => { exited = true; done(code); })); await ready; turn.abort(); - await Bun.sleep(300); + // Abort listeners run synchronously inside abort(); one macrotask runs any + // continuation they scheduled. A kill sent by then stops the worker before + // it can read "grace", so the exit code and output below are the proof. + await new Promise(resolve => setImmediate(resolve)); expect(exited, "TURN_ABORT_LEAVES_WORKER_TO_SDK_CLOSE").toBe(false); child.stdin.end("grace\n"); expect(await exit).toBe(0); diff --git a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts index 3f208c6c04..3cbfc79118 100644 --- a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts +++ b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts @@ -212,6 +212,10 @@ for (const failure of ["startup failure", "initialization timeout"] as const) { if (failure === "initialization timeout") timeout(); await reached.promise; controller.abort(); + // Kept real time: a negative observation. The release is held in memory, + // but a startup failure that stopped awaiting it would still close the + // worker's turn temp on the native broker before settling. That close has + // no in-process signal, so only a window can show the turn did not settle. await Bun.sleep(50); expect(settled, "PI_START_FAILURE_AWAITS_RELEASE_DESPITE_CANCELLATION").toBe(false); released.resolve(); diff --git a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts index 636654d6e7..3fb9e5b8e4 100644 --- a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts @@ -64,6 +64,11 @@ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "non if (pool || hold === "none" || !String(chunk).includes(`"type":"${hold}"`)) return; const held = pool = holdWorkPool(fifos.dir); const ended = (stream: NodeJS.ReadableStream) => new Promise(done => stream.once("end", done)); + // Kept real time: the delay is the stimulus. It makes Bun's own close of + // its descriptor duplicates late, so a turn that settles at exit or at + // end of output settles with them still open. Freeing the pool when the + // turn asks for release would let a turn that asks without awaiting the + // answer race the pool's close. void Promise.all([ended(launched.stdout), ended(launched.stderr)]).then(() => Bun.sleep(250)).then(held.release); })) as typeof launched.stdin.write; return launched; @@ -110,7 +115,10 @@ test.skipIf(!native)("a pi turn waits for its worker's stdio release, however lo const turn = piTurn(ANSWERING, "none", { promise: release.promise, called: calling.resolve }).then(outcome => { settled = true; return outcome; }); cleanup.push(() => release.resolve()); expect(await Promise.race([calling.promise.then(() => true), Bun.sleep(10_000).then(() => false)]), "PI_TURN_REACHES_RELEASE").toBe(true); - await Bun.sleep(100); + // The release is the turn's last teardown step and is withheld in memory. + // Everything after it is in-process work, so one macrotask after the call is + // when a turn that did not await the release would already have settled. + await new Promise(resolve => setImmediate(resolve)); expect(settled, "PI_TURN_PENDING_WHILE_RELEASE_WITHHELD").toBe(false); release.resolve(); const { open, refused, result } = await turn; diff --git a/packages/ui-sdk/tests/identity-broker-qualification.native.ts b/packages/ui-sdk/tests/identity-broker-qualification.native.ts index 700a8c75bc..786a344b14 100644 --- a/packages/ui-sdk/tests/identity-broker-qualification.native.ts +++ b/packages/ui-sdk/tests/identity-broker-qualification.native.ts @@ -491,6 +491,11 @@ raise SystemExit(child.wait())`); try { await until(() => existsSync(pulse) && statSync(pulse).size > 2, "IDENTITY_NESTED_PID_DID_NOT_START"); expect(workerPids().length).toBeGreaterThan(1); + // Kept real time (here and after the kill): negative observations. The + // payload appends to the pulse every 20 ms from inside a nested PID + // namespace. The broker signals the tree synchronously, but only the + // pulse shows that every writer stopped, including one outside the PIDs + // this test can list. 160 ms spans eight pulses; 100 ms spans five. worker.freeze(); const frozen = statSync(pulse).size; await sleep(160); expect(statSync(pulse).size).toBe(frozen); worker.resume(); await until(() => statSync(pulse).size > frozen + 2, "IDENTITY_NESTED_PID_DID_NOT_RESUME"); worker.kill("SIGKILL"); expect(await worker.exited).toBe(137); expect(errors()).toBe(""); @@ -515,6 +520,8 @@ with open('${pulse}','a',buffering=1) as out: } const result = await outcome; expect(result).toHaveProperty("error"); expect(String((result as { error: string }).error)).toMatch(/supervisor|control|supervision/); console.log(JSON.stringify({ supervisionMode: mode, outcome: result, stderr: errors() })); + // Kept real time below: no listed PID remains, and only the pulse, which + // grows every 20 ms, would show a writer that escaped the list. await until(() => workerPids().length === 0, "IDENTITY_SUPERVISION_LOSS_LEFT_WRITER").catch(error => { console.error("Surviving worker processes", workerPids().map(pid => ({pid, status:readFileSync(`/proc/${pid}/status`,"utf8").split("\n").filter(line=>/^(Name|State|PPid|Uid):/.test(line))}))); throw error; }); const ended = statSync(pulse).size; await sleep(100); expect(statSync(pulse).size).toBe(ended); } finally { await close(worker); } @@ -537,6 +544,7 @@ await worker.exited;`; await until(()=>existsSync(pulse)&&statSync(pulse).size>2,"IDENTITY_CHILD_SERVER_WORKER_DID_NOT_START"); server.kill("SIGKILL");expect(await server.exited).toBe(137); await until(()=>workerPids().length===0,"IDENTITY_SERVER_DEATH_LEFT_WORKER"); + // Kept real time: as above, the 20 ms pulse is the only witness of a writer outside the listed PIDs. const ended=statSync(pulse).size;await sleep(100);expect(statSync(pulse).size).toBe(ended);if(duringSetup)expect(existsSync(mustNotRun)).toBe(false); await stdout;expect(await stderr).toBe(""); } finally { if(server.exitCode===null)server.kill("SIGKILL");await server.exited; } 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 c59a8cdffd..8ff9a05830 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -127,16 +127,23 @@ test("a scratch mask's ignore check runs its real maintenance worker with the ev } finally { f.cleanup(); } }); -/** A supervisor request that takes `ms`, counting the ticks that fire while it is outstanding. */ +/** + * A supervisor request, counting the ticks that fire while it is outstanding. + * The blocking form holds the thread for `ms`, as a synchronous round trip + * would: no timer can fire inside it, so it counts none however long it takes. + * The awaited form is outstanding until the 1 ms ticker has actually fired, + * the one thing an event loop left free does, instead of for `ms`. + */ function statusRequests(replies: IdentityWorkerStatus[], ms: number) { const seen = { requests: 0, ticksDuringRequests: 0 }; let ticks = 0; - const timer = setInterval(() => { ticks++; }, 1); + const ticked: Array<() => void> = []; + const timer = setInterval(() => { ticks++; for (const resolve of ticked.splice(0)) resolve(); }, 1); const status = () => workerStep(() => { const before = ticks; Bun.sleepSync(ms); seen.ticksDuringRequests += ticks - before; return replies[Math.min(seen.requests++, replies.length - 1)]!; }, async () => { - const before = ticks; await Bun.sleep(ms); seen.ticksDuringRequests += ticks - before; + const before = ticks; await new Promise(resolve => { ticked.push(resolve); }); seen.ticksDuringRequests += ticks - before; return replies[Math.min(seen.requests++, replies.length - 1)]!; }); return { seen, status, stop: () => clearInterval(timer) }; @@ -177,7 +184,11 @@ test("a broker release that cannot confirm cleanup after the exit refuses that e finish: () => { finished = true; }, release: async () => { throw new identity.WorkerIdentityCleanupError("worker_identity_cleanup_unconfirmed: fixture"); } }) .then(code => code, (error: unknown) => error); expect(identity.workerCleanupUnconfirmed(refusal), "IDENTITY_EXIT_RELEASE_FAILURE_OBSERVABLE").toBe(true); - await Bun.sleep(20); + // The release rejected before the exit's refusal was observed, and every + // step here is in memory. Bun reports an unhandled rejection once the + // microtasks drain, before the next macrotask; under `bun test` the runner + // fails this test with it, as it did after the former 20 ms window. + await new Promise(resolve => setImmediate(resolve)); expect(unhandled, "IDENTITY_RELEASE_FAILURE_HANDLED").toEqual([]); } finally { process.off("unhandledRejection", record); requests.stop(); } }); @@ -598,6 +609,13 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke }; } +/** + * Kept real time. With 3000 ms it is a failure maximum. With 50 ms it is a + * negative race: the control stand-in answers a broker close only after 100 ms, + * in a separate process, so a non-final close that waited for the last + * handle's close would still be pending. No in-process event precedes that + * answer. + */ const settledWithin = (promise: Promise, ms: number) => Promise.race([promise.then(() => "settled", () => "settled"), Bun.sleep(ms).then(() => "pending")]); diff --git a/tests/build-concurrency.test.ts b/tests/build-concurrency.test.ts index e31b9212c6..4890de89a9 100644 --- a/tests/build-concurrency.test.ts +++ b/tests/build-concurrency.test.ts @@ -48,6 +48,7 @@ const args=process.argv.slice(2), directory=dirname(args[args.indexOf("-p")+1]), writeFileSync(join(${JSON.stringify(root)},name+"-started"), String(process.pid)); const compiler=Bun.spawn([process.execPath,${JSON.stringify(join(repo, "node_modules/typescript/bin/tsc"))},...args],{stdout:"inherit",stderr:"inherit"}); const code=await compiler.exited; +writeFileSync(join(${JSON.stringify(root)},name+"-exited"),String(code)); if(name==="beta" && code===0){writeFileSync(join(${JSON.stringify(root)},"peer-ready"),"");while(!existsSync(${JSON.stringify(release)})) await Bun.sleep(10);writeFileSync(join(${JSON.stringify(root)},"peer-drained"),"");} process.exitCode=code; `); @@ -77,6 +78,14 @@ process.exitCode=code; expect(running[0].state, "LIVE_PEER_RECEIPT_REMAINS_PARTIAL").toBe("running"); expect(running[0].packages.find((pkg: {name: string}) => pkg.name === "beta").children[0].code).toBeUndefined(); } + // The window starts only once alpha's compiler has actually failed, so it + // always follows the error it is about. + while (!existsSync(join(root, "alpha-exited")) && !exited && Date.now() < deadline) await Bun.sleep(10); + expect(existsSync(join(root, "alpha-exited")) && readFileSync(join(root, "alpha-exited"), "utf8"), "FAILING_COMPILER_EXITED_BEFORE_WINDOW").toBe("2"); + // Kept real time: a negative observation. A build that stopped waiting for + // its live peer would report alpha's failure and exit as a process. Correct + // code never exits here, so nothing marks the moment; 300 ms is the window + // in which that exit would be observed. await Bun.sleep(300); expect(exited, "PARALLEL_BUILD_WAITS_LIVE_COMPILER_PEER_AFTER_ERROR").toBe(false); writeFileSync(release, ""); diff --git a/tests/test-invocation-lifetime.test.ts b/tests/test-invocation-lifetime.test.ts index 958f89b90d..fb0fe34344 100644 --- a/tests/test-invocation-lifetime.test.ts +++ b/tests/test-invocation-lifetime.test.ts @@ -202,6 +202,7 @@ try { const ready=Date.now()+10000;while((!existsSync("tmp/orphan")||!output.includes(${JSON.stringify(phase === "build" ? '"event":"build-exit"' : "TEST_LEADER_EXIT")}))&&Date.now()