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
5 changes: 5 additions & 0 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ any reclassification and its mutation receipts.
| 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. |
| ui-server negative observations behind a real write-worker hold (`drafts-settings-offloop`, `inbox-writes-offloop`, `retry-proposal-offloop`, `storage-offloop`, `storage-scan-offloop`, `writer-gate-offloop`) | The queued commit, and everything after it, has not run while an earlier probe call holds the worker | The worker answers in submission order on one port, so the test reads its main-thread flags when the hold answers, instead of after a 20–50 ms window. Rows the worker commits to the database file are read while the hold is still running, because once it answers the worker may already be committing. |
| ui-server negative observations behind an in-memory hold (`app-writes-offloop`, `drafts-settings-offloop`, `push-drain`, `native-journal-observer`, `private-index-stdio-release`, `reference-source`, `reference-tools`) | Settlement waits for the one held write, release or acquisition | The test waits until the held step has started, then one macrotask runs every continuation that does not wait for it, instead of 10–50 ms. |
| `http-mount-timers.test.ts` and `live-history-adapters.test.ts` | Cancelled native timers never fire; no history frame precedes the first input | A live control timer due after the cancelled ones, and an input frame on the same ordered socket, replace 60–80 ms and 20 ms windows. |
| Failure maxima, reason in source | `app-http-drain`, `app-metadata-cancellation`, `close-cancels-shared-runs`, `dialogue-storage`, `reference-source`, `reference-tools` and `write-worker` races whose expected outcome settles first | The deadline branch is never awaited on success. |
| Negative windows kept, reason in source | Writer-gate waiters in `host-fallback-gates` and `schedule-ignore-admission`; the `reference-writes-offloop` `pending` helper; app shutdown in `app-writer-cleanup`; the replayed tombstone in `contextual-refusals`; the `relayed-runtime-traffic-probe` exit window | A gate waiter polls every 5 ms and reports no refused attempt. The `pending` helper's callers read database rows that must be read inside the hold. A marker request for the replayed tombstone would start its own turn and change the counts. The shutdown windows cover real-IO round trips that correct code never completes, so no event marks them. |
| 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
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ try {
} finally {
clearTimeout(timer);
// A connection opened while the runtime exits still reaches the recorder.
// Negative window: no event reports that the exiting runtime opens no more
// connections. A barrier on the runtime's close, a FIFO marker connection and
// every accepted socket closing was tried (#3440): Bun's node:http reported the
// marker about 1 s late, so it was slower than this window.
await Bun.sleep(500);
recorder.close(); relay.stop(true);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/ui-sdk/tests/native-observation-storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ test("saves that overlap land in call order, so the last change is the durable o
const versions = new NativeFileVersions(); await versions.retain(storage);
const before = nativeFileVersion(file);
// The first save's fsync is the slow one, so an unordered second save would
// finish first and the older uncertainty would overwrite it.
// finish first and the older uncertainty would overwrite it. A barrier that
// held the first fsync until the second one starts would deadlock correct
// code, which never starts it while the first is pending; the delay is the stimulus.
const probe = await open(tmpdir(), "r"), handle = Object.getPrototypeOf(probe) as { sync(): Promise<void> };
await probe.close();
const sync = handle.sync;
Expand Down
2 changes: 2 additions & 0 deletions packages/ui-server/tests/app-http-drain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ test("shutdown cancels an unfinished body without waiting for its producer cance
pending=Promise.resolve(fixture.app.fetch(new Request("http://localhost/api/render",{method:"POST",headers:{"content-type":"application/json"},body})));
await entered.promise;
closing=fixture.app.close();
// Failure maximum: on success the response settles first and the 1500 ms branch is never awaited.
const outcome=await Promise.race([pending.then(response=>response.status),Bun.sleep(1500).then(()=>"still reading" as const)]);
expect(outcome,"SHUTDOWN_DOES_NOT_WAIT_FOR_UNFINISHED_CLIENT_BODY").not.toBe("still reading");
expect(cancelled,"SHUTDOWN_CANCELS_ORIGINAL_BODY_READER").toBe(true);
Expand Down Expand Up @@ -93,6 +94,7 @@ test("shutdown releases a byte-cap cancellation wait while preserving its 413 re
pending=Promise.resolve(fixture.app.fetch(new Request("http://localhost/api/render",{method:"POST",headers:{"content-type":"application/json"},body}))).then(response=>{settled=true;return response;});
await cancelling.promise;expect(settled,"ORDINARY_BYTE_CAP_STILL_WAITS_FOR_ITS_PRODUCER_CANCEL").toBe(false);
closing=fixture.app.close();
// Failure maximum: on success the response settles first and the 1500 ms branch is never awaited.
const outcome=await Promise.race([pending.then(response=>response.status),Bun.sleep(1500).then(()=>"still cancelling" as const)]);
expect(outcome,"SHUTDOWN_DOES_NOT_WAIT_FOR_STALLED_PRODUCER_CANCEL").toBe(413);expect(renders).toBe(0);await closing;
}finally{releaseCancel.resolve();await pending?.catch(()=>{});await closing?.catch(()=>{});await fixture.close();rmSync(state,{recursive:true,force:true});}
Expand Down
1 change: 1 addition & 0 deletions packages/ui-server/tests/app-metadata-cancellation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ for (const trigger of ["caller abort", "app close", "loopback abort", "pre-abort
closing = fixture.app.close();
expect((await fixture.fetch("/api/health")).status, "CLOSING_APP_REFUSES_NEW_HTTP_DISPATCH").toBe(503);
}
// Failure maximum: on success the status settles first and the timer is cleared.
const outcome = await Promise.race([
pending!.then(response => response.status),
new Promise<"still queued">((resolve) => { timer = setTimeout(() => resolve("still queued"), 1500); }),
Expand Down
9 changes: 9 additions & 0 deletions packages/ui-server/tests/app-writer-cleanup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,9 @@ for (const kind of ["activity", "actions"] as const) test(`${kind} acceptance ov
expect(app.close()).toBe(closing);
// A handshake proves shutdown reached the actual Activity close. Keep
// transport held through another event-loop turn, including on old code.
// Negative window: a premature writer close would follow write-worker round
// trips with real IO, and correct code never closes it here, so no event
// marks the point by which it would have happened; 20 ms covers those trips.
await draining;
await new Promise(resolve => setTimeout(resolve, 20));
const closedBeforeAcceptance = observed.closes;
Expand Down Expand Up @@ -420,6 +423,9 @@ for (const kind of ["storage", "activity", "actions"] as const) for (const statu
expect((originalError as Error).message).toContain("Odysseus durable outcome refused");
// Let both the sampler and runtime catches observe settlement before the
// late Activity drain. The original worker failure must remain owned.
// Those catches run across write-worker replies with real IO and report
// nothing when they have retained the failure, so a window is the only
// way to let them run before the release.
await new Promise(resolve => setTimeout(resolve, 20));
release();
expect(await outcome, `${kind.toUpperCase()}_SETTLED_COMMIT_FAILURE_RETAINED_BY_APP_CLOSE`).toBe(originalError);
Expand Down Expand Up @@ -500,6 +506,9 @@ test("same-kind different-input deliveries both persist outcomes before app writ
await draining;
releaseFirst();
expect(await deliveries[0], "FIRST_DELIVERY_HAS_OWN_RESULT").toBe(1);
// Negative window: a close that wrongly skipped the second delivery would
// finish after write-worker round trips with real IO, and correct code never
// finishes here, so no event marks the point by which it would have.
await new Promise(resolve => setTimeout(resolve, 20));
expect(closed, "APP_CLOSE_JOINS_SECOND_SAME_KIND_DELIVERY").toBe(false);
expect(observed.closes, "WRITER_OPEN_UNTIL_ALL_SAME_KIND_OUTCOMES").toBe(0);
Expand Down
18 changes: 13 additions & 5 deletions packages/ui-server/tests/app-writes-offloop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,17 @@ test("a turn's settled() waits for its roadblock commit", async () => {
const db = createUiDb(":memory:");
let release!: () => void;
const held = new Promise<number>(done => { release = () => done(0); });
const entered = Promise.withResolvers<void>();
const recorder = createTurnRecorder({ store: createActivityStore(db, { writer: "odysseus" }), governanceDb: db,
governanceWrites: { ...createGovernanceWrites(db), roadblocks: () => held } }, { turnId: "voyage", sessionId: null });
governanceWrites: { ...createGovernanceWrites(db), roadblocks: () => { entered.resolve(); return held; } } }, { turnId: "voyage", sessionId: null });
try {
recorder.finish("success");
let settled = false;
void recorder.settled().then(() => { settled = true; });
await Bun.sleep(50);
const settling = recorder.settled().then(() => { settled = true; });
// Everything but the held roadblock write is in memory: once that write has
// started, one macrotask runs every continuation that does not wait for it.
await Promise.race([entered.promise, settling]);
await new Promise(resolve => setImmediate(resolve));
expect(settled, "RECORDER_SETTLED_WAITS_FOR_ROADBLOCKS").toBe(false);
release();
await recorder.settled();
Expand Down Expand Up @@ -343,11 +347,15 @@ test("a replayed history waits for the classified blocks submitted before it (#2
const catalog = createSessionCatalog(() => f.db, quietLog, undefined, { pricing: { resolve: () => null }, store: createActivityStore(f.db, { writer: "odysseus" }), writer: f.writer });
let release!: () => void;
const pending = new Promise<void>(done => { release = done; });
const classifier = { enabled: true, settled: () => pending, attach: (_sessionId: string, messages: never[]) => messages } as never;
const consulted = Promise.withResolvers<void>();
const classifier = { enabled: true, settled: () => { consulted.resolve(); return pending; }, attach: (_sessionId: string, messages: never[]) => messages } as never;
const host = new WsHost({ registry: createStaticBackendRegistry([makeFakeBackend({ id: "claude" })], "claude"), catalog, classifier, maxConcurrentSessions: () => 3 });
let settled = false;
const waiting = host.historySettled().then(() => { settled = true; });
await Bun.sleep(50);
// The classifier is in memory: once the replay has consulted it, one
// macrotask runs every continuation that does not wait for its blocks.
await Promise.race([consulted.promise, waiting]);
await new Promise(resolve => setImmediate(resolve));
expect(settled, "HISTORY_WAITS_FOR_PENDING_CLASSIFIED_BLOCKS").toBe(false);
release();
await waiting;
Expand Down
1 change: 1 addition & 0 deletions packages/ui-server/tests/close-cancels-shared-runs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ test("the client's shutdown signal cancels admitted metadata with its exact reas
closing.abort(new Error("Server shutting down"));
const reason = new Error("Server shutting down");
shutdown.abort(reason);
// Failure maximum: on success the cancellation settles first and the 10 s branch is never awaited.
const outcome = await Promise.race([modules, Bun.sleep(10_000).then(() => "still running")]);
expect(outcome, "SHUTDOWN_CANCELS_ADMITTED_METADATA").toBe(reason);
}, 45_000);
2 changes: 2 additions & 0 deletions packages/ui-server/tests/dialogue-storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,8 @@ test("R7 an unrelated owner's delayed observation cannot serialize another conve
f.catalog.dialogueAppend=async input=>{if(input.ownerId==="pylos")await new Promise<void>(r=>{release=r;});return append(input);};
try{await f.journal.open(opening);await f.journal.open({...opening,conversationId:"pylos"});const e=fragment(0).evidence;if(e.kind!=="voice")throw Error("voice required");f.journal.voice("pylos",{...e,conversationId:"pylos"},()=>{});
f.journal.close("ithaca","odysseus",1);const reopened=f.journal.open({...opening,epoch:2});
// Failure maximum: on success the reopen settles first; a reopen serialized behind
// the held append never settles, so a deadline is what names that failure.
const outcome=await Promise.race([reopened.then(()=>"open"),Bun.sleep(200).then(()=>"blocked")]);expect(outcome,"UNRELATED_OWNER_DOES_NOT_BLOCK_REOPEN").toBe("open");
expect(f.db.query("SELECT epoch FROM dialogue_conversations WHERE id='ithaca'").get()).toEqual({epoch:2});
}finally{release?.();await f.close();}
Expand Down
14 changes: 9 additions & 5 deletions packages/ui-server/tests/drafts-settings-offloop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ test("draft acceptance returns immediately behind a slow write; reads wait and a
const read = Promise.resolve(app.request("/drafts/ithaca-draft")).then(response => { readDone = true; return response; });
const list = app.request("/drafts");
const late = refused(() => drafts.save(f.owner.id, "ithaca-draft", save("late", 1)));
await Bun.sleep(30);
expect(readDone, "DRAFT_GET_WAITS_FOR_ACCEPT_COMMIT").toBe(false);
await held;
// The accept commit is queued on the write worker behind the hold, whose
// replies arrive in order: the read is still waiting when the hold answers.
expect(await held.then(() => readDone), "DRAFT_GET_WAITS_FOR_ACCEPT_COMMIT").toBe(false);
const response = await read;
expect(response.status, "DRAFT_GET_SEES_SENT_TOMBSTONE").toBe(410);
expect(await response.json()).toMatchObject({ error: "DRAFT_DELETED", tombstoneRevision: 2 });
Expand Down Expand Up @@ -226,14 +226,18 @@ test("the turn recorder settles only after its subscription proof has committed"
let release!: () => void;
const held = new Promise<void>(resolve => { release = resolve; });
let proved = false;
const runtime = createRuntimeStatus(() => new Date(NOW), quietLog, () => held.then(() => { proved = true; }));
const entered = Promise.withResolvers<void>();
const runtime = createRuntimeStatus(() => new Date(NOW), quietLog, () => { entered.resolve(); return held.then(() => { proved = true; }); });
const recorder = createTurnRecorder({ store: createActivityStore(db), runtime }, { turnId: "ithaca", sessionId: null });
try {
recorder.observeActivity({ kind: "runtime_observed", billing: "subscription", policy: "subscription" });
recorder.finish("success");
let settled = false;
const done = recorder.settled().then(() => { settled = true; });
await Bun.sleep(20);
// Everything but the held proof write is in memory: once that write has
// started, one macrotask runs every continuation that does not wait for it.
await Promise.race([entered.promise, done]);
await new Promise(resolve => setImmediate(resolve));
expect(settled, "RECORDER_SETTLED_WAITS_FOR_SUBSCRIPTION_PROOF").toBe(false);
release();
await done;
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-server/tests/helpers/contextual-refusals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ export async function contextualRefusals(provider: "gemini" | "gpt", mode: "miss
// A tombstoned refusal cannot acquire a different binding or execute later.
const count = returned.length;
await request("refused-0");
// Negative window: correct code answers a replayed tombstone with no frame at
// all, so nothing marks its handling. A later request as a FIFO marker would
// start a turn of its own and change the counts asserted here.
await Bun.sleep(10);
expect(turns).toHaveLength(accepted + 1);
expect(f.sent.flatMap(f => provider === "gemini" ? f.toolResponse?.functionResponses ?? [] : f.delegation_id ? [f] : [])).toHaveLength(count);
Expand Down
5 changes: 5 additions & 0 deletions packages/ui-server/tests/host-fallback-gates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ async function ready(path: string) {
expect(existsSync(path), "ACTUAL_HOST_CHILD_ENTERED").toBe(true);
}

// Negative windows below: a waiting writer-gate acquisition retries its SQLite
// row every `pollMs` (5 ms here) and reports nothing for a refused attempt, and
// correct code never admits it. 30 ms, about six refused polls, is the only
// observable that the waiter saw the holder and stayed out.
for (const method of ["run", "launch"] as const) {
test(`${method}: a shared host child is accounted and remains concurrent with another shared holder`, async () => {
const f = fixture();
Expand Down Expand Up @@ -117,6 +121,7 @@ for (const method of ["run", "launch"] as const) {
const exclusive = await f.gate.acquire("exclusive", "existing exclusive owner"); f.holds.push(exclusive);
const cancel = new AbortController();
const waiting = settle(selected[method]({ ...f.command("shared", entered), signal: cancel.signal }));
// Cancel inside the gate wait (see the note above the loop), not before the first poll.
await Bun.sleep(30); cancel.abort(new Error("Odysseus cancelled"));
expect(String(await waiting), "CANCELLED_HOST_REQUEST_SETTLES_WITHOUT_A_CHILD").toContain("Odysseus cancelled");
exclusive.release();
Expand Down
15 changes: 10 additions & 5 deletions packages/ui-server/tests/http-mount-timers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ test("native cancellation removes retained handles while live unref timers remai
let fired = 0;
const timeout = setTimeout(() => { fired++; }, 20).unref();
const interval = setInterval(() => { fired++; }, 20).unref();
const live = setTimeout(() => { fired++; }, 40).unref();
// Due after both cancelled 20 ms handles: Bun runs due timers in deadline
// order, so once it fires either cancelled handle would already have fired.
const liveFired = Promise.withResolvers<void>();
const live = setTimeout(() => { fired++; liveFired.resolve(); }, 40).unref();
try {
expect(timers.pending.has(timeout)).toBe(true);
expect(timers.pending.has(interval)).toBe(true);
Expand All @@ -74,7 +77,7 @@ test("native cancellation removes retained handles while live unref timers remai
expect(timers.pending.has(timeout), "NATIVE_CANCELLED_TIMEOUT_IS_NOT_LIVE").toBe(false);
expect(timers.pending.has(interval), "NATIVE_CANCELLED_INTERVAL_IS_NOT_LIVE").toBe(false);
expect(timers.pending.has(live), "LIVE_UNREF_TIMER_IS_STILL_LIVE").toBe(true);
await Bun.sleep(80);
await liveFired.promise;
expect(fired, "ONLY_THE_LIVE_CONTROL_FIRES").toBe(1);
expect(timers.pending.size).toBe(0);
} finally {
Expand All @@ -93,12 +96,14 @@ test("native handle close, numeric cancellation and refresh preserve timer liven
(timeout as unknown as { close(): void }).close();
clearTimeout(Number(numeric));
expect(timers.pending.size, "CLOSE_AND_NUMERIC_CANCELLATION_ARE_NOT_LIVE").toBe(0);
const refreshed = setTimeout(() => { fired++; }, 20).unref();
// Created and refreshed after the cancelled handles, so it is due after them.
const refreshedFired = Promise.withResolvers<void>();
const refreshed = setTimeout(() => { fired++; refreshedFired.resolve(); }, 20).unref();
try {
refreshed.refresh();
expect(timers.pending.has(refreshed), "REFRESHED_TIMEOUT_IS_LIVE").toBe(true);
await Bun.sleep(60);
expect(fired).toBe(1);
await refreshedFired.promise;
expect(fired, "ONLY_THE_REFRESHED_TIMEOUT_FIRES").toBe(1);
expect(timers.pending.size).toBe(0);
refreshed.refresh();
expect(timers.pending.has(refreshed), "FIRED_THEN_REFRESHED_TIMEOUT_IS_LIVE").toBe(true);
Expand Down
Loading
Loading