Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/ui-backend-claude/tests/worker-event-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
10 changes: 9 additions & 1 deletion packages/ui-backend-pi/tests/worker-stdio-release.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions packages/ui-sdk/tests/identity-broker-qualification.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
Expand All @@ -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); }
Expand All @@ -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; }
Expand Down
26 changes: 22 additions & 4 deletions packages/ui-sdk/tests/worker-steps-event-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<IdentityWorkerStatus>(() => {
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<void>(resolve => { ticked.push(resolve); }); seen.ticksDuringRequests += ticks - before;
return replies[Math.min(seen.requests++, replies.length - 1)]!;
});
return { seen, status, stop: () => clearInterval(timer) };
Expand Down Expand Up @@ -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(); }
});
Expand Down Expand Up @@ -598,6 +609,13 @@ function heldRootSeam(f: ReturnType<typeof fixture>, 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 = <T>(promise: Promise<T>, ms: number) =>
Promise.race([promise.then(() => "settled", () => "settled"), Bun.sleep(ms).then(() => "pending")]);

Expand Down
9 changes: 9 additions & 0 deletions tests/build-concurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
`);
Expand Down Expand Up @@ -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, "");
Expand Down
1 change: 1 addition & 0 deletions tests/test-invocation-lifetime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()<ready)await Bun.sleep(10);
expect(existsSync("tmp/orphan"),output).toBe(true);orphan=JSON.parse(readFileSync("tmp/orphan","utf8"));
expect(output, "ACTUAL_LEADER_EXIT_BEFORE_CANCEL").toContain(${JSON.stringify(phase === "build" ? '"event":"build-exit"' : "TEST_LEADER_EXIT")});
/* Kept real time: a negative observation. Completion is the wrapper's exit plus EOF on both outputs, which the orphan still holds; a wrapper that ended it early would complete through process exits. Correct code never completes here, so no event marks the moment. */
await Bun.sleep(30);expect(done,"EOF_HOLDER_BLOCKS_WRAPPER_COMPLETION").toBe(false);
child.kill(${JSON.stringify(cancellation === "SIGKILL" ? "SIGKILL" : "SIGTERM")});const end=Date.now()+2500;while(!done&&Date.now()<end)await Bun.sleep(10);
const survives=processIdentity(orphan.pid)?.start===orphan.start;
Expand Down
Loading