From d294193c31a02cc856292708a63904f0271b5685 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 10:47:43 +0000 Subject: [PATCH 1/2] test: justify or replace ui-server negative-observation windows (#3332 slice 6) Windows behind a real write-worker hold now read main-thread flags when the hold answers (the worker replies in order on one port); database rows are read while the hold still runs. In-memory holds wait for the held step to start, then one macrotask. Native timers and loopback sockets use ordered markers. Failure maxima and the remaining windows state their reason in source. No timeout changed. Refs #3332 Co-Authored-By: Claude Opus 5.5 --- docs/process/test-waits.md | 5 +++ .../fixtures/relayed-runtime-traffic-probe.ts | 4 ++ .../tests/native-observation-storage.test.ts | 4 +- .../ui-server/tests/app-http-drain.test.ts | 2 + .../tests/app-metadata-cancellation.test.ts | 1 + .../tests/app-writer-cleanup.test.ts | 9 +++++ .../tests/app-writes-offloop.test.ts | 18 ++++++--- .../tests/close-cancels-shared-runs.test.ts | 1 + .../ui-server/tests/dialogue-storage.test.ts | 2 + .../tests/drafts-settings-offloop.test.ts | 14 ++++--- .../tests/helpers/contextual-refusals.ts | 3 ++ .../tests/host-fallback-gates.test.ts | 5 +++ .../ui-server/tests/http-mount-timers.test.ts | 15 ++++--- .../tests/inbox-writes-offloop.test.ts | 7 ++-- .../tests/live-history-adapters.test.ts | 5 ++- .../tests/native-journal-observer.test.ts | 3 +- .../tests/private-index-stdio-release.test.ts | 4 +- packages/ui-server/tests/push-drain.test.ts | 10 +++-- .../ui-server/tests/reference-source.test.ts | 5 ++- .../ui-server/tests/reference-tools.test.ts | 5 ++- .../tests/reference-writes-offloop.test.ts | 10 ++++- .../tests/retry-proposal-offloop.test.ts | 23 +++++++---- .../tests/schedule-ignore-admission.test.ts | 3 ++ .../tests/storage-maintenance-owners.test.ts | 4 +- .../ui-server/tests/storage-offloop.test.ts | 19 +++++---- .../tests/storage-scan-offloop.test.ts | 40 +++++++++++-------- packages/ui-server/tests/write-worker.test.ts | 1 + .../tests/writer-gate-offloop.test.ts | 6 +-- 28 files changed, 163 insertions(+), 65 deletions(-) diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 4801bda5ce..833d618324 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -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 diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index ea190f48c7..a49fbd79f2 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -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); } diff --git a/packages/ui-sdk/tests/native-observation-storage.test.ts b/packages/ui-sdk/tests/native-observation-storage.test.ts index 0eae9f56cb..416b8b6bed 100644 --- a/packages/ui-sdk/tests/native-observation-storage.test.ts +++ b/packages/ui-sdk/tests/native-observation-storage.test.ts @@ -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 }; await probe.close(); const sync = handle.sync; diff --git a/packages/ui-server/tests/app-http-drain.test.ts b/packages/ui-server/tests/app-http-drain.test.ts index 194355210e..5791334db8 100644 --- a/packages/ui-server/tests/app-http-drain.test.ts +++ b/packages/ui-server/tests/app-http-drain.test.ts @@ -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); @@ -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});} diff --git a/packages/ui-server/tests/app-metadata-cancellation.test.ts b/packages/ui-server/tests/app-metadata-cancellation.test.ts index 97f50619b0..0938c2f4ea 100644 --- a/packages/ui-server/tests/app-metadata-cancellation.test.ts +++ b/packages/ui-server/tests/app-metadata-cancellation.test.ts @@ -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); }), diff --git a/packages/ui-server/tests/app-writer-cleanup.test.ts b/packages/ui-server/tests/app-writer-cleanup.test.ts index 100f151315..6d66e2ae09 100644 --- a/packages/ui-server/tests/app-writer-cleanup.test.ts +++ b/packages/ui-server/tests/app-writer-cleanup.test.ts @@ -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; @@ -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); @@ -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); diff --git a/packages/ui-server/tests/app-writes-offloop.test.ts b/packages/ui-server/tests/app-writes-offloop.test.ts index 882c92ce60..a9b7d48a0f 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -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(done => { release = () => done(0); }); + const entered = Promise.withResolvers(); 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(); @@ -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(done => { release = done; }); - const classifier = { enabled: true, settled: () => pending, attach: (_sessionId: string, messages: never[]) => messages } as never; + const consulted = Promise.withResolvers(); + 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; diff --git a/packages/ui-server/tests/close-cancels-shared-runs.test.ts b/packages/ui-server/tests/close-cancels-shared-runs.test.ts index 73a9b5de06..97813e9bee 100644 --- a/packages/ui-server/tests/close-cancels-shared-runs.test.ts +++ b/packages/ui-server/tests/close-cancels-shared-runs.test.ts @@ -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); diff --git a/packages/ui-server/tests/dialogue-storage.test.ts b/packages/ui-server/tests/dialogue-storage.test.ts index 89a389d882..0c4f184543 100644 --- a/packages/ui-server/tests/dialogue-storage.test.ts +++ b/packages/ui-server/tests/dialogue-storage.test.ts @@ -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(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();} diff --git a/packages/ui-server/tests/drafts-settings-offloop.test.ts b/packages/ui-server/tests/drafts-settings-offloop.test.ts index 38c332710a..fb1b8e57c3 100644 --- a/packages/ui-server/tests/drafts-settings-offloop.test.ts +++ b/packages/ui-server/tests/drafts-settings-offloop.test.ts @@ -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 }); @@ -226,14 +226,18 @@ test("the turn recorder settles only after its subscription proof has committed" let release!: () => void; const held = new Promise(resolve => { release = resolve; }); let proved = false; - const runtime = createRuntimeStatus(() => new Date(NOW), quietLog, () => held.then(() => { proved = true; })); + const entered = Promise.withResolvers(); + 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; diff --git a/packages/ui-server/tests/helpers/contextual-refusals.ts b/packages/ui-server/tests/helpers/contextual-refusals.ts index 87846663db..1acb0f1b5a 100644 --- a/packages/ui-server/tests/helpers/contextual-refusals.ts +++ b/packages/ui-server/tests/helpers/contextual-refusals.ts @@ -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); diff --git a/packages/ui-server/tests/host-fallback-gates.test.ts b/packages/ui-server/tests/host-fallback-gates.test.ts index 0ef20b2a15..e2606b934e 100644 --- a/packages/ui-server/tests/host-fallback-gates.test.ts +++ b/packages/ui-server/tests/host-fallback-gates.test.ts @@ -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(); @@ -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(); diff --git a/packages/ui-server/tests/http-mount-timers.test.ts b/packages/ui-server/tests/http-mount-timers.test.ts index f4483fac2f..4b58244f57 100644 --- a/packages/ui-server/tests/http-mount-timers.test.ts +++ b/packages/ui-server/tests/http-mount-timers.test.ts @@ -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(); + const live = setTimeout(() => { fired++; liveFired.resolve(); }, 40).unref(); try { expect(timers.pending.has(timeout)).toBe(true); expect(timers.pending.has(interval)).toBe(true); @@ -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 { @@ -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(); + 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); diff --git a/packages/ui-server/tests/inbox-writes-offloop.test.ts b/packages/ui-server/tests/inbox-writes-offloop.test.ts index c7366854e4..6568b19958 100644 --- a/packages/ui-server/tests/inbox-writes-offloop.test.ts +++ b/packages/ui-server/tests/inbox-writes-offloop.test.ts @@ -210,9 +210,10 @@ test("share submission does not wait on the app loop and settles after earlier w let settled = false; const started = shares.start(f.principal.id, "odysseus-turn", undefined, undefined, () => true).then(() => { settled = true; }); expect(performance.now() - at, "INBOX_SHARE_SUBMISSION_NEVER_BLOCKS_APP_LOOP").toBeLessThan(100); - await Bun.sleep(20); - expect(settled, "INBOX_SHARE_WAITS_FOR_EARLIER_COMMITS").toBe(false); - await slow; await started; + // The share's commit is queued on the write worker behind the hold, whose + // replies arrive in order: the share is still waiting when the hold answers. + expect(await slow.then(() => settled), "INBOX_SHARE_WAITS_FOR_EARLIER_COMMITS").toBe(false); + await started; } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/live-history-adapters.test.ts b/packages/ui-server/tests/live-history-adapters.test.ts index 64643e5f83..e5aa0b6f3f 100644 --- a/packages/ui-server/tests/live-history-adapters.test.ts +++ b/packages/ui-server/tests/live-history-adapters.test.ts @@ -131,7 +131,10 @@ for (const engine of ["gemini", "gpt"] as const) { test(`${engine}: no history and no resync keeps current setup shape`, async () => { const { provider, sockets } = loopback(engine); const s = await open(provider, "ithaca-second", 1); - await Bun.sleep(20); + // The socket delivers frames in order: once a later input frame has arrived, + // any history the adapter sent on setup has arrived before it. + s.appendAudio({ utteranceId: "u1", sequence: 0, rate: rate(engine), pcm: new Uint8Array([0, 0]) }); + await until(() => sockets[0]!.some(m => isInput(engine, m))); expect(historyTexts(engine, sockets[0]!)).toEqual([]); if (engine === "gemini") expect(sockets[0]![0].setup.historyConfig).toBeUndefined(); await s.close(); diff --git a/packages/ui-server/tests/native-journal-observer.test.ts b/packages/ui-server/tests/native-journal-observer.test.ts index 82bcde58fb..5bc1c3ce97 100644 --- a/packages/ui-server/tests/native-journal-observer.test.ts +++ b/packages/ui-server/tests/native-journal-observer.test.ts @@ -273,7 +273,8 @@ test("repeating a commit hands its checkpoint over once, and retries it after a const result=await f.observer.observe(); await Promise.all([result.commit(),result.commit()]); const first=await f.next();requested.push(first.id);first.settle(new Error("Odysseus release refused"));await f.observer.releasesSettled(); - await Bun.sleep(50);expect(f.waiting,"NATIVE_REPEATED_COMMIT_RELEASES_ONCE").toEqual([]); + // The release owner has no timers: settled releases leave only continuations, which one macrotask runs. + await new Promise(resolve=>setImmediate(resolve));expect(f.waiting,"NATIVE_REPEATED_COMMIT_RELEASES_ONCE").toEqual([]); await result.commit(); const retry=await f.next();requested.push(retry.id);retry.settle();await f.observer.releasesSettled(); expect(requested,"NATIVE_REPEATED_COMMIT_RETRIES_FAILED_RELEASE").toEqual([result.beforeRoot.id,result.beforeRoot.id]); diff --git a/packages/ui-server/tests/private-index-stdio-release.test.ts b/packages/ui-server/tests/private-index-stdio-release.test.ts index b69fd0396c..b003ec8eba 100644 --- a/packages/ui-server/tests/private-index-stdio-release.test.ts +++ b/packages/ui-server/tests/private-index-stdio-release.test.ts @@ -131,7 +131,9 @@ for (const path of ["masked CLI", "turn tree"] as const) for (const abort of [fa try { expect(await Promise.race([calling.promise.then(() => true), work.then(() => false), Bun.sleep(10_000).then(() => false)]), "SETTLEMENT_REACHES_RELEASE").toBe(true); expect(await Promise.race([child!.exited, Bun.sleep(10_000).then(() => "no exit")]), "EXIT_REPORTED_WHILE_RELEASE_PENDING").toBe(0); - await Bun.sleep(25); + // Exit is reported and the release has been requested: only the withheld release + // stands before settlement, so one macrotask runs every other continuation. + await new Promise(resolve => setImmediate(resolve)); expect(settled, "SETTLEMENT_WAITS_FOR_RELEASE").toBe(false); if (abort) controller.abort(); release.resolve(); diff --git a/packages/ui-server/tests/push-drain.test.ts b/packages/ui-server/tests/push-drain.test.ts index cb3a8a368e..f948c97ea9 100644 --- a/packages/ui-server/tests/push-drain.test.ts +++ b/packages/ui-server/tests/push-drain.test.ts @@ -33,7 +33,9 @@ test("failed bookkeeping still joins a sibling write before delivery and close s try { await started; const closing = f.sender.close().then(() => { closed = true; }, error => { closed = true; return error; }); - await new Promise(resolve => setTimeout(resolve, 20)); + // Everything but the held sibling write is in memory: one macrotask runs + // every continuation that does not wait for it. + await new Promise(resolve => setImmediate(resolve)); expect(settled, "FAILED_BOOKKEEPING_JOINS_SIBLING_WRITE").toBe(false); expect(closed, "DRAIN_JOINS_SIBLING_OF_FAILED_WRITE").toBe(false); release(); @@ -120,8 +122,10 @@ test("settling a delivery cannot remove a reentrant same-kind delivery from the // The first promise has settled; its removal must leave the new owner intact. let settled = false; const closing = f.sender.close().then(() => { settled = true; }); - await Promise.race([started, new Promise(resolve => setTimeout(resolve, 20))]); - await new Promise(resolve => setTimeout(resolve, 20)); + // Once the reentrant delivery holds its bookkeeping, everything else is in + // memory: one macrotask runs every continuation that does not wait for it. + await Promise.race([started, closing]); + await new Promise(resolve => setImmediate(resolve)); expect(settled, "SETTLED_CALL_CANNOT_DELETE_REENTRANT_OWNER").toBe(false); release(); expect(await reentrant).toBe(1); diff --git a/packages/ui-server/tests/reference-source.test.ts b/packages/ui-server/tests/reference-source.test.ts index c22a7a531c..3c72fbb182 100644 --- a/packages/ui-server/tests/reference-source.test.ts +++ b/packages/ui-server/tests/reference-source.test.ts @@ -315,6 +315,7 @@ describe("admission, cancellation and eviction", () => { const waiting = sources.request({ principalId: penelope.id, repository: "https://github.com/odysseus/argo", revision: "main" }); await until(() => state.fetches.length === 1 && sources.activity().waiting === 1); const third = sources.request({ principalId: penelope.id, repository: "https://github.com/odysseus/scylla", revision: "main" }); + // Failure maximum: the refusal settles first on success; the 50 ms branch names a queue that grew. const early = await Promise.race([third.then(() => "admitted", (error: { code?: string }) => error.code ?? "error"), Bun.sleep(50).then(() => "waiting")]); state.gate.resolve(); await Promise.allSettled([running, waiting, third]); @@ -350,6 +351,7 @@ describe("admission, cancellation and eviction", () => { await until(() => state.fetches.some(call => call.repository === PRIVATE)); revokeReferenceGrant(db, { brain: BRAIN, principalId: telemachus.id, id: record.id, now: Date.now() }); await sources.revoke({ grantIds: [record.id], principalIds: [] }); + // Failure maximum: on success the refusal settles first and the 2 s branch is never awaited. const outcome = await Promise.race([request.then(() => "published", () => "refused"), Bun.sleep(2_000).then(() => "running")]); state.gate.resolve(); expect(outcome, "REFERENCE_SOURCE_REVOCATION_CANCELS_REFRESH").toBe("refused"); @@ -543,7 +545,8 @@ describe("review regressions", () => { try { const controller = new AbortController(); controller.abort(); await expect(sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main", signal: controller.signal })).rejects.toMatchObject({ code: "cancelled" }); - await Bun.sleep(20); + // Bun reports an unhandled rejection once the microtask queue drains, so a macrotask comes after it. + await drain(); expect(unobserved, "REFERENCE_SOURCE_ABORTED_REQUEST_OBSERVED").toEqual([]); expect(sources.activity()).toEqual({ active: 0, waiting: 0 }); } finally { process.off("unhandledRejection", track); } diff --git a/packages/ui-server/tests/reference-tools.test.ts b/packages/ui-server/tests/reference-tools.test.ts index e5f7045250..975e4bbc9a 100644 --- a/packages/ui-server/tests/reference-tools.test.ts +++ b/packages/ui-server/tests/reference-tools.test.ts @@ -244,8 +244,10 @@ describe("binding a view is a new mount (#2432, option 1)", () => { while (state.resolves === resolves) await Bun.sleep(1); const controller = new AbortController(); const binding = sources.bindable(telemachus.id, controller.signal).then(() => "bound", (error: Error) => error.message); - expect(await Promise.race([binding, Bun.sleep(20).then(() => "waiting")])).toBe("waiting"); + // The pool and transport are in memory: one macrotask runs the bind up to the held acquisition. + expect(await Promise.race([binding, drain().then(() => "waiting")])).toBe("waiting"); controller.abort(new Error("turn cancelled")); + // Failure maximum: on success the cancelled bind settles first and the 500 ms branch is never awaited. expect(await Promise.race([binding, Bun.sleep(500).then(() => "waiting")]), "REFERENCE_TOOLS_CANCELLED_BIND_RETURNS").toBe("turn cancelled"); open(); (await refreshing).release(); @@ -335,6 +337,7 @@ describe("admission (#2432 review)", () => { const binding = sources.bindable(telemachus.id, controller.signal).then(() => "bound", (error: Error) => error.message); while (!paused) await Bun.sleep(1); controller.abort(new Error("turn cancelled")); + // Failure maximum: on success the cancelled bind settles first and the 500 ms branch is never awaited. expect(await Promise.race([binding, Bun.sleep(500).then(() => "waiting")]), "REFERENCE_TOOLS_CANCELLED_BIND_DURING_SUSPENSION").toBe("turn cancelled"); open(); }); diff --git a/packages/ui-server/tests/reference-writes-offloop.test.ts b/packages/ui-server/tests/reference-writes-offloop.test.ts index ee799b8711..7ddcde8511 100644 --- a/packages/ui-server/tests/reference-writes-offloop.test.ts +++ b/packages/ui-server/tests/reference-writes-offloop.test.ts @@ -70,7 +70,15 @@ async function fixture() { } }; } -/** Observe an earlier held worker without occupying the app loop. */ +/** + * Observe an earlier held worker without occupying the app loop. + * + * Negative window inside a real 300–400 ms write-worker hold. Each caller then + * reads rows the worker commits straight to the database file, so the reads must + * run while the worker is still inside its hold: once the hold answers, the + * worker may already be committing the queued write. 30 ms gives a wrongly + * loop-side commit time to land while staying well inside the hold. + */ async function pending(work: Promise, label: string) { let finished = false; void work.then(() => { finished = true; }, () => { finished = true; }); diff --git a/packages/ui-server/tests/retry-proposal-offloop.test.ts b/packages/ui-server/tests/retry-proposal-offloop.test.ts index ad6cd21455..5e38ae9591 100644 --- a/packages/ui-server/tests/retry-proposal-offloop.test.ts +++ b/packages/ui-server/tests/retry-proposal-offloop.test.ts @@ -152,11 +152,15 @@ test("dispatch waits for the reservation receipt and duplicate frames never disp const reserve = f.catalog.reserveRetry!; const held = f.writer.channel(probe, { table: "odysseus_log" }); await held.ready; let slow: Promise | undefined; - f.catalog.reserveRetry = (...args) => { slow ??= held.call("slow", "Calypso", 300); return reserve(...args); }; + const reserving = Promise.withResolvers(); + f.catalog.reserveRetry = (...args) => { slow ??= held.call("slow", "Calypso", 300); reserving.resolve(); return reserve(...args); }; const first = handleClientMessage(host, ws, frame, connection); dispatched.push(first); - await Bun.sleep(30); - expect(calls, "RETRY_PENDING_RESERVATION_NO_DISPATCH").toEqual([]); - expect(receipts, "RETRY_PENDING_RESERVATION_NO_ACK").toEqual([]); + await Promise.race([reserving.promise, first]); + // The reservation is queued on the write worker behind the hold, whose + // replies arrive in order: nothing that follows it has run when the hold answers. + const pending = await (slow ?? Promise.resolve()).then(() => ({ calls: [...calls], receipts: [...receipts] })); + expect(pending.calls, "RETRY_PENDING_RESERVATION_NO_DISPATCH").toEqual([]); + expect(pending.receipts, "RETRY_PENDING_RESERVATION_NO_ACK").toEqual([]); const duplicate = handleClientMessage(host, ws, frame, connection); dispatched.push(duplicate); await Promise.all([first, duplicate]); await slow; expect(early, "RETRY_COMMITTED_BEFORE_RECEIPT_AND_DISPATCH").toEqual([]); @@ -202,11 +206,14 @@ test("proposal insertion and writing save commit before approval and policy publ expect(proposals.read("athena", "voyage", "policy-voyage", "ithaca")?.state, "POLICY_READ_AFTER_INSERT_SETTLED").toBe("pending"); const writingSlow = held.call("slow", "Circe", 300); approval.resolve(true); - await Bun.sleep(30); + // Wait for the approval's continuations, then read while the worker is still inside the hold. + await new Promise(resolve => setImmediate(resolve)); expect(state(), "POLICY_WRITING_SAVE_STILL_QUEUED").toBe("pending"); - expect(readFileSync(f.path, "utf8"), "POLICY_FILE_UNTOUCHED_BEFORE_WRITING_COMMIT").toBe(original); - expect(publications).toBe(0); - await writingSlow; + // The writing save is queued on the write worker behind the hold, whose + // replies arrive in order: nothing that follows it has run when the hold answers. + const queued = await writingSlow.then(() => ({ file: readFileSync(f.path, "utf8"), publications })); + expect(queued.file, "POLICY_FILE_UNTOUCHED_BEFORE_WRITING_COMMIT").toBe(original); + expect(queued.publications).toBe(0); expect((await result).state, "POLICY_FINAL_SAVE_WORKER_FULL").toBe("updated"); expect(await duplicate).toEqual(await result); await proposals.settled(); diff --git a/packages/ui-server/tests/schedule-ignore-admission.test.ts b/packages/ui-server/tests/schedule-ignore-admission.test.ts index 95e9d03cf1..85797ba58a 100644 --- a/packages/ui-server/tests/schedule-ignore-admission.test.ts +++ b/packages/ui-server/tests/schedule-ignore-admission.test.ts @@ -56,6 +56,9 @@ test("schedule Git waits for an exclusive holder before creating its actual chil try { const held = await f.gate.acquire("exclusive", "Athena maintenance"); f.holds.push(held); const result = f.check("ignored.md"); + // Negative window: the waiting acquisition retries its SQLite row every 5 ms + // (`pollMs`) and reports nothing for a refused attempt, and correct code never + // admits it. 25 ms, about five refused polls, is the only observable. await Bun.sleep(25); expect(f.spawnRows, "SCHEDULE_EXCLUSIVE_OWNER_BLOCKS_PROCESS_CREATION").toEqual([]); held.release(); diff --git a/packages/ui-server/tests/storage-maintenance-owners.test.ts b/packages/ui-server/tests/storage-maintenance-owners.test.ts index cd5a684713..f9f268eb25 100644 --- a/packages/ui-server/tests/storage-maintenance-owners.test.ts +++ b/packages/ui-server/tests/storage-maintenance-owners.test.ts @@ -48,7 +48,9 @@ test("maintenance revalidates authorization after the real cross-process writer const hold = await f.gate.acquire("exclusive", "fixture hold"); const pending = f.boundary.run({ argv: [process.execPath, "-e", 'await Bun.write(process.env.BRAIN_WORKER_DATA_ROOT+"/started.txt","Ithaca");'], env: { PATH: process.env.PATH, BRAIN_ROOT: f.brain }, credentials: false, gate: "shared", purpose: "Storage guard fixture", outputBytes: 1024, assertAuthorized() { if (!allowed) throw Error("authorization revoked"); } }); try { - await Bun.sleep(30); allowed = false; hold.release(); + // run() checks authority synchronously before it waits for the gate, and the + // exclusive hold is released only after revocation: no window is needed. + allowed = false; hold.release(); await expect(pending).rejects.toThrow("authorization revoked"); expect(existsSync(join(f.brain, "started.txt")), "STORAGE_MAINTENANCE_AFTER_GATE_AUTHORITY").toBe(false); } finally { hold.release(); await pending.catch(() => {}); await f.close(); } diff --git a/packages/ui-server/tests/storage-offloop.test.ts b/packages/ui-server/tests/storage-offloop.test.ts index 1601c03579..a0f60461ee 100644 --- a/packages/ui-server/tests/storage-offloop.test.ts +++ b/packages/ui-server/tests/storage-offloop.test.ts @@ -79,10 +79,11 @@ test("a held worker keeps flush off the loop and coalesces requests after the in expect(history.status().pending, "STORAGE_PENDING_INCLUDES_IN_FLIGHT").toBe(true); let committed = false; void Promise.resolve(first).then(() => { committed = true; }); - await Bun.sleep(20); - expect(committed, "STORAGE_HELD_FLUSH_DOES_NOT_BLOCK_LOOP").toBe(false); + // Read while the worker is still inside the hold: an inline commit would show here. expect(history.read()!.metadata.state.lastObservedAt).toBe(0); - await held; + // The flush is queued on the write worker behind the hold, whose replies + // arrive in order: it has not settled when the hold answers. + expect(await held.then(() => committed), "STORAGE_HELD_FLUSH_DOES_NOT_BLOCK_LOOP").toBe(false); expect(await second, "STORAGE_COALESCED_FLUSH_RUNS_AFTER_FIRST").toBe(true); expect(history.read()!.metadata.state.lastObservedAt).toBe(start + 60_000); expect(f.db.query("SELECT revision FROM storage_history").get(), "STORAGE_EXACTLY_TWO_ORDERED_FLUSH_COMMITS").toEqual({ revision: 2 }); @@ -112,16 +113,18 @@ test("sampling ticks submit without waiting or overlapping and close awaits the expect(result, "STORAGE_TICK_RETURNS_SYNCHRONOUSLY").toBeUndefined(); expect(flush, "STORAGE_TICK_NEVER_OVERLAPS_FLUSH").toHaveBeenCalledTimes(1); expect(sweep, "STORAGE_TICK_NEVER_OVERLAPS_SWEEP").toHaveBeenCalledTimes(1); - let released = false; void held.then(() => { released = true; }); - await Bun.sleep(20); + let released = false, closed = false; + // The tick's writes, and the close's final flush, are queued on the write + // worker behind the hold, whose replies arrive in order: none has committed + // when the hold answers. + const queued = held.then(() => { released = true; return closed; }); expect(released, "STORAGE_TICK_DOES_NOT_WAIT_FOR_FLUSH_SWEEP").toBe(false); + // Read while the worker is still inside the hold: an inline commit would show here. expect(history.read()!.metadata.state.lastObservedAt).toBe(start); // A final observation arrives while the tick's write is still queued. f.advance(start + 120_000); history.offer(observation(f.now())); - let closed = false; const closing = sampling.close().then(() => { closed = true; }); - await Bun.sleep(20); - expect(closed, "STORAGE_CLOSE_WAITS_FOR_FINAL_FLUSH").toBe(false); + expect(await queued, "STORAGE_CLOSE_WAITS_FOR_FINAL_FLUSH").toBe(false); await closing; expect(history.read()!.metadata.state.lastObservedAt, "STORAGE_CLOSE_PRESERVES_LAST_OBSERVATION").toBe(start + 120_000); expect(history.status().pending).toBe(false); diff --git a/packages/ui-server/tests/storage-scan-offloop.test.ts b/packages/ui-server/tests/storage-scan-offloop.test.ts index 76eb81efb4..37b7a71fbe 100644 --- a/packages/ui-server/tests/storage-scan-offloop.test.ts +++ b/packages/ui-server/tests/storage-scan-offloop.test.ts @@ -94,17 +94,20 @@ test("held acquisition prevents collector launch and held finish prevents servin const held = queue.call("slow", "Ithaca acquire", 300); let answered = false; const starting = Promise.resolve(f.storage.start(f.owner.id, true)).then(value => { answered = true; return value; }); - await Bun.sleep(20); - expect(answered, "STORAGE_SCAN_START_WAITS_FOR_LEASE").toBe(false); - expect(collectorCalls, "STORAGE_SCAN_NO_COLLECTOR_BEFORE_LEASE_COMMIT").toBe(0); + // Each commit below is queued on the write worker behind a hold, whose + // replies arrive in order: nothing that follows it has run when the hold answers. + // Read while the worker is still inside the hold: an inline commit would show here. expect(f.db.query("SELECT job_id FROM storage_scan_leases").get()).toBeNull(); - await held; await starting; + const leasing = await held.then(() => ({ answered, collectorCalls })); + expect(leasing.answered, "STORAGE_SCAN_START_WAITS_FOR_LEASE").toBe(false); + expect(leasing.collectorCalls, "STORAGE_SCAN_NO_COLLECTOR_BEFORE_LEASE_COMMIT").toBe(0); + await starting; await enteredFinish.promise; - await Bun.sleep(20); - expect(collectorCalls, "STORAGE_SCAN_COLLECTOR_REALLY_RAN").toBe(1); - expect(leaseSeen, "STORAGE_SCAN_COLLECTOR_SEES_COMMITTED_LEASE").toBe(true); - expect(f.storage.status(f.owner.id).snapshot, "STORAGE_SCAN_NO_RESULT_BEFORE_FINISH_COMMIT").toBeNull(); - await heldFinish; await f.storage.idle(); + const finishing = await heldFinish!.then(() => ({ collectorCalls, leaseSeen, snapshot: f.storage.status(f.owner.id).snapshot })); + expect(finishing.collectorCalls, "STORAGE_SCAN_COLLECTOR_REALLY_RAN").toBe(1); + expect(finishing.leaseSeen, "STORAGE_SCAN_COLLECTOR_SEES_COMMITTED_LEASE").toBe(true); + expect(finishing.snapshot, "STORAGE_SCAN_NO_RESULT_BEFORE_FINISH_COMMIT").toBeNull(); + await f.storage.idle(); expect(f.storage.status(f.owner.id).snapshot, "STORAGE_SCAN_RESULT_AFTER_FINISH_COMMIT").not.toBeNull(); expect(f.db.query("SELECT job_id FROM storage_scan_leases").get()).toEqual({ job_id: null }); } finally { collect.mockRestore(); finish.mockRestore(); await f.close(); } @@ -125,12 +128,13 @@ test("collector completion waits for registration and unregister commits", async unregister(pid) { registeredBeforeUnregister = registered; unregistration = queue.call("slow", "Ithaca unregister", 300); unregistering.resolve(); return f.shared.unregister(scan, pid); }, }, }).then(value => { done = true; return value; }); - await registering.promise; await Bun.sleep(20); - expect(done, "STORAGE_SCAN_COLLECTOR_WAITS_FOR_REGISTER").toBe(false); - await registration; await unregistering.promise; await Bun.sleep(20); + // Each commit is queued on the write worker behind a hold, whose replies + // arrive in order: the collector has not completed when the hold answers. + await registering.promise; + expect(await registration!.then(() => done), "STORAGE_SCAN_COLLECTOR_WAITS_FOR_REGISTER").toBe(false); + await unregistering.promise; expect(registeredBeforeUnregister, "STORAGE_SCAN_REGISTER_BEFORE_UNREGISTER").toBe(true); - expect(done, "STORAGE_SCAN_COLLECTOR_WAITS_FOR_UNREGISTER").toBe(false); - await unregistration; + expect(await unregistration!.then(() => done), "STORAGE_SCAN_COLLECTOR_WAITS_FOR_UNREGISTER").toBe(false); expect(await result).toEqual({ destination: "Ithaca" }); expect(f.shared.check(scan).workers_json).toBe("[]"); await f.shared.finish(scan, false, false, at); @@ -269,9 +273,11 @@ test("staging removal waits for the maintenance item intent on the worker", asyn const sites = await watchWriteSites(f.db, f.writer, ["storage_scan_leases", "storage_maintenance_operations"]); await queue.ready; await m.operations.start(f.owner.id, { id, operation: "cleanup-staging" }); - await entered.promise; await Bun.sleep(20); - expect(existsSync(target), "STORAGE_STAGING_RETAINED_UNTIL_ITEM_INTENT_COMMIT").toBe(true); - await held; await m.operations.idle(); + // The item intent is queued on the write worker behind the hold, whose + // replies arrive in order: removal has not run when the hold answers. + await entered.promise; + expect(await held!.then(() => existsSync(target)), "STORAGE_STAGING_RETAINED_UNTIL_ITEM_INTENT_COMMIT").toBe(true); + await m.operations.idle(); expect(durableBeforeRemoval, "STORAGE_STAGING_ITEM_INTENT_DURABLE_BEFORE_REMOVAL").toBe(true); expect(existsSync(target)).toBe(false); expect(await m.operations.receipt(f.owner.id, id)).toMatchObject({ state: "complete", outcome: { items: [{ id: itemId, state: "cleaned" }] } }); diff --git a/packages/ui-server/tests/write-worker.test.ts b/packages/ui-server/tests/write-worker.test.ts index 1b38d92db8..8d69708a02 100644 --- a/packages/ui-server/tests/write-worker.test.ts +++ b/packages/ui-server/tests/write-worker.test.ts @@ -154,6 +154,7 @@ import * as probe from ${JSON.stringify(join(import.meta.dir, "fixtures/write-wo const db = createUiDb(${JSON.stringify(join(root, "ui.db"))}), voyage = openSqliteWriter(db).channel(probe, { table: "odysseus_log" }); await voyage.call("log", "Ithaca"); console.log("committed");\n`); const child = Bun.spawn([process.execPath, script], { stdout: "pipe", stderr: "pipe" }); + // Failure maximum: an idle worker lets the child exit at once; the 10 s branch only names a held process. const exited = await Promise.race([child.exited, Bun.sleep(10_000).then(() => "running")]); if (exited === "running") child.kill(); expect(exited, "WRITE_WORKER_IDLE_DOES_NOT_HOLD_PROCESS").toBe(0); diff --git a/packages/ui-server/tests/writer-gate-offloop.test.ts b/packages/ui-server/tests/writer-gate-offloop.test.ts index 308e846e08..238848d132 100644 --- a/packages/ui-server/tests/writer-gate-offloop.test.ts +++ b/packages/ui-server/tests/writer-gate-offloop.test.ts @@ -63,9 +63,9 @@ test("a release counts for this process's next acquisition at once, and settles let settled = false; void released.then(() => { settled = true; }); const next = gate.acquire("exclusive", "revert:ithaca"); - await Bun.sleep(50); - expect(settled, "GATE_RELEASE_SETTLES_AFTER_ITS_COMMIT").toBe(false); - await slow; + // The release commit is queued on the write worker behind the hold, whose + // replies arrive in order: the release has not settled when the hold answers. + expect(await slow.then(() => settled), "GATE_RELEASE_SETTLES_AFTER_ITS_COMMIT").toBe(false); await released; expect(row(f, first.id), "GATE_RELEASE_COMMITTED").toBeNull(); // Without seeing the release it would wait a whole poll. From c857a2b7f6762a195ed5f8a6550771d195a61fee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 11:07:06 +0000 Subject: [PATCH 2/2] test: replace the remaining storage-scan-offloop maintenance and cancel windows (#3332 slice 6) Refs #3332 Co-Authored-By: Claude Opus 5.5 --- .../tests/storage-scan-offloop.test.ts | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/packages/ui-server/tests/storage-scan-offloop.test.ts b/packages/ui-server/tests/storage-scan-offloop.test.ts index 37b7a71fbe..727b38b768 100644 --- a/packages/ui-server/tests/storage-scan-offloop.test.ts +++ b/packages/ui-server/tests/storage-scan-offloop.test.ts @@ -174,10 +174,11 @@ test("maintenance route waits for its receipt and cancellation waits for its dur const held = queue.call("slow", "Ithaca start", 300); let answered = false; const response = Promise.resolve(app.request("/api/storage/maintenance", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, operation: "pack-git" }) })).then(value => { answered = true; return value; }); - await Bun.sleep(20); - expect(answered, "STORAGE_MAINTENANCE_ROUTE_WAITS_FOR_RECEIPT").toBe(false); + // Read while the worker is still inside the hold: an inline commit would show here. expect(f.db.query("SELECT id FROM storage_maintenance_operations").get()).toBeNull(); - await held; + // The receipt is queued on the write worker behind the hold, whose replies + // arrive in order: the route has not answered when the hold answers. + expect(await held.then(() => answered), "STORAGE_MAINTENANCE_ROUTE_WAITS_FOR_RECEIPT").toBe(false); const answer = await response; expect(answer.status).toBe(202); expect(await answer.json(), "STORAGE_MAINTENANCE_ROUTE_COMMITTED_RECEIPT").toMatchObject({ id, state: "waiting" }); @@ -186,10 +187,11 @@ test("maintenance route waits for its receipt and cancellation waits for its dur expect(f.db.query("SELECT state FROM storage_maintenance_operations").get(), "STORAGE_MAINTENANCE_RUNNING_INTENT_BEFORE_OWNER").toEqual({ state: "running" }); const slowCancel = queue.call("slow", "Ithaca cancel", 300); const cancelling = m.operations.cancel(f.owner.id, id); - await Bun.sleep(20); - expect(m.ownerCancelled(), "STORAGE_MAINTENANCE_NO_ABORT_BEFORE_CANCEL_COMMIT").toBe(false); + // Read while the worker is still inside the hold: an inline commit would show here. expect(f.db.query("SELECT cancel_requested FROM storage_maintenance_operations").get()).toEqual({ cancel_requested: 0 }); - await slowCancel; await cancelling; await m.cancelled.promise; await m.operations.idle(); + // The cancel flag is queued behind the hold: the owner is not aborted when the hold answers. + expect(await slowCancel.then(() => m.ownerCancelled()), "STORAGE_MAINTENANCE_NO_ABORT_BEFORE_CANCEL_COMMIT").toBe(false); + await cancelling; await m.cancelled.promise; await m.operations.idle(); expect(f.db.query("SELECT cancel_requested FROM storage_maintenance_operations").get()).toEqual({ cancel_requested: 1 }); expect(await m.operations.receipt(f.owner.id, id)).toMatchObject({ state: "unknown", reason: "owner_outcome_unknown" }); expect(await sites.log(), "STORAGE_MAINTENANCE_START_WRITE_CANCEL_WORKER_FULL").toEqual(Array(5).fill("storage_maintenance_operations")); @@ -225,10 +227,13 @@ test("a held scan cancellation leaves authority intact until its commit", async const scan = (await f.shared.acquire(f.owner.id, randomUUID(), scope, 1, true, at))!; await queue.ready; const held = queue.call("slow", "Ithaca cancel", 300); - const cancelling = f.shared.cancel(scan); - await Bun.sleep(20); + let cancelled = false; + const cancelling = Promise.resolve(f.shared.cancel(scan)).then(() => { cancelled = true; }); + // Read while the worker is still inside the hold: an inline commit would show here. expect(f.shared.check(scan).cancel_requested, "STORAGE_SCAN_AUTHORITY_UNTIL_CANCEL_COMMIT").toBe(0); - await held; await cancelling; + // The cancel commit is queued behind the hold: it has not settled when the hold answers. + expect(await held.then(() => cancelled), "STORAGE_SCAN_CANCEL_SETTLES_AFTER_ITS_COMMIT").toBe(false); + await cancelling; expect(() => f.shared.check(scan), "STORAGE_SCAN_AUTHORITY_REVOKED_AFTER_CANCEL_COMMIT").toThrow("storage-scan-authority-lost"); await f.shared.finish(scan, false, true, at); } finally { await f.close(); }