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
7 changes: 7 additions & 0 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 6 additions & 1 deletion packages/geo/tests/routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>}}).transport;
const original = instrumented.writeAtomic;
Expand Down
12 changes: 9 additions & 3 deletions packages/ui-backend-claude/tests/worker-cleanup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(), closing = Promise.withResolvers<void>();
let gate = Promise.withResolvers<void>(), closing = Promise.withResolvers<void>(), stateClosed = Promise.withResolvers<void>();
const retries: Array<() => Promise<void>> = [];
// 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 => {
Expand All @@ -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<typeof createStateLedger>) => {
Expand All @@ -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<void>(); closing = Promise.withResolvers<void>();
gate = Promise.withResolvers<void>(); closing = Promise.withResolvers<void>(); stateClosed = Promise.withResolvers<void>();
const refused = createStateLedger();
const refusing = turn(refused);
await closing.promise;
Expand Down
8 changes: 6 additions & 2 deletions packages/ui-backend-claude/tests/worker-stdio-release.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>();
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); };
Expand All @@ -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;
Expand Down
6 changes: 5 additions & 1 deletion packages/ui-react/tests/runtime-hook-phases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
16 changes: 10 additions & 6 deletions packages/ui-sdk/tests/maintenance-worker-kill-child.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ async function settled(f: Awaited<ReturnType<typeof fixture>>) {
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));
Expand Down Expand Up @@ -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 () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-sdk/tests/native-identity-inspector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
33 changes: 20 additions & 13 deletions packages/ui-sdk/tests/worker-steps-event-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(), reply = Promise.withResolvers<void>(), answered = Promise.withResolvers<void>();
let requests = 0;
const status = () => workerStep<IdentityWorkerStatus>(() => { 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<number>(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<number>(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 () => {
Expand Down
21 changes: 19 additions & 2 deletions tests/build-concurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]) {
Expand Down
13 changes: 10 additions & 3 deletions tests/helpers/planning-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,16 @@ export async function observePlanning<T>(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<typeof setTimeout> | undefined;
try {
await new Promise<void>((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;
Expand Down
2 changes: 2 additions & 0 deletions tests/helpers/planning-sampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading