diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 7692517e03..b99436456d 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -135,6 +135,27 @@ any reclassification and its mutation receipts. | ui-react `conversation-endpoint`, `conversation-consent` and `conversation.offline.tsx` | No speech block arrives after the drain; consent alone, or a pending opening after Mute, never reopens capture | The first audio frame below the speaking threshold follows every queued speaking block, instead of a 200 ms drain. Frames are handled on delivery and a capture calls `getUserMedia` synchronously, so the consent cases read the open count once epoch 2 is applied, or at once, instead of after 100 ms or 30 ms. | | Kept, reason in source | ui-react `recording-limits` source starvation; the drains in `dialogue-browser-server` and `contextual-conversation-browser-server` | The starvation is the real-time stimulus. The fixture drains only pace or batch frames: tests poll step replies for every outcome. | | Reclassified, no change | `hygiene-lifecycle-command` 234 (cancellation-safety release cap); `storage-server-command` 39 (startup failure maximum); `liveness-clock` 53 (the page timer under the controlled clock) | Each is a maximum or the timer under test, and its reason is in source. | +| Claude `worker-event-loop.test.ts` and Pi `worker-stdio-release.test.ts`, a turn abort and a withheld stdio release | A worker survives its turn's abort; a turn stays pending while its last teardown step is withheld | The abort listeners run inside `abort()`, and everything after the withheld release runs in-process, so one macrotask replaces the 300 ms and 100 ms windows. | +| ui-sdk `worker-steps-event-loop.test.ts`, identity polls and a rejected release | A timer fires while an identity poll is outstanding; a rejected release is handled | The awaited status request stays outstanding until the 1 ms ticker has fired, instead of 30 ms. One macrotask lets Bun report an unhandled rejection, instead of 20 ms. | +| Negative windows and stimuli kept, reason in source | Claude `worker-event-loop` broker close; Pi `early-cancel-lifecycle` temp close and `worker-stdio-release` late descriptor close; ui-sdk `identity-broker-qualification.native` pulse spans and `worker-steps-event-loop` blocking hold and `settledWithin`; root `build-concurrency` live-peer window and `test-invocation-lifetime` orphan window | The broker close, the native temp close and process exits have no event outside the turn, and awaiting one would attach the handler whose absence is checked. The pulse file is the only witness that a writer outside the listed PIDs stopped. The blocking hold and the late close are the stimulus. The `build-concurrency` window opens only after the failing compiler has exited. | +| ui-server `private-index.test.ts`, the first type-selector turn after server start | The turn's peer-plan wait admits it once the server-start writer finishes, rather than refusing | The gate worker answers in submission order, so a peer check submitted after the wait's first check marks the point where the wait has seen the writer. The writer is released then, instead of 300 ms after the wait starts, and the wait must settle after the release. | +| ui-react `untrusted-marks-runtime.test.ts`, an unsupported server | No cue, control, unknown note or entry row is drawn | The window starts once the detail and list lookups have been answered with the generic 404, instead of when the toolbar appears. An unsupported server draws nothing, so no element marks the answer as rendered; the 200 ms window stays, with that reason in source. | +| ui-react `conversation-controls.offline.tsx`, the pointer resting on the attach tooltip | The tip stays visible while the pointer is on it | A tip that lost its host's hover runs a 150 ms visibility transition to hidden. The test reads the style, then awaits the tip's running animations, instead of 300 ms. | + +The second re-census runs the same expression at `a63e564f02f9b1ab0462bb0ac02dbf8ea6eacee7`. It covers the 66 files that started matching after `3984040f` (128 lines), and the 35 lines added since then to files that already matched. The [bundle](https://github.com/schlessera/brain-kit/tree/e3b6a50630f7dc04322af2ec609af8982a4ec8e1/scripts/measurements/wait-census-3332-2026-11-08) records both lists, the rule-based classification and the reviewed outcome of every row the rules called replaceable or a negative observation. + +| Source / assertion | Attributed role and retained proof | Completion control / native boundary | +| --- | --- | --- | +| core `compute-cli.test.ts`, a signal while a job starts | The signal is recorded while the job is still starting, and the run settles cancelled | The test reads the child's stderr until its handler logs the signal, then opens the stage gate, instead of 200 ms. | +| core `compute-ops.test.ts`, the background driver | A running job stays tracked after each visit; `stop()` during a visit ends visiting | A wrapper on `status` counts answered visits. The test checks after each answered visit, and stops right after one, instead of 30–40 ms. The windows after settle and after stop stay, with their reason in source: no event marks that no timer is armed. | +| core `compute-race.test.ts`, racing admissions | Exactly one of six racers is admitted | Each racer prints `ready` before it polls for the barrier; the barrier is written once all six are ready, instead of after 300 ms. The runner's 50 ms ledger gap stays: it is the stimulus that widens a broken lock's window. | +| ui-server `apify-runs`, `attachment-sweep`, `attachment-extract`, `attachment-reads-delivery` | Racing processes hold the ledger; concurrent uploads hold their reservations; cancel reaches a running extract; a read follows the hello | Ready files from each race child, a poll on `attachment_reservations`, a `Bun.spawn` observer (descriptor restored) and a `ping`/`pong` barrier replace 20–300 ms windows. | +| ui-server `compute-host`, `contextual-status`, `relay-recording-settlement`, `safety-ledger`, `session-run-stages`, `ws-turn-budgets` | In-flight calls finish before cancel settles; no provider acceptance before durable admission; a relay waits for its own egress recording; backend contact waits for safety admission; the turn timeout drains; a late response returns with every report submitted | The host's `clock` option, a marker on the same ordered socket after one macrotask, an egress wrapper recording `admit()`, a pending-count poll plus a contact-time check, the controller's `abort` event and the report count at return replace 5–200 ms windows. | +| Kept, reason in source (ui-server) | `contextual-status` after the provider socket closes; `tainted-destination-ask` shared-card and late-contact windows; `policy-observation-pause` 600 ms against a `Date.now()` deadline; the misbehaving extract worker's hold; `journal-idle-maintenance`, `turn-coordinator` and `ws-turn-budgets` maxima | A closed socket or a loopback contact has no later frame to mark it. The pause deadline is read from `Date.now()`, which no clock in the file reaches. The worker hold is the measured input. The maxima are never awaited on success. | +| ui-react `draft-files.test.ts`, `attachment-queue.test.ts` | The draft is saved only after the 800 ms debounce; the queue asks again only after its busy retry | Fake timers advance the debounce (799 ms, then 1 ms) and the 2 s busy retry, instead of 900 ms sleeps and a real 2 s retry. | +| ui-react `composer-files.offline.tsx`, `hygiene-media.layout.tsx` and its fixture | A held send is sent once on acceptance; `a` sends nothing while checking; a busy preview is ready once the foreign preview frees the scan | The fixture socket delivers the host's acceptance, the key handler's synchronous send is read at once, and the fixture answers `releasePlans` after the foreign preview has finished, instead of 50 ms–1.2 s. The native-loader windows stay with their reason: no page event marks a request that is never made. | +| ui-sdk `refused-launch-gate.test.ts`, a refused or orphaned gated payload | The payload never starts once its gate is refused | The test polls `/proc//stat` (PID and start time) until each gated sandbox is gone, with a 10 s failure maximum, instead of 1.2 s windows. The signal delays stay: they stand in for scheduler latency. | +| Kept real time, reason in source (other packages) | Claude `transcript-archive-event-loop` fsync delay; ui-sdk `inference-relay` and `provider-relay` native socket idle timer; ui-kit `ghost-handoff` and `streaming-handoff` long tasks | Each is the stimulus: slow IO, Bun's native idle timer, which no JS clock advances, and a long task that must also delay the browser's own frames. | ## Continuity settling boundaries diff --git a/packages/core/tests/compute-cli.test.ts b/packages/core/tests/compute-cli.test.ts index 0f76b72667..b214f554bd 100644 --- a/packages/core/tests/compute-cli.test.ts +++ b/packages/core/tests/compute-cli.test.ts @@ -253,15 +253,45 @@ describe("a run interrupted or left unclean", () => { throw new Error(`no new job reached ${state}`); } + /** + * Read `reader` until the text seen so far contains `needle`, the stream + * ends or 10 s pass (a failure maximum, cleared once a read answers); return + * everything read. The run logs a signal from its handler, so that line is + * on stderr once the signal has been recorded. + */ + async function readUntil(reader: ReadableStreamDefaultReader, needle: string, seen = ""): Promise { + const decoder = new TextDecoder(); + const deadline = Date.now() + 10_000; + while (!seen.includes(needle) && Date.now() < deadline) { + let timer: ReturnType | undefined; + const late = new Promise((resolve) => (timer = setTimeout(resolve, deadline - Date.now(), undefined))); + const chunk = await Promise.race([reader.read(), late]); + clearTimeout(timer); + if (!chunk || chunk.done) break; + seen += decoder.decode(chunk.value, { stream: true }); + } + return seen; + } + + /** The rest of `reader`'s stream, after `seen`. */ + async function readToEnd(reader: ReadableStreamDefaultReader, seen: string): Promise { + const decoder = new TextDecoder(); + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) seen += decoder.decode(chunk.value, { stream: true }); + return seen + decoder.decode(); + } + test("a signal while the job is still starting is kept: the job is cancelled once it has started", async () => { rmSync(gate(), { force: true }); const before = new Set(jobIds(faults)); const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/raft.md", "--json", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); proc.kill("SIGTERM"); - await Bun.sleep(200); + // Open the stage only once the run has recorded the signal, so it arrives while the job is starting. + const reader = proc.stderr.getReader(); + const logged = await readUntil(reader, "SIGTERM received"); + expect(logged).toContain("SIGTERM received"); writeFileSync(gate(), ""); - const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), readToEnd(reader, logged), proc.exited]); rmSync(gate(), { force: true }); expect(code).toBe(3); expect(stderr).toContain("SIGTERM received, cancelling"); @@ -276,16 +306,11 @@ describe("a run interrupted or left unclean", () => { const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/route.md", "--human", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); const reader = proc.stderr.getReader(); - let seen = ""; - const deadline = Date.now() + 10_000; - while (!seen.includes(id) && Date.now() < deadline) { - const chunk = await Promise.race([reader.read(), Bun.sleep(500).then(() => undefined)]); - if (chunk?.value) seen += new TextDecoder().decode(chunk.value); - if (chunk?.done) break; - } + const seen = await readUntil(reader, id); expect(seen).toContain(id); proc.kill("SIGINT"); - await Bun.sleep(200); + // Open the stage only once the run has recorded the signal, so it arrives while the job is starting. + expect(await readUntil(reader, "SIGINT received", seen)).toContain("SIGINT received"); writeFileSync(gate(), ""); reader.releaseLock(); const [stdout, code] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); diff --git a/packages/core/tests/compute-ops.test.ts b/packages/core/tests/compute-ops.test.ts index 1faaa6eb7e..6cf1814582 100644 --- a/packages/core/tests/compute-ops.test.ts +++ b/packages/core/tests/compute-ops.test.ts @@ -214,21 +214,51 @@ describe("caller binding", () => { }); describe("the background driver", () => { + /** + * `ops` whose `status` answers count as visits: `visited(n)` resolves once + * the driver's nth status call has answered, before the driver continues. + */ + function counted(ops: ComputeOps) { + let visits = 0; + const waiting: { n: number; resolve: () => void }[] = []; + const wrapped: ComputeOps = { + ...ops, + status: async (input) => { + const result = await ops.status(input); + visits++; + for (const w of waiting.filter((w) => w.n <= visits)) w.resolve(); + return result; + }, + }; + const visited = (n: number) => (visits >= n ? Promise.resolve() : new Promise((resolve) => waiting.push({ n, resolve }))); + return { ops: wrapped, visited }; + } + /** One macrotask: the driver's continuation after an answered visit has run. */ + const macrotask = () => new Promise((resolve) => setImmediate(resolve)); + test("advances tracked jobs through status until settled, then stops visiting", async () => { const { ops, clock, memory } = setup(); const o = ops(TELEMACHUS); const run = await o.run({ provider: "pylos-memory", argv: ["sleep", "5"] }); if (!run.ok) throw new Error(run.error.code); - const driver = createComputeDriver(o, { initialDelayMs: 5, maxDelayMs: 20 }); + const visits = counted(o); + const driver = createComputeDriver(visits.ops, { initialDelayMs: 5, maxDelayMs: 20 }); driver.track(run.job.id); expect(driver.tracked()).toEqual([run.job.id]); - await Bun.sleep(40); - expect(driver.tracked()).toEqual([run.job.id]); + // Each visit answers "running"; the next is armed at least 8 ms later, after this macrotask. + for (const n of [1, 2]) { + await visits.visited(n); + await macrotask(); + expect(driver.tracked()).toEqual([run.job.id]); + } clock.advance(6_000); for (let i = 0; i < 100 && driver.tracked().length > 0; i++) await Bun.sleep(10); expect(driver.tracked()).toEqual([]); expect(await o.status({ job: run.job.id })).toMatchObject({ ok: true, job: { state: "succeeded", cleanup: { state: "released" } } }); const polls = memory.calls.filter((c) => c.method === "poll").length; + // Nothing is tracked, so the driver arms no timer and no visit is due. + // A visit it wrongly scheduled would fire within maxDelayMs (20 ms); the + // window gives it three of those, and there is no event for "no timer". await Bun.sleep(60); expect(memory.calls.filter((c) => c.method === "poll").length).toBe(polls); driver.stop(); @@ -239,11 +269,16 @@ describe("the background driver", () => { const o = ops(TELEMACHUS); const run = await o.run({ provider: "pylos-memory", argv: ["sleep", "600"] }); if (!run.ok) throw new Error(run.error.code); - const driver = createComputeDriver(o, { initialDelayMs: 5, maxDelayMs: 5 }); + const visits = counted(o); + const driver = createComputeDriver(visits.ops, { initialDelayMs: 5, maxDelayMs: 5 }); driver.track(run.job.id); - await Bun.sleep(30); + // Stop once a visit has answered, before the driver re-tracks the job. + await visits.visited(1); driver.stop(); const calls = memory.calls.length; + // Stopped, the driver clears its timer and arms no other. A visit it still + // ran would come within its 5 ms delay; the window gives it eight, and + // there is no event for "no timer". await Bun.sleep(40); expect(memory.calls.length).toBe(calls); expect(memory.calls.some((c) => c.method === "kill" || c.method === "release")).toBe(false); diff --git a/packages/core/tests/compute-race.run.ts b/packages/core/tests/compute-race.run.ts index 23d1d224c3..a9f870e01c 100644 --- a/packages/core/tests/compute-race.run.ts +++ b/packages/core/tests/compute-race.run.ts @@ -4,7 +4,8 @@ * process, and assert its exit. It installs the repository network guard * itself, since a plain `bun` child does not run the test preload. * - * race wait for a barrier file, then run one job; print the result + * race print "ready", wait for a barrier file, then run one job; + * print the result * hold take a compute lock, print "held", and keep it until killed * crash run a job on the local-process provider and SIGKILL this * process at a named point, leaving the record mid-lifecycle @@ -57,6 +58,8 @@ if (mode === "race") { budget: fileBudget(spec.ledger, spec.cap), config: { compute: { providers: { ithaca: { provider: memory.provider, lease: { maxSeconds: 600 }, maxConcurrent: spec.maxConcurrent, hourlyCeilingUsd: spec.ceiling } } } }, }); + // Every racer reports "ready" here; the test writes the barrier only once all have. + console.log("ready"); while (!existsSync(spec.barrier)) await Bun.sleep(2); const result = await svc.run(PENELOPE, { instance: "ithaca", argv: ["sleep", "3600"] }); console.log(JSON.stringify(result.ok ? { ok: true, id: result.job.id } : { ok: false, code: result.code })); diff --git a/packages/core/tests/compute-race.test.ts b/packages/core/tests/compute-race.test.ts index a91257ae62..ed201feafb 100644 --- a/packages/core/tests/compute-race.test.ts +++ b/packages/core/tests/compute-race.test.ts @@ -27,6 +27,26 @@ afterEach(async () => { box?.dispose(); }); +/** A child's stdout one line at a time; `next()` is undefined once the stream ends without one. */ +function lines(stream: ReadableStream) { + const reader = stream.getReader(); + const decoder = new TextDecoder(); + let buffered = ""; + return { + async next(): Promise { + while (!buffered.includes("\n")) { + const chunk = await reader.read(); + if (chunk.done) return undefined; + buffered += decoder.decode(chunk.value, { stream: true }); + } + const at = buffered.indexOf("\n"); + const line = buffered.slice(0, at); + buffered = buffered.slice(at + 1); + return line; + }, + }; +} + async function race(spec: { maxConcurrent: number; ceiling?: number; cap: number }) { box = sandbox(); const barrier = join(box.base, "go"); @@ -35,15 +55,22 @@ async function race(spec: { maxConcurrent: number; ceiling?: number; cap: number const racers = Array.from({ length: RACERS }, () => { const child = Bun.spawn([process.execPath, RUNNER, "race", file], { stdout: "pipe", stderr: "pipe", stdin: "ignore" }); children.push(child); - return child; + return { child, stdout: lines(child.stdout) }; }); - await Bun.sleep(300); + // Release the barrier only once every racer is waiting at it, so all of them contend for admission. + // Bounded, so a racer that never reports ready fails here; the file's + // teardown kills every child it spawned. + let bound: ReturnType | undefined; + try { + const timedOut = new Promise(resolve => { bound = setTimeout(() => resolve("RACER_NEVER_READY"), 10_000); }); + for (const racer of racers) expect(await Promise.race([racer.stdout.next(), timedOut])).toBe("ready"); + } finally { clearTimeout(bound); } writeFileSync(barrier, ""); const results = await Promise.all( - racers.map(async (child) => { - const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + racers.map(async ({ child, stdout }) => { + const [result, stderr] = await Promise.all([stdout.next(), new Response(child.stderr).text(), child.exited]); expect({ code: child.exitCode, stderr: child.exitCode === 0 ? "" : stderr }).toEqual({ code: 0, stderr: "" }); - return JSON.parse(stdout.trim()) as { ok: boolean; code?: string }; + return JSON.parse(result ?? "null") as { ok: boolean; code?: string }; }) ); return { admitted: results.filter((r) => r.ok).length, refused: results.filter((r) => !r.ok).map((r) => r.code) }; diff --git a/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts b/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts index 86d68c21cc..666924dccc 100644 --- a/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts @@ -22,7 +22,10 @@ beforeEach(async () => { listSessionsFn: async () => metadata, log: (_message, error) => errors.push(error), activeSessionIds: () => active }; ({ live, archive } = transcriptPaths(brain, options.env)); mkdirSync(live, { recursive: true }); // Every asynchronous fsync is delayed, as on a host under write load; a - // hook can act as another caller at a chosen sync. + // hook can act as another caller at a chosen sync. Kept real time: the delay + // is the stimulus. Each awaited sync then takes wall time on any host (a + // tmpfs fsync returns at once), so the liveness case's 1 ms interval has a + // chance to run; a fake clock does not slow native IO. const probe = await open(tmpdir(), "r"), handle = Object.getPrototypeOf(probe) as { sync(): Promise }; await probe.close(); const sync = handle.sync; syncs = 0; onSync = undefined; diff --git a/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx b/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx index e35fd42b06..73fd1221a8 100644 --- a/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx +++ b/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx @@ -25,7 +25,11 @@ async function withCard(theme: string, run: (host: HTMLElement) => Promise } } -/** Block the main thread, as a loaded runner does, without touching the component. */ +/** + * Block the main thread, as a loaded runner does, without touching the + * component. Kept real time: the stall is the stimulus. It must also delay the + * browser's own animation ends and frames, which a fake clock cannot hold back. + */ function stallAfter(delay: number, ms: number) { setTimeout(() => { const start = performance.now(); diff --git a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx index 2de860f009..3ea20bd06b 100644 --- a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx +++ b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx @@ -23,7 +23,11 @@ async function withStream(theme: string, run: (host: HTMLElement) => Promise { const start = performance.now(); diff --git a/packages/ui-react/tests/attachment-queue.test.ts b/packages/ui-react/tests/attachment-queue.test.ts index 23a8105e9d..25cae4777f 100644 --- a/packages/ui-react/tests/attachment-queue.test.ts +++ b/packages/ui-react/tests/attachment-queue.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, test, vi } from "bun:test"; import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol"; import { createAttachmentQueue, fileNameHeader, queuedFileCopy, storedFileCopy, type QueuedFile } from "../src/lib/attachment-queue.js"; @@ -66,8 +66,20 @@ test("a lost answer is unknown, never 'not stored'; the drop's reconnect uploads } finally { h.queue.dispose(); } }); +/** `BUSY_RETRY_MS` in attachment-queue.ts: a busy host is asked again after this pause. */ +const BUSY_RETRY = 2_000; +/** Promise turns until `predicate` holds; real under the fake clock, unlike `Bun.sleep`. */ +async function turns(predicate: () => boolean) { + for (let turn = 0; !predicate(); turn++) { + if (turn === 100) throw Error("The queue did not settle."); + await new Promise((resolve) => setImmediate(resolve)); + } +} + test("while connected, a lost answer waits for Upload again, which replays the same key; a busy host is asked again with it too", async () => { - // No automatic loop while the page is online: only Upload again asks. + // No automatic loop while the page is online: only Upload again asks. The + // queue's only clock is its busy-host timer, so a fake clock owns it. + vi.useFakeTimers(); const h = harness((call) => { if (call === 1) throw new TypeError("Failed to fetch"); if (call === 2) return Response.json({ error: "busy" }, { status: 503 }); @@ -75,17 +87,21 @@ test("while connected, a lost answer waits for Upload again, which replays the s }); try { h.queue.add([permit()], DRAFT, { count: 0, bytes: 0 }, null); - await settle(() => h.queue.files[0]?.state === "unknown"); - await Bun.sleep(20); + await turns(() => h.queue.files[0]?.state === "unknown"); + expect(vi.getTimerCount(), "no timer is armed to ask again").toBe(0); + vi.runAllTimers(); expect(h.calls, "nothing asks again on its own while connected").toHaveLength(1); h.queue.retry(h.queue.files[0]!.id); - await settle(() => h.calls.length === 2 && h.queue.files[0]?.state === "waiting"); + await turns(() => h.calls.length === 2 && h.queue.files[0]?.state === "waiting"); // The busy host is asked again after its pause, not at once. + vi.advanceTimersByTime(BUSY_RETRY - 1); expect(h.calls).toHaveLength(2); - await settle(() => h.done.length === 1, 4_000); + vi.advanceTimersByTime(1); + await turns(() => h.done.length === 1); + expect(h.calls).toHaveLength(3); const keys = h.calls.map((c) => new Headers(c.init.headers).get("idempotency-key")); expect(new Set(keys).size).toBe(1); - } finally { h.queue.dispose(); } + } finally { h.queue.dispose(); vi.useRealTimers(); } }, 10_000); test("host refusals are known not stored and say why; a 5xx is a retryable failure", async () => { diff --git a/packages/ui-react/tests/browser/composer-files.offline.tsx b/packages/ui-react/tests/browser/composer-files.offline.tsx index 40537ead00..323690eaf2 100644 --- a/packages/ui-react/tests/browser/composer-files.offline.tsx +++ b/packages/ui-react/tests/browser/composer-files.offline.tsx @@ -255,7 +255,12 @@ test("Send pressed while a file uploads holds once, then sends that file after t expect(s.files.saves.length, "a save bound the file before the send").toBeGreaterThan(0); expect(s.messages()[0]!.draftRef, "sent from the acknowledged revision that binds it").toEqual({ draftId: s.files.saves.at(-1)!.draftId, revision: s.files.saves.length }); expect(s.files.saves.at(-1)!.fileIds).toEqual(s.messages()[0]!.attachmentRefs!.map((r) => r.fileId)); - await new Promise((resolve) => setTimeout(resolve, 1_200)); + // The host's acceptance is the only later input to the hold: it lifts the + // pending send's wait and consumes the draft. `deliver` commits it in + // `flushSync`, so the hold's effect has run again with both changes. + const requestId = s.messages()[0]!.requestId!; + FixtureSocket.last!.deliver({ type: "session_info", sessionId: SESSION, isNew: false, requestId }); + expect(s.root.stores.drafts.getState().sends[requestId]?.state, "the host accepted the send").toBe("accepted"); expect(s.messages(), "the hold sends once").toHaveLength(1); }); diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx index 66157993d8..5e6501ba45 100644 --- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx @@ -211,7 +211,10 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ await expect.poll(shown, { timeout: 2000 }).toBe(true); await s.capture("attach-hover-tooltip"); await userEvent.hover(tip()); - await new Promise(resolve => setTimeout(resolve, 300)); + // A tip that lost its host's hover runs its 150 ms visibility transition to + // hidden. Reading the style starts any such transition; await it to the end. + void getComputedStyle(tip()).visibility; + await Promise.all(tip().getAnimations().map(animation => animation.finished)); expect(shown(), "the pointer can rest on the tooltip").toBe(true); await userEvent.keyboard("{Escape}"); expect(shown(), "Escape dismisses a hover tooltip without moving the pointer").toBe(false); diff --git a/packages/ui-react/tests/browser/hygiene-media.layout.tsx b/packages/ui-react/tests/browser/hygiene-media.layout.tsx index 07053775e5..36d6c1acca 100644 --- a/packages/ui-react/tests/browser/hygiene-media.layout.tsx +++ b/packages/ui-react/tests/browser/hygiene-media.layout.tsx @@ -44,7 +44,11 @@ afterEach(async () => { if (originalTheme === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = originalTheme; }); -const settle = (ms = 200) => new Promise((r) => setTimeout(r, ms)); +// Kept real time: a second media request, or one before Load, would come from +// Chromium's native loader for an element a later render mounts. No page event +// marks a request that is never made, so these cases read the fixture's file +// log after a window in which such a render and its request would arrive. +const settle = (ms: number) => new Promise((r) => setTimeout(r, ms)); const set = async (patch: Record) => (await commands.hygieneServer({ op: "set", id: fixture!.id, patch })) as Fixture; const HARBOUR = ".brain/scratch/2026-07-11/harbour-dawn.jpg"; @@ -290,8 +294,8 @@ test("dark 320: only the latest preview renders; `a` does nothing while checking await expect.poll(() => region()?.dataset.mediaPreviewRegion).toBe("checking"); await destination("places/ithaca/second.jpg"); title().focus(); + // The key handler sends synchronously: when the dispatched key returns, a frame would already be recorded. await userEvent.keyboard("a"); - await settle(); expect(status()).toBe("Preview in progress. You can change your choice."); expect(frames.filter((f) => f.type === "inbox_resolve"), "`a` sends nothing while checking").toEqual([]); await set({ releasePlans: true }); @@ -308,8 +312,8 @@ test("dark 320: another device's running preview answers preview-busy as an aler await set({ foreignPreview: true }); await radio("Persist here").click(); await expect.poll(() => alertText()).toBe("Another device is checking a file. Try again in a moment."); + // Answered once the other device's preview has finished and freed the scan. await set({ releasePlans: true }); - await settle(); await page.getByRole("button", { name: "Try again", exact: true }).click(); await ready("Preview ready"); }); diff --git a/packages/ui-react/tests/draft-files.test.ts b/packages/ui-react/tests/draft-files.test.ts index 8e9683b809..d26ee748e6 100644 --- a/packages/ui-react/tests/draft-files.test.ts +++ b/packages/ui-react/tests/draft-files.test.ts @@ -1,4 +1,4 @@ -import { afterEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, test, vi } from "bun:test"; import type { AttachmentFile, Draft, DraftSaveRequest, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; import { createBrainUiRoot, type BrainUiRoot } from "../src/root.ts"; import { createDraftClient } from "../src/lib/draft-client.ts"; @@ -12,7 +12,10 @@ import { holdsUnsaved } from "../src/stores/draft-state.ts"; // fixtures, an in-memory host, no network. const roots: BrainUiRoot[] = []; -afterEach(() => { for (const r of roots.splice(0)) r.dispose(); }); +// The draft client's save debounce and retry backoff run on a fake clock; the +// in-memory host answers in promise turns, which stay real. +beforeEach(() => { vi.useFakeTimers(); }); +afterEach(() => { for (const r of roots.splice(0)) r.dispose(); vi.useRealTimers(); }); const SESSION = "odysseus-ithaca"; function original(fileId: string, name = "ithaca-permit.pdf"): AttachmentFile { return { fileId, name, path: `.brain-ui/attachments/${fileId}/${name}`, mediaType: "application/pdf", bytes: 2_400_000, sha256: "b".repeat(64), kind: "pdf", reader: "pdf" }; @@ -45,7 +48,26 @@ function scene() { const id = drafts.getState().idFor(SESSION); return { ui, drafts, id, saves, silence: () => { answer = "silent"; } }; } -const pause = () => Bun.sleep(900); +type Scene = ReturnType; +/** `SAVE_DELAY_MS` in draft-client.ts: a pause in typing before a change is saved. */ +const SAVE_DELAY = 800; +/** + * The pause in typing: nothing is saved before the debounce ends; one save + * then starts, and this returns once its answer is applied. + */ +async function pause(s: Scene) { + const before = s.saves.length; + vi.advanceTimersByTime(SAVE_DELAY - 1); + await turn(); + expect(s.saves, "nothing is saved before the pause ends").toHaveLength(before); + vi.advanceTimersByTime(1); + for (let turns = 0; s.saves.length === before || s.drafts.getState().drafts[s.id]?.savingSince != null; turns++) { + if (turns === 100) throw new Error("The save did not settle."); + await turn(); + } +} +/** One macrotask: every promise continuation queued before it has run. */ +const turn = () => new Promise((resolve) => setImmediate(resolve)); test("a hello with composerFiles exposes the host's file limits; without it there are none", () => { const s = scene(); @@ -58,7 +80,7 @@ test("a stored original is saved as a fileIds binding, and reads as saved only a const s = scene(); s.drafts.getState().edit(s.id, SESSION, { text: "Which harbour fees does the permit list?", files: [{ file: PERMIT, lineage: s.id }] }); expect(holdsUnsaved(s.drafts.getState()), "unacknowledged files are at risk").toBe(true); - await pause(); + await pause(s); expect(s.saves).toHaveLength(1); expect(s.saves[0]!.body.fileIds).toEqual([PERMIT.fileId]); const d = s.drafts.getState().drafts[s.id]!; @@ -71,7 +93,7 @@ test("a save that gets no answer never acknowledges the binding", async () => { const s = scene(); s.silence(); s.drafts.getState().edit(s.id, SESSION, { files: [{ file: PERMIT, lineage: s.id }] }); - await pause(); + await pause(s); const d = s.drafts.getState().drafts[s.id]!; expect(s.saves[0]!.body.fileIds).toEqual([PERMIT.fileId]); expect(d.host).toBeNull(); @@ -81,17 +103,17 @@ test("a save that gets no answer never acknowledges the binding", async () => { test("a file of another draft id is never listed; removing the last original unbinds it with an empty list", async () => { const s = scene(); s.drafts.getState().edit(s.id, SESSION, { text: "Crew list for Ithaca", files: [{ file: PERMIT, lineage: s.id }, { file: CREW, lineage: "a-rotated-away-draft" }] }); - await pause(); + await pause(s); expect(s.saves.at(-1)!.body.fileIds).toEqual([PERMIT.fileId]); s.drafts.getState().edit(s.id, SESSION, { files: [] }); - await pause(); + await pause(s); expect(s.saves.at(-1)!.body.fileIds, "the host is told to drop the binding").toEqual([]); }); test("a send takes exactly its originals out of the draft; the content comes back when the frame never left", async () => { const s = scene(); s.drafts.getState().edit(s.id, SESSION, { text: "Read the permit", files: [{ file: PERMIT, lineage: s.id }] }); - await pause(); + await pause(s); const store = s.drafts.getState(); const message = { type: "chat_message" as const, text: "Read the permit", sessionId: SESSION, requestId: "req-permit", attachmentRefs: [{ kind: "attachment" as const, fileId: PERMIT.fileId }] }; const ref = store.beginSend({ requestId: "req-permit", draftId: s.id, sessionId: SESSION, text: "Read the permit", attachments: [], attachmentFiles: [{ file: PERMIT, lineage: s.id }], message }, "Read the permit"); diff --git a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts index d8be07aa3b..781fff96db 100644 --- a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts +++ b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts @@ -198,6 +198,10 @@ let mediaKept = 0; let planRefusals: Record>> = {}; let holdPlans = false; const planHolds: Array<() => void> = []; +/** Told when a plan parks in a hold. */ +let parked: (() => void) | undefined; +/** Another device's preview, started by `foreignPreview`. */ +let foreign: Promise | undefined; let applyMode = ""; let undoMode = ""; const mediaJournal = new Map }>(); @@ -230,6 +234,7 @@ async function mediaPlan(args: string[], signal?: AbortSignal) { if (holdPlans) await new Promise((resolve, reject) => { planHolds.push(resolve); + parked?.(); signal?.addEventListener("abort", () => reject(new Error("aborted"))); }); const linked = m.links.conversations > 0 ? "linked" : m.source === "scratch" && m.links.state !== "complete" ? "unknown" : "unlinked"; @@ -555,14 +560,21 @@ app.post("/fixture", async (c) => { if (p.mediaFiles) { mediaFiles = p.mediaFiles === "default" ? MEDIA_DEFAULT : p.mediaFiles; mediaDone.clear(); mediaKept = 0; } if (p.planRefusals) planRefusals = p.planRefusals; if (p.holdPlans !== undefined) holdPlans = p.holdPlans; - if (p.releasePlans) { holdPlans = false; for (const release of planHolds.splice(0)) release(); } + if (p.releasePlans) { + holdPlans = false; for (const release of planHolds.splice(0)) release(); + // The other device's preview has finished, and freed the scan, when this answers. + await foreign; foreign = undefined; + } if (p.applyMode !== undefined) applyMode = p.applyMode; if (p.undoMode !== undefined) undoMode = p.undoMode; if (p.foreignPreview) { const current = review.read().action!; holdPlans = true; - void review.preview(penelope.id, { itemId: current.id, optionId: "media-delete", expectedVersion: current.version, input: null }).catch(() => {}); - await new Promise((r) => setTimeout(r, 50)); + const inPlan = new Promise((resolve) => { parked = resolve; }); + foreign = review.preview(penelope.id, { itemId: current.id, optionId: "media-delete", expectedVersion: current.version, input: null }).catch(() => {}); + // Its scan is running once its plan parks in the hold (or it ended without one). + await Promise.race([inPlan, foreign]); + parked = undefined; } if (p.start) await review.command(principal.id, "start"); // The real media flow (#2783): boot it, then read its bytes, counts and remote, or kill and boot it again. diff --git a/packages/ui-react/tests/untrusted-marks-runtime.test.ts b/packages/ui-react/tests/untrusted-marks-runtime.test.ts index bdc0107807..f3fbc5cf25 100644 --- a/packages/ui-react/tests/untrusted-marks-runtime.test.ts +++ b/packages/ui-react/tests/untrusted-marks-runtime.test.ts @@ -411,10 +411,17 @@ describe.skipIf(!executablePath)("untrusted marks in the real Files panel", () = const unsupported = await open("owner", 1440, 900, "light"); try { await unsupported.page.route("**/api/files/untrusted**", route => route.fulfill({ status: 404, contentType: "text/plain", body: "404 Not Found" })); + const lookup = (part: string) => unsupported.page.waitForResponse(response => response.url().includes(part) && response.status() === 404); + const list = lookup("/api/files/untrusted/list"); await unsupported.page.reload(); await unsupported.page.waitForFunction("window.__marks !== undefined"); + const detail = lookup(`/api/files/untrusted?path=${encodeURIComponent(MESSAGE)}`); await openFile(unsupported.page, MESSAGE); + await Promise.all([list, detail]); await unsupported.page.getByRole("button", { name: "Copy path" }).waitFor(); + // Both lookups have been answered. An unsupported server draws nothing, so + // no element or state change marks the answer having been rendered: this + // window lets a wrongly drawn cue, control or entry row commit. await Bun.sleep(200); expect(await unsupported.page.locator("[data-untrusted-cue], [data-untrusted-control], [data-untrusted-unknown], [data-untrusted-entry]").count(), "UNSUPPORTED_NOTHING").toBe(0); } finally { await unsupported.context.close(); } diff --git a/packages/ui-sdk/tests/inference-relay.test.ts b/packages/ui-sdk/tests/inference-relay.test.ts index bc65b2da52..d41ca99750 100644 --- a/packages/ui-sdk/tests/inference-relay.test.ts +++ b/packages/ui-sdk/tests/inference-relay.test.ts @@ -143,6 +143,9 @@ describe("inference relay", () => { test("a stream that idles longer than Bun's default idle timeout still arrives whole (#3441)", async () => { // A model writing one large tool input can send nothing for over 10s. + // Kept real time: the timeout under test is Bun's native socket idle timer + // (10 s by default), which no JavaScript clock advances. 15 s outlasts it + // by 5 s. const paused = Bun.serve({ hostname: "127.0.0.1", port: 0, idleTimeout: 0, fetch: () => { let pulls = 0; return new Response(new ReadableStream({ async pull(controller) { diff --git a/packages/ui-sdk/tests/provider-relay.test.ts b/packages/ui-sdk/tests/provider-relay.test.ts index c955c3d347..8ba19772f1 100644 --- a/packages/ui-sdk/tests/provider-relay.test.ts +++ b/packages/ui-sdk/tests/provider-relay.test.ts @@ -296,6 +296,8 @@ describe("second review", () => { test("a response body that idles longer than Bun's default idle timeout still arrives whole (#3441)", async () => { // Bun closes a started response that sends nothing for 10s unless the server disables idleTimeout. + // Kept real time: that idle timer is native, so no JavaScript clock advances + // it. 15 s outlasts it by 5 s. reply = () => new Response(new ReadableStream({ async start(controller) { controller.enqueue(new TextEncoder().encode('{"usage":')); await Bun.sleep(15_000); diff --git a/packages/ui-sdk/tests/refused-launch-gate.test.ts b/packages/ui-sdk/tests/refused-launch-gate.test.ts index f0e23b12e6..7809b2bded 100644 --- a/packages/ui-sdk/tests/refused-launch-gate.test.ts +++ b/packages/ui-sdk/tests/refused-launch-gate.test.ts @@ -12,7 +12,9 @@ import { createWorkerStatusPipe, type WorkerStatusSupervisor } from "../src/serv // yet let die. Only a gate that waits for their deaths keeps the payload out. // The live launch now gates in the sandbox and refuses EOF itself (#3392); the // fixtures below keep bubblewrap's EOF-opening --block-fd on purpose, so they -// prove this ordering as a guard of its own. +// prove this ordering as a guard of its own. The delays are real time: they +// stand in for scheduler latency before a native process dies, which a fake +// clock cannot hold back. const SIGNAL_DELAY_MS = 200; const PID_SIGNAL_DELAY_MS = 2 * SIGNAL_DELAY_MS; @@ -31,6 +33,31 @@ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +/** `/proc//stat` after the command name: [state, ppid, ..., starttime at 19]. */ +function stat(pid: number): string[] | undefined { + try { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" "); } catch { return undefined; } +} +/** A process by PID and kernel start time, so a recycled PID never matches. */ +function identity(pid: number) { return { pid, start: stat(pid)?.[19] }; } +const childrenOf = (pid: number) => { try { return readFileSync(`/proc/${pid}/task/${pid}/children`, "utf8").trim(); } catch { return ""; } }; +/** + * Resolves once none of these gated sandbox processes can run code: gone, + * recycled or a zombie. Each is its PID namespace's first process, so its + * death ends every process that could start the payload, and a payload the + * gate released has written its marker by then. + */ +async function sandboxesDead(gated: { pid: number; start: string | undefined }[]) { + const deadline = Date.now() + 10_000; + const running = ({ pid, start }: { pid: number; start: string | undefined }) => { + const fields = stat(pid); + return fields !== undefined && fields[19] === start && !["Z", "X", "x"].includes(fields[0]!); + }; + while (gated.some(running)) { + if (Date.now() >= deadline) throw Error(`GATED_SANDBOX_NEVER_DIED ${JSON.stringify(gated.filter(running))}`); + await Bun.sleep(5); + } +} + function delayedKills(child: T): T { const kill = child.kill.bind(child); child.kill = (signal?: NodeJS.Signals | number) => { @@ -71,9 +98,12 @@ test("a refused governed launch never starts its payload when bubblewrap dies la command: ["/bin/sh", "-c", "printf Odysseus > payload-started.md"] }); } catch (error) { refusal = error; } finally { hook.mockRestore(); } expect(supervisor, "the launch spawned bubblewrap").toBeDefined(); + // The refusal stopped bubblewrap; its kill is still delayed, so it has not reaped its sandbox. + const gated = childrenOf(supervisor!.pid).split(/\s+/).filter(Boolean).map(pid => identity(Number(pid))); + expect(gated, "bubblewrap forked its sandbox").not.toEqual([]); await supervisor!.exited; - // The gate closes only after the supervisor's exit; give a released payload time to write. - await Bun.sleep(3 * PID_SIGNAL_DELAY_MS); + // The gate closes only after the supervisor's exit, and a released payload runs before its sandbox dies. + await sandboxesDead(gated); expect(String(refusal)).toContain("retained folder mount points are unavailable"); expect(existsSync(join(brain, "payload-started.md")), "UNQUALIFIED_FOLDER_PAYLOAD_NEVER_STARTS").toBe(false); }, 20_000); @@ -91,12 +121,13 @@ test("closing an unreleased gate kills a sandbox whose status was never read", a try { // Wait until bubblewrap has forked its gated sandbox process. const deadline = Date.now() + 5_000; - const children = () => { try { return readFileSync(`/proc/${child.pid}/task/${child.pid}/children`, "utf8").trim(); } catch { return ""; } }; + const children = () => childrenOf(child.pid); while (!children() && child.exitCode === null && Date.now() < deadline) await Bun.sleep(5); expect(children(), "bubblewrap forked its sandbox").not.toBe(""); + const gated = children().split(/\s+/).map(pid => identity(Number(pid))); channel.close(supervisor); await child.exited; - await Bun.sleep(3 * PID_SIGNAL_DELAY_MS); + await sandboxesDead(gated); expect(existsSync(marker), "REFUSED_GATE_PAYLOAD_NEVER_STARTS").toBe(false); } finally { child.kill("SIGKILL"); await child.exited; } }, 20_000); @@ -114,12 +145,13 @@ test("closing an unreleased gate kills a verified sandbox that outlived its reap let gated: number | undefined; try { gated = channel.childPid(child.pid, Date.now() + 5_000); + const sandbox = identity(gated); channel.closeWriter(); child.kill("SIGKILL"); await child.exited; expect(child.signalCode, "bubblewrap was reaped").toBe("SIGKILL"); channel.close(child); - await Bun.sleep(3 * PID_SIGNAL_DELAY_MS); + await sandboxesDead([sandbox]); expect(existsSync(marker), "ORPHANED_GATED_PAYLOAD_NEVER_STARTS").toBe(false); } finally { processKill?.mockRestore(); diff --git a/packages/ui-server/tests/apify-runs.test.ts b/packages/ui-server/tests/apify-runs.test.ts index ba2aa67eba..d25f5f6c7c 100644 --- a/packages/ui-server/tests/apify-runs.test.ts +++ b/packages/ui-server/tests/apify-runs.test.ts @@ -6,7 +6,7 @@ * Actor and its prices are fictional, and nothing reaches the network. */ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; @@ -410,9 +410,18 @@ describe("races and shared accounting", () => { const child = join(import.meta.dir, "fixtures", "apify-ledger-race-child.ts"); openLedger(); const procs = [0, 1, 2, 3].map(index => Bun.spawn([process.execPath, child, ledgerPath, go, String(index)], { stdout: "pipe", stderr: "pipe" })); - await Bun.sleep(300); - writeFileSync(go, ""); - const outputs = await Promise.all(procs.map(async proc => ({ code: await proc.exited, out: (await new Response(proc.stdout).text()).trim(), err: await new Response(proc.stderr).text() }))); + // Every child has opened the ledger and is waiting at the start line before + // it opens, so all four contend for the allowance at once. + const ready = procs.map((_, index) => `${go}.${index}.ready`); + let outputs: { code: number; out: string; err: string }[]; + try { + // The deadline is a failure maximum: a child that never gets ready fails + // the named check instead of the runner's timeout. + for (const end = Date.now() + 10_000; !ready.every(path => existsSync(path)) && procs.every(proc => proc.exitCode === null) && Date.now() < end;) await Bun.sleep(5); + expect(ready.every(path => existsSync(path)), "APIFY_RACE_CHILDREN_READY").toBe(true); + writeFileSync(go, ""); + outputs = await Promise.all(procs.map(async proc => ({ code: await proc.exited, out: (await new Response(proc.stdout).text()).trim(), err: await new Response(proc.stderr).text() }))); + } finally { for (const proc of procs) if (proc.exitCode === null) proc.kill(); } for (const output of outputs) expect(output.code, `APIFY_RACE_CHILD_EXIT: ${output.err}`).toBe(0); const results = outputs.map(output => output.out); expect(results.filter(result => result === "admitted"), `APIFY_TWO_PROCESS_RACE: ${results.join(",")}`).toHaveLength(1); diff --git a/packages/ui-server/tests/attachment-extract.test.ts b/packages/ui-server/tests/attachment-extract.test.ts index 7340b795bf..ba03cc2be3 100644 --- a/packages/ui-server/tests/attachment-extract.test.ts +++ b/packages/ui-server/tests/attachment-extract.test.ts @@ -85,14 +85,34 @@ test("wall clock, CPU and memory bounds stop the child, and the rest of the host test("cancelling the turn kills a running child and drops a queued one", async () => { const single = createExtractor({ concurrency: 1 }, { worker: MISBEHAVING }); const controller = new AbortController(); - const running = single.extract(new Uint8Array(8), request(1, 1, 10_000), controller.signal); - const queued = single.extract(new Uint8Array(8), request(1, 1, 10_000), controller.signal); - await Bun.sleep(200); - const at = Date.now(); - controller.abort(); - expect(await running, "EXTRACT_CANCEL_RUNNING").toEqual({ outcome: "cancelled" }); - expect(await queued, "EXTRACT_CANCEL_QUEUED").toEqual({ outcome: "cancelled" }); - expect(Date.now() - at).toBeLessThan(2_000); + // Observe the first child's spawn. The extractor arms its abort listener in + // the same synchronous step, so once the spawn has returned the child is + // running and cancellable, and the second read is waiting for its slot. + const descriptor = Object.getOwnPropertyDescriptor(Bun, "spawn")!; + const spawned = Promise.withResolvers(); + Object.defineProperty(Bun, "spawn", { ...descriptor, value: (...args: Parameters) => { + const child = (descriptor.value as typeof Bun.spawn)(...args); + spawned.resolve(); + return child; + } }); + try { + const running = single.extract(new Uint8Array(8), request(1, 1, 10_000), controller.signal); + const queued = single.extract(new Uint8Array(8), request(1, 1, 10_000), controller.signal); + // Bounded, so a read that settles without spawning, or never spawns, fails + // here and the finally below still restores Bun.spawn. + let bound: ReturnType | undefined; + try { + await Promise.race([spawned.promise, + running.then(result => { throw new Error(`EXTRACT_SETTLED_BEFORE_SPAWN: ${JSON.stringify(result)}`); }), + new Promise((_, reject) => { bound = setTimeout(() => reject(new Error("EXTRACT_NEVER_SPAWNED")), 10_000); })]); + } finally { clearTimeout(bound); } + const at = Date.now(); + controller.abort(); + expect(await running, "EXTRACT_CANCEL_RUNNING").toEqual({ outcome: "cancelled" }); + expect(await queued, "EXTRACT_CANCEL_QUEUED").toEqual({ outcome: "cancelled" }); + expect(Date.now() - at).toBeLessThan(2_000); + } finally { Object.defineProperty(Bun, "spawn", descriptor); } + expect(Object.getOwnPropertyDescriptor(Bun, "spawn"), "EXTRACT_SPAWN_DESCRIPTOR_RESTORED").toEqual(descriptor); // The slot is free again afterwards. expect(await single.extract(new Uint8Array(8), request(1, 1, 10), live())).toEqual({ outcome: "malformed" }); }); diff --git a/packages/ui-server/tests/attachment-reads-delivery.test.ts b/packages/ui-server/tests/attachment-reads-delivery.test.ts index d1339f7ce7..a5cda90274 100644 --- a/packages/ui-server/tests/attachment-reads-delivery.test.ts +++ b/packages/ui-server/tests/attachment-reads-delivery.test.ts @@ -67,7 +67,15 @@ async function harness() { if (frame.type === "server_hello") resolve(); })); ws.send(JSON.stringify({ type: "client_hello", protocolRev: 5, capabilities })); - await Bun.sleep(20); + // The socket's messages are handled in order, so the pong follows the + // hello's handler: the declared capabilities are recorded by then. + const probeId = `hello-${crypto.randomUUID()}`; + const ponged = new Promise((resolve) => ws.addEventListener("message", (event) => { + const frame = JSON.parse(String(event.data)) as ServerMessage; + if (frame.type === "pong" && frame.probeId === probeId) resolve(); + })); + ws.send(JSON.stringify({ type: "ping", probeId })); + await ponged; return { frames, send: (frame: object) => ws.send(JSON.stringify(frame)) }; }; return { principal, call, connect }; diff --git a/packages/ui-server/tests/attachment-sweep.test.ts b/packages/ui-server/tests/attachment-sweep.test.ts index c6f01433b1..a767e60148 100644 --- a/packages/ui-server/tests/attachment-sweep.test.ts +++ b/packages/ui-server/tests/attachment-sweep.test.ts @@ -147,8 +147,11 @@ test("concurrent uploads at the pool edge cannot multiply the cap: reservations duplex: "half", }); const first = start(0), second = start(1); - await Bun.sleep(50); - // Two 40-byte uploads are reserved and still streaming. A third cannot fit. + // Both uploads have reserved their declared 40 bytes and are still streaming. + const reserved = () => t.app.db.query("SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b FROM attachment_reservations").get() as { n: number; b: number }; + for (const deadline = Date.now() + 5_000; reserved().n < 2 && Date.now() < deadline;) await Bun.sleep(5); + expect(reserved(), "ATTACHMENT_STREAMING_UPLOADS_RESERVED").toEqual({ n: 2, b: 80 }); + // A third cannot fit. const third = await t.fetch("/api/drafts/draft-2/files", { method: "POST", body: "y".repeat(40), headers: { cookie, origin: "http://localhost", host: "localhost", "idempotency-key": "k2", "content-type": "text/plain", "content-length": "40", "x-file-name": "log-2.txt" } }); expect([third.status, await third.json()]).toEqual([507, expect.objectContaining({ error: "ATTACHMENT_CAPACITY", bound: "pool" })]); diff --git a/packages/ui-server/tests/compute-host.test.ts b/packages/ui-server/tests/compute-host.test.ts index d318b81fb7..7fb317810b 100644 --- a/packages/ui-server/tests/compute-host.test.ts +++ b/packages/ui-server/tests/compute-host.test.ts @@ -382,18 +382,21 @@ describe("cancellation racing admission (R7)", () => { test("cancelling a turn waits for its in-flight compute calls and cancels what they started", async () => { let f!: Fixture; - let release!: () => void; + let release!: () => void, reserving = false; const held = new Promise(resolve => { release = resolve; }); f = fixture({ host: { budgets: { compute: { - async reserve(jobId: string, turnId: string, sessionId: string | null, usd: number | null) { await held; return f.budgets.compute.reserve(jobId, turnId, sessionId, usd); }, + async reserve(jobId: string, turnId: string, sessionId: string | null, usd: number | null) { reserving = true; await held; return f.budgets.compute.reserve(jobId, turnId, sessionId, usd); }, settle: (jobId: string, usd: number | null) => f.budgets.compute.settle(jobId, usd), } } as never } }); await f.begin("t-1"); const running = f.host.forTurn(f.turn("t-1"))(run({ argv: ["sleep", "600"] })); - await until(() => f.cards.length === 1, "the card"); + await until(() => f.cards.length === 1 && reserving, "the held reservation"); let cancelled = false; const cancelling = f.host.cancelTurn("t-1", "the turn was cancelled").then(() => { cancelled = true; }); - await Bun.sleep(10); + // The call is held inside its reservation, before its job row exists, so + // cancelTurn's first sweep finds nothing and only the in-flight call can + // keep it waiting. That sweep is in memory: one macrotask runs it out. + await new Promise(resolve => setTimeout(resolve, 0)); expect(cancelled, "CANCEL_WAITS_FOR_INFLIGHT_CALL").toBe(false); release(); await Promise.all([running, cancelling]); @@ -486,7 +489,9 @@ describe("ledger settlement", () => { }); test("a later visit to a settled job rewrites neither its row nor its run", async () => { - const f = fixture(); + // The host's own clock, so a rewrite would carry a later stamp. + let hostNow = Date.UTC(2026, 6, 12, 9); + const f = fixture({ host: { clock: () => hostNow } as never }); await f.begin("t-1"); const compute = f.host.forTurn(f.turn("t-1")); const started = ok(await compute(run())); @@ -494,7 +499,7 @@ describe("ledger settlement", () => { const snapshot = () => ({ row: hostRow(f, started.job.id), endedAt: f.store.getSpan(`compute:${started.job.id}`)!.endedAt, events: f.store.snapshotRun(`compute:${started.job.id}`)!.events.length }); const before = snapshot(); - await Bun.sleep(5); + hostNow += 60_000; ok(await compute(job("brain_compute_status", started.job.id))); ok(await compute(job("brain_compute_collect", started.job.id))); expect(snapshot(), "SETTLED_ROW_NOT_REWRITTEN").toEqual(before); diff --git a/packages/ui-server/tests/fixtures/apify-ledger-race-child.ts b/packages/ui-server/tests/fixtures/apify-ledger-race-child.ts index 755a2c99d8..47db349ac0 100644 --- a/packages/ui-server/tests/fixtures/apify-ledger-race-child.ts +++ b/packages/ui-server/tests/fixtures/apify-ledger-race-child.ts @@ -2,13 +2,16 @@ * One process of the two-process ledger race (#3161): waits for the shared * start signal, then tries to reserve $2 against a $3 account day. Prints * `admitted` or `refused:`. Keyless and offline: it only opens the - * ledger file the parent names. + * ledger file the parent names, and marks itself ready beside the start + * signal once that ledger is open. */ -import { existsSync } from "node:fs"; +import { existsSync, writeFileSync } from "node:fs"; import { ApifyLedgerRefusal, openApifyLedger } from "@schlessera/brain-common/internal/apify"; const [path, go, index] = process.argv.slice(2) as [string, string, string]; const ledger = openApifyLedger(path); +// At the start line: the parent opens it once every child has said so. +writeFileSync(`${go}.${index}.ready`, ""); while (!existsSync(go)) await Bun.sleep(5); const now = Date.parse("2026-07-12T09:00:00.000Z"); try { diff --git a/packages/ui-server/tests/fixtures/extract-misbehaving-worker.ts b/packages/ui-server/tests/fixtures/extract-misbehaving-worker.ts index 9adc6b6879..7dc0fffde6 100644 --- a/packages/ui-server/tests/fixtures/extract-misbehaving-worker.ts +++ b/packages/ui-server/tests/fixtures/extract-misbehaving-worker.ts @@ -7,6 +7,9 @@ const request = JSON.parse(process.argv[2] ?? "{}") as { startPage: number; offset: number }; for await (const _ of Bun.stdin.stream()) { /* drain the original */ } if (request.startPage === 1) { + // Fixture hold: a child that stays alive for `offset` ms. The bound cases + // measure the extractor against it (its wall-clock kill, its queueing and + // its cancellation), so the hold is real time by design. await Bun.sleep(request.offset); process.stdout.write(`${JSON.stringify({ outcome: "malformed" })}\n`); } else if (request.startPage === 2) { diff --git a/packages/ui-server/tests/helpers/contextual-status.ts b/packages/ui-server/tests/helpers/contextual-status.ts index 10b2771989..f79d5385c8 100644 --- a/packages/ui-server/tests/helpers/contextual-status.ts +++ b/packages/ui-server/tests/helpers/contextual-status.ts @@ -109,9 +109,16 @@ export async function contextualStatus(engine: "gemini" | "gpt", mode: "complete : frame.delegation_id && frame.content?.startsWith('{"hostTaskStatus"') ? [{ id: frame.delegation_id, state: JSON.parse(frame.content).hostTaskStatus, content: frame.content, frame }] : []); await recognize("Find the mast decision.", 0); request("mast-native"); await until(() => !!finishAdmission); - // Negative window: persistence is deliberately unresolved, so no causal - // completion event exists to await. This tests absence of premature acceptance. - await Bun.sleep(10); + // Persistence is held, so durable admission never completes here. One + // macrotask runs every host continuation that does not wait for it. A status + // any of them sent travels the same ordered provider socket as the audio + // frame the host forwards after it: once that frame has arrived, every + // earlier status would have too. + await new Promise(resolve => setTimeout(resolve, 0)); + const audioFrames = () => f.sent.filter(frame => frame.realtimeInput?.audio || frame.type === "session.input_audio.append").length; + const forwarded = audioFrames(); + send({ type: "conversation_audio", conversationId, epoch, utteranceId: "capture", sequence: 1, rate: engine === "gemini" ? 16000 : 24000, pcm: "AAA=" }); + await until(() => audioFrames() > forwarded); expect(statuses(), "NO_PROVIDER_ACCEPTANCE_BEFORE_DURABLE_ADMISSION").toEqual([]); expect(turns).toHaveLength(0); if (mode === "replace") { @@ -134,6 +141,10 @@ export async function contextualStatus(engine: "gemini" | "gpt", mode: "complete if (mode === "storage") await until(() => frames.some(frame => frame.nativeHandle === "mast-native" && frame.state === "refused")); else if (mode === "status-error") await until(() => frames.some(frame => frame.type === "conversation_closed")); else await host.catalog.settled!(); + // Negative window, kept real time: a wrong acceptance would cross the real + // provider socket after this outcome. Status-error and GPT withdrawal have + // closed that socket, so no later frame can follow it and mark its arrival. + // 10 ms gives a frame already sent on loopback its chance to arrive. await Bun.sleep(10); expect(statuses(), "FAILED_OR_STALE_ADMISSION_NEVER_CLAIMS_ACCEPTED").toEqual([]); expect(turns).toHaveLength(0); diff --git a/packages/ui-server/tests/journal-idle-maintenance.test.ts b/packages/ui-server/tests/journal-idle-maintenance.test.ts index f12966af7c..45ca31595b 100644 --- a/packages/ui-server/tests/journal-idle-maintenance.test.ts +++ b/packages/ui-server/tests/journal-idle-maintenance.test.ts @@ -108,6 +108,8 @@ test("closing abandons an idle pass instead of waiting for its native work", asy }); }); void f.journal.maintain(); await blocked; + // Failure maximum: a correct close settles first; the 5 s branch is only + // reached if close waits for the blocked native work. const closed = await Promise.race([f.journal.close().then(() => "closed"), Bun.sleep(5_000).then(() => "waiting")]); expect(closed, "CLOSE_ABANDONS_THE_IDLE_PASS").toBe("closed"); } finally { f.blockCheckpoints(undefined); unblock(); await f.close().catch(() => {}); } diff --git a/packages/ui-server/tests/policy-observation-pause.test.ts b/packages/ui-server/tests/policy-observation-pause.test.ts index 2c82a6844c..9d65c132b6 100644 --- a/packages/ui-server/tests/policy-observation-pause.test.ts +++ b/packages/ui-server/tests/policy-observation-pause.test.ts @@ -135,6 +135,10 @@ test("repeated pauses share one finite deadline, and expiry publishes nothing", const firstPause = Date.now(); // A second changed path: the fresh attempt's own observation reaches the granted cap, which is Stop only. writeFileSync(join(p.f.brain, "voyage-chart.md"), "Odysseus charts Scheria.\n"); + // Real time, the stimulus: the shared deadline is taken from Date.now() when + // the first pause starts waiting, and no clock in this file reaches it. This + // spends half of it, so a second pause that restarted the bound would wait + // past waitMs + 400 and fail POLICY_PAUSES_SHARE_ONE_DEADLINE. await Bun.sleep(600); expect((await p.f.scope.decide(p.f.message("continue"), true)).state).toBe("accepted"); const result = await pending; diff --git a/packages/ui-server/tests/private-index.test.ts b/packages/ui-server/tests/private-index.test.ts index 1095bc77cc..154e6d2c31 100644 --- a/packages/ui-server/tests/private-index.test.ts +++ b/packages/ui-server/tests/private-index.test.ts @@ -169,22 +169,32 @@ test("the first type-selector turn after server start waits for a writer started // Admitted with the server, before the turn: its plan cannot hold me/. const boot = await gate.acquire("shared", "brain CLI version"); expect(boot.folderPaths, "SERVER_START_WRITER_PLANS_NO_TYPE_FOLDER").toEqual([]); - // The boot writer finishes a little after the turn reaches it. A turn that - // refuses, or checks without waiting, never lets it finish first. + // The boot writer finishes after the turn's wait has seen it still lacking + // the folder. Gate procedures run in submission order, so once a peer check + // submitted after the wait's first check reports the boot writer, that first + // check has reported it too. The turn's admission steps are recorded: the + // peer-plan step must end, and every later step start, after the release. A + // turn that refuses, checks without waiting or stops awaiting the wait + // proceeds before it. let releasedAt: number | undefined; + const steps: { name: string; at: number; ended?: number }[] = []; + const timing = (name: string) => { const step: { name: string; at: number; ended?: number } = { name, at: performance.now() }; steps.push(step); return () => { step.ended = performance.now(); }; }; const hook = spyOn(gate, "acquire").mockImplementation(async (...args) => { const hold = await acquire(...args), wait = hold.waitForPeerFolderPlans?.bind(hold); return wait ? Object.assign(hold, { waitForPeerFolderPlans: (...values: Parameters) => { - setTimeout(() => { releasedAt = performance.now(); boot.release(); }, 300); - return wait(...values); + const waiting = wait(...values); + void hold.assertPeerFolderPlans!(values[0]).then(() => {}, () => {}).then(() => { releasedAt = performance.now(); boot.release(); }); + return waiting; } }) : hold; }); let hold: Awaited> | undefined, refusal: unknown; try { - try { hold = await f.turns.begin("first-after-start", new AbortController().signal); } catch (error) { refusal = error; } - const admittedAt = performance.now(); + try { hold = await f.turns.begin("first-after-start", new AbortController().signal, undefined, undefined, undefined, timing); } catch (error) { refusal = error; } expect(refusal, "FIRST_PROVIDER_POLICY_TURN_AFTER_START_ADMITTED").toBeUndefined(); - expect(releasedAt !== undefined && admittedAt >= releasedAt, "ADMITTED_ONLY_ONCE_THE_SERVER_START_WRITER_FINISHED").toBe(true); + const peer = steps.findIndex(step => step.name === "peer_folder_plans"); + expect(peer >= 0 && releasedAt !== undefined, "PEER_PLAN_STEP_RAN_AND_RELEASED").toBe(true); + expect(steps[peer]!.ended! >= releasedAt! && steps.slice(peer + 1).every(step => step.at >= releasedAt!), + "ADMITTED_ONLY_ONCE_THE_SERVER_START_WRITER_FINISHED").toBe(true); expect(hold!.sandbox.profile, hold!.sandbox.fallbackReason).toBe("governed"); expect(hold!.sandbox.retainedFolders, "TYPE_FOLDER_RETAINED").toEqual([".brain-cache", ".brain-index", "me"]); } finally { hook.mockRestore(); boot.release(); await hold?.end(); } diff --git a/packages/ui-server/tests/relay-recording-settlement.test.ts b/packages/ui-server/tests/relay-recording-settlement.test.ts index fe0b070161..aafffde014 100644 --- a/packages/ui-server/tests/relay-recording-settlement.test.ts +++ b/packages/ui-server/tests/relay-recording-settlement.test.ts @@ -68,9 +68,17 @@ for (const kind of ["inference", "provider"] as const) { return writes.record(event); } }); const path = kind === "inference" ? "/v1/messages" : "/v1beta/models/gemini-2.5-flash:generateContent"; + // The relay's admission of its own operation, observed: when it starts, and when it answers. + const admission = { entered: Promise.withResolvers(), answered: false }; + const observed = }>(operation: Operation): Operation => ({ ...operation, admit() { + admission.entered.resolve(); + return operation.admit().finally(() => { admission.answered = true; }); + } }); + const egress = { ...proxy, inference: (...args: Parameters) => observed(proxy.inference(...args)), + relayed: (...args: Parameters) => observed(proxy.relayed(...args)) }; const relay = kind === "inference" - ? startInferenceRelay({ upstream: origin.url.origin, routes: [path], credentials: { "x-api-key": "odysseus-host-key" }, egress: proxy }) - : startProviderRelay({ egress: proxy, credential: name => name === "GEMINI_API_KEY" ? "odysseus-host-key" : undefined, + ? startInferenceRelay({ upstream: origin.url.origin, routes: [path], credentials: { "x-api-key": "odysseus-host-key" }, egress }) + : startProviderRelay({ egress, credential: name => name === "GEMINI_API_KEY" ? "odysseus-host-key" : undefined, origins: new Map([["GEMINI_API_KEY", [origin.url.origin]]]) }); let dispatch: Promise | undefined; try { @@ -84,7 +92,12 @@ for (const kind of ["inference", "provider"] as const) { ...(kind === "provider" ? { "x-brain-provider": "gemini", "x-brain-provider-key": "GEMINI_API_KEY", "x-brain-provider-origin": origin.url.origin } : {}) }; let completed = false; dispatch = exchange(relay.socketPath, path, "POST", headers, body).then(status => { completed = true; return status; }); - await Bun.sleep(30); + // The relay has received the request and asked to admit it. Its own + // recording is held in the worker; everything else admission awaits is + // in memory, so one macrotask runs whatever does not wait for the hold. + await admission.entered.promise; + await new Promise(resolve => setTimeout(resolve, 0)); + expect(admission.answered, "RELAY_WAITS_FOR_OWN_EGRESS_RECORDING").toBe(false); expect(completed, "RELAY_WAITS_FOR_OWN_EGRESS_RECORDING").toBe(false); expect(upstream).toBe(0); if (mode === "shared loss") pending = writes.safetyFail("other-turn"); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 59e65df8a9..3529f78946 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -262,10 +262,21 @@ test("Claude delivery hooks await real SQLite commits before tool contact and re const hold=f.writer.channel(probe,{table:"odysseus_log"});await hold.ready; const slow=hold.call("slow","Ithaca",200);let contacted=false; const pre=wiring.hooks!.PreToolUse!.find(group=>!group.matcher)!.hooks[0]!; - const admitting=pre({hook_event_name:"PreToolUse",tool_use_id:"actual-hook",tool_name:"WebFetch",tool_input:{url:origin.url.href}} as never,undefined,{signal:new AbortController().signal}).then(()=>{contacted=true;return fetch(origin.url);}); - await Bun.sleep(20); - expect(contacted,"SAFETY_BACKEND_CONTACT_WAITS_FOR_DURABLE_ADMISSION").toBe(false); + const admitting=pre({hook_event_name:"PreToolUse",tool_use_id:"actual-hook",tool_name:"WebFetch",tool_input:{url:origin.url.href}} as never,undefined,{signal:new AbortController().signal}).then(()=>{contacted=true; + // Contact itself checks the order: the admission must have committed first. + const pending=f.writes.safety(null,"ithaca").pendingCount; + if(pending)throw new Error(`SAFETY_BACKEND_CONTACT_WAITS_FOR_DURABLE_ADMISSION: contacted with ${pending} pending`); + return fetch(origin.url);}); + // The hook's admission write is submitted while the 200 ms hold still runs; + // one macrotask then runs every continuation that does not wait for it. + for(const deadline=Date.now()+5_000;f.writes.safety(null,"ithaca").pendingCount<1&&Date.now()setTimeout(resolve,0)); expect(f.writes.safety(null,"ithaca").pendingCount).toBe(1); + expect(contacted,"SAFETY_BACKEND_CONTACT_WAITS_FOR_DURABLE_ADMISSION").toBe(false); + // The worker answers in submission order on one port: when the hold answers, + // the admission queued behind it has not, so contact must still wait. + await slow; + expect(contacted,"SAFETY_BACKEND_CONTACT_WAITS_FOR_DURABLE_ADMISSION").toBe(false); const response=await admitting;await slow; const post=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!.hooks[0]!; await post({hook_event_name:"PostToolUse",tool_use_id:"actual-hook",tool_name:"WebFetch",tool_response:await response.text()} as never,undefined,{signal:new AbortController().signal}); diff --git a/packages/ui-server/tests/session-run-stages.test.ts b/packages/ui-server/tests/session-run-stages.test.ts index 6d726858bc..fb0d63b135 100644 --- a/packages/ui-server/tests/session-run-stages.test.ts +++ b/packages/ui-server/tests/session-run-stages.test.ts @@ -396,7 +396,9 @@ describe("host admission", () => { const controller = new AbortController(); const handle = armTurnTimeout(host, slot.turn, controller); expect(slot.turn.timeoutHandle).toBe(handle); - await new Promise(resolve => setTimeout(resolve, 30)); + // The armed 5 ms timer aborts the turn, then drains it in the same + // callback, before this continuation runs. + await new Promise(resolve => controller.signal.addEventListener("abort", resolve, { once: true })); expect(controller.signal.aborted).toBe(true); expect(drained).toEqual(["Turn timed out"]); }); diff --git a/packages/ui-server/tests/tainted-destination-ask.test.ts b/packages/ui-server/tests/tainted-destination-ask.test.ts index 9db9c20afe..a6208af173 100644 --- a/packages/ui-server/tests/tainted-destination-ask.test.ts +++ b/packages/ui-server/tests/tainted-destination-ask.test.ts @@ -147,7 +147,12 @@ test("concurrent connections to the same new host share one card", async () => { const proxy = await turn(db, bridge); try { const both = [get(proxy.socketPath, island.url.href), get(proxy.socketPath, `${island.url.href}again`)]; - await raised(asks, Promise.all(both)); await Bun.sleep(50); + await raised(asks, Promise.all(both)); + // Negative window, kept real time: nothing outside the proxy marks the + // second connection reaching the shared card, and the bridge double sees + // only cards, the action under test. 50 ms lets its loopback request + // reach admission and raise a second card if the host does not share it. + await Bun.sleep(50); expect(asks.requests, "TAINTED_ASK_ONE_CARD_PER_HOST").toHaveLength(1); asks.answer({ behavior: "allow" }); expect((await Promise.all(both)).map(result => result.status)).toEqual([200, 200]); @@ -215,6 +220,9 @@ test("cancelling the turn while the card is pending refuses the connection; a la controller.abort(); asks.answer({ behavior: "allow" }); expect((await response).status, "TAINTED_ASK_CANCEL_REFUSES").not.toBe(200); + // Negative window, kept real time: a contact the late allow started would + // reach the island over loopback after the refusal, and no frame on that + // path can mark its absence. 50 ms gives such a connection its chance. await Bun.sleep(50); expect(calls, "TAINTED_ASK_CANCEL_NO_CONTACT").toBe(0); expect(events(db, "egress_connection"), "TAINTED_ASK_CANCEL_NOT_ADMITTED").toMatchObject([{ outcome: "cancelled", bytes: 0 }]); diff --git a/packages/ui-server/tests/turn-coordinator.test.ts b/packages/ui-server/tests/turn-coordinator.test.ts index 0c27ea0dc3..cf5d142d23 100644 --- a/packages/ui-server/tests/turn-coordinator.test.ts +++ b/packages/ui-server/tests/turn-coordinator.test.ts @@ -11,7 +11,11 @@ import type { RunningTurn } from "../src/ws/turns"; import { closeDb, resetForTests, setBackendForTests, testHost } from "./helpers/test-host"; import { testPrincipal } from "./helpers/principal"; -/** How a request settled within a second: its rejection message, "resolved", or "unsettled". */ +/** + * How a request settled within a second: its rejection message, "resolved", or + * "unsettled". A failure maximum: a request that settles wins the race at once, + * and the 1 s branch is only reached by one that hangs. + */ function settlement(request: Promise): Promise { return Promise.race([ request.then(() => "resolved", (error: unknown) => (error instanceof Error ? error.message : String(error))), diff --git a/packages/ui-server/tests/ws-turn-budgets.test.ts b/packages/ui-server/tests/ws-turn-budgets.test.ts index e1597aa9a3..5e81183f11 100644 --- a/packages/ui-server/tests/ws-turn-budgets.test.ts +++ b/packages/ui-server/tests/ws-turn-budgets.test.ts @@ -27,9 +27,13 @@ for (const adapter of ["claude", "pi"] as const) const priced = mode !== "token", backstop = mode === "sdk", unavailable = mode === "unavailable", late = mode === "late"; // The block follows the report's commit on the write worker (#2850), queued // behind the turn's earlier writes, so the fake waits for the host's abort - // instead of a fixed 200 ms a loaded runner can exceed. Only "late" returns - // early on purpose: before its commit lands, 400 ms after the response. - const abortWindowMs = late ? 200 : 2500; + // instead of a fixed 200 ms a loaded runner can exceed; 2.5 s is only a + // failure maximum. Only "late" returns early on purpose: as soon as its + // reports are submitted, before the wrapper below delivers their observed + // result, 400 ms later. + const abortWindowMs = 2500; + const reports: unknown[] = []; + let reportsAtReturn = -1; let failAccounting: () => void = () => { }; const root = await mkdtemp(resolve(tmpdir(), "odysseus-budget-host-")), brain = resolve(root, "brain"); await createFixtureBrain(resolve(import.meta.dir, "../../.."), brain); @@ -61,7 +65,9 @@ for (const adapter of ["claude", "pi"] as const) for (const frame of stream.adapt({ type: "stream_event", event } as SDKMessage)) req.bridge.emit(frame); } - if (!req.signal.aborted) + if (late) + reportsAtReturn = reports.length; + else if (!req.signal.aborted) await Promise.race([new Promise(done => req.signal.addEventListener("abort", () => done(), { once: true })), Bun.sleep(abortWindowMs)]); } else { @@ -83,7 +89,7 @@ for (const adapter of ["claude", "pi"] as const) budgets: (() => { const budgets = createTurnBudgets(app.db, { resolve: () => ({ input: 1, output: 1, cacheRead: 1, cacheWrite: 1, estimate: false, source: "snapshot" }) }); // The blocking report's commit lands after the backend has returned (#2850). - return late ? { ...budgets, observe: (...args: Parameters) => { const committed = budgets.observe(...args); return committed && Bun.sleep(400).then(() => committed); } } : budgets; + return late ? { ...budgets, observe: (...args: Parameters) => { reports.push(args[1]); const committed = budgets.observe(...args); return committed && Bun.sleep(400).then(() => committed); } } : budgets; })() }) : app.wsHost; failAccounting = () => app.db.exec("DROP TABLE turn_budget_days"); try { @@ -106,6 +112,8 @@ for (const adapter of ["claude", "pi"] as const) expect(receivedContext, "NO_ROUTINE_BUDGET_TAIL_AT_ADMISSION").toBeUndefined(); expect(called, "BUDGET_ACTUAL_ADAPTER_LAUNCHED").toBe(1); expect(aborted, "BUDGET_HOST_ABORTS_ACTUAL_ADAPTER").toBe(!late); + if (late) + expect([reportsAtReturn > 0, reportsAtReturn], "LATE_RESPONSE_RETURNS_WITH_EVERY_REPORT_SUBMITTED").toEqual([true, reports.length]); expect(maxBudget).toBe(10); const failure = frames().findLast(frame => frame.type === "error")!; expect(failure).toMatchObject(unavailable ? { code: "BUDGET_UNAVAILABLE", failure: { errorClass: "budget_unavailable" } } : { code: "BUDGET_EXCEEDED", failure: { errorClass: "budget_exceeded", budgetScope: "turn" } }); diff --git a/tests/host-admission.test.ts b/tests/host-admission.test.ts index d70bd35d12..594a1a43cf 100644 --- a/tests/host-admission.test.ts +++ b/tests/host-admission.test.ts @@ -1,7 +1,7 @@ // Host-wide admission for heavy local commands (#2943): separate worktrees on // one machine share a limited number of slots instead of timing out together. import { afterEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { admissionLimit, admissionOrder, PREEMPTED_EXIT, readHistory, testLedgerFor, type AdmissionEntry } from "../scripts/host-admission.mjs"; @@ -68,12 +68,19 @@ describe("host admission ledger", () => { test("with the limit at 1, heavy commands from two worktrees run one after the other and neither times out", async () => { const { dir, ledger, timings } = fixture(); const log = join(dir, "log"); - // Each command fails if another is running, and has its own deadline. + // Each command fails if another is running. It holds its slot until the + // test writes its release file (at most 10 s), so the second command is + // queued behind the first by construction rather than by a race against a + // fixed sleep, which a loaded host can lose. const heavy = (name: string) => `if ! mkdir ${dir}/running 2>/dev/null; then echo OVERLAP-${name} >> ${log}; exit 9; fi; ` + - `echo start-${name} >> ${log}; sleep 0.4; echo end-${name} >> ${log}; rmdir ${dir}/running`; + `echo start-${name} >> ${log}; i=0; while [ ! -e ${dir}/release-${name} ] && [ $i -lt 1000 ]; do sleep 0.01; i=$((i+1)); done; ` + + `echo end-${name} >> ${log}; rmdir ${dir}/running`; const first = admit(join(dir, "ithaca"), ledger, timings, heavy("ithaca")); await until(() => holding(ledger).length === 1, "the first holder"); const second = admit(join(dir, "ogygia"), ledger, timings, heavy("ogygia")); + await until(() => queued(ledger).length === 1, "the second command queued behind the first"); + writeFileSync(join(dir, "release-ithaca"), ""); + writeFileSync(join(dir, "release-ogygia"), ""); const deadline = Bun.sleep(8_000).then(() => "timed out"); expect(await Promise.race([Promise.all([first.child.exited, second.child.exited]), deadline])).toEqual([0, 0]); expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(["start-ithaca", "end-ithaca", "start-ogygia", "end-ogygia"]); @@ -114,7 +121,12 @@ describe("host admission ledger", () => { await holder.child.exited; expect(alive(orphan), "the detached command survives its killed wrapper").toBe(true); const next = admit(join(dir, "ogygia"), ledger, timings, "echo PENELOPE_ADMITTED"); - expect(await Promise.race([next.child.exited, Bun.sleep(8_000).then(() => "blocked")])).toBe(0); + // A failure maximum: a slot that is never reclaimed blocks this admission. + // On success the exit settles first and the deadline is cleared. + let deadline: ReturnType | undefined; + const blocked = new Promise((resolve) => { deadline = setTimeout(() => resolve("blocked"), 8_000); }); + try { expect(await Promise.race([next.child.exited, blocked])).toBe(0); } + finally { clearTimeout(deadline); } expect(await next.output).toContain("PENELOPE_ADMITTED"); expect(alive(orphan), "reclaiming the slot stops the orphaned group").toBe(false); expect(readHistory(ledger).map(event => event.kind)).toContain("reclaimed");