diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 58bc9f8c17..d19d37c8e7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -288,9 +288,13 @@ available, with the pinned image and diagnostics unchanged. Browser shards use a committed per-project/file timing table, not live CI artifacts or a fixed allowlist. Unknown specs get a positive one-second weight; -invalid tables fail visibly. Refresh explicitly from two successful browser jobs: -`bun scripts/refresh-browser-costs.ts `. Review the source -head/checkout/tree, job IDs and seconds/median metadata alongside the table. +invalid tables fail visibly. Refresh explicitly from one successful CI run +attempt in which every shard of the domain, as configured in `PROOF_SHARDS` +(`scripts/proof-shards.ts`), ran fresh and succeeded: +`bun scripts/refresh-browser-costs.ts [browser|layout]` +(browser by default). Cancelled, partial or retained-only proof supplies no +measurements. Review the source head/checkout/tree, job IDs and seconds/median +metadata alongside the table. Unsharded discovery is unchanged and existing browser file concurrency is kept. `bun run test:browser` runs every configured browser project in the pinned diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index a180a053df..7692517e03 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -95,6 +95,47 @@ Existing issues #1242 (PDF effect readiness), #1685 (hygiene layout readiness), #1837 (repeated build attribution), and the recording/matrix children retain their ownership rather than being duplicated here. +### Re-census of later files + +The inventory above is a snapshot. Waits added after it are held to the same +rule ([#3332](https://github.com/schlessera/brain-kit/issues/3332)). The +[re-census](https://github.com/schlessera/brain-kit/tree/a13f2247adcc3946d44c023553ff662e926143ea/scripts/measurements/wait-census-3332-2026-11-02) +runs the same expression at `3984040f199cbadbee6e4ce3f1beff816b68dc36`. It +classifies every match in files that do not match at the inventory source +(604 lines in 204 files) as justified, replaceable or not a wait. The +classification is rule-based and does not count executions. A slice that +replaces waits re-reads each enclosing test first, and its pull request records +any reclassification and its mutation receipts. + +| Source / assertion | Attributed role and retained proof | Completion control / native boundary | +| --- | --- | --- | +| `private-index-cache.test.ts`, idle expiry and active-base skip | Registered idle timers, armed and delivered while a turn holds the base; expiry still applies once the turn finishes | `privateIndexClock` owns only the cache's timers and `Date.now`. Checkpoints, files and the held delta stay native. | +| Same file, advance/close ordering | The advance holds the base's queue before a turn arrives; close stops a delta or run that has actually started | The bench's `entered`/`running` signals replace 50–100 ms sleeps. Dropping either await reorders the outcome. | +| `reference-source.test.ts` and `reference-tools.test.ts`, admission, eviction and exposure ordering | Each step starts after the scripted fetch, admission or held pool call it depends on; a cancelled fetch's reservation is released only after its teardown | Conditions on the scripted transport and pool replace 5–20 ms sleeps. A held teardown barrier replaces the 30 ms `settleDelayMs` latency. The collaborators are in memory, so one macrotask turn runs all work up to the held barrier. | +| `application-index-timing.test.ts`, deferred index update | Twenty writes return before a slow index update; one targeted update covers them | The update is held until the writes are measured, instead of sleeping 1500 ms. On a route where a write waits for it, each update still takes 1500 ms and the median assertion fails. | +| `chat-lifecycle.test.ts` and `writer-gate-offloop.test.ts`, work queued behind a held writer | The retirement, or the host downgrade, is posted to the real write worker before the racing step | A `Worker.prototype.postMessage` observer replaces 20–50 ms sleeps and fixed timers; the descriptor is restored after each case. | +| `write-worker.test.ts`, app writes against a running procedure | The worker is inside the held procedure before the app writes | The probe sets an `entered` flag that the test awaits with `Atomics.waitAsync`, instead of sleeping 20–50 ms. | +| `native-brain-leases.test.ts`, `storage-offloop.test.ts` and `turn-egress.test.ts` | A lost reply after a newer release started; failures settled before close; a pending taint | The newer release's arrival, one macrotask after the synchronous tick, and a bounded taint poll replace fixed 20–100 ms waits. | +| `worker-steps-event-loop.test.ts`, a supervisor lost during a status request | The request is outstanding when the supervisor is lost; its late answer neither settles again nor releases the broker | The status step is held open, so the request is outstanding by construction. The test releases it and awaits its answer, instead of sleeping 150 ms and then 200 ms. | +| `maintenance-worker-kill-child.ts`, every thread confirms its stop | A non-leader thread that reports itself running delays the snapshot until it confirms | The thread reports running for exactly two polls, instead of until a 10 ms timer fires. The zero-delay heartbeat timers in the fork-ordering cases are the observation: they prove that stop confirmation yields. | +| Claude `worker-cleanup.test.ts` and `worker-stdio-release.test.ts`, reservation and settlement held | The reservation stays charged, and settlement waits, while only the held close or release remains | The state handle's real close is observed, or the release request is polled for. One macrotask then runs any continuation, instead of 20–50 ms windows. | +| ui-react `runtime-hook-phases.test.ts`, pending output | Exit and stderr completion are reported while stdout is held | A condition on those two records, then one macrotask, replaces a 20 ms window. | +| Root `build-concurrency.test.ts`, optional dependency before its consumer | A consumer never compiles before its optional dependency, despite a peer cycle | The dependency's compiler wrapper holds until a peer has finished and its slot has been refilled, instead of sleeping 500 ms. A consumer started in that slot compiles, and fails, while the dependency is held. | +| Root `helpers/planning-observer.ts`, first sampler reading | The sampler has a reading before the observed call blocks the main thread | The sampler posts `ready` after its first reading. The observer awaits that message, instead of one 250 ms interval, with the existing stop budget as its failure maximum. | +| 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. | +| ui-react `share-review/commands.ts`, review admission refused or retired | A failed copy, another account, a live owner in another tab, a racing tab or an expired record never admits review | The fixture counts its share-review lock requests and their settlements; a request that admits stays open. The command waits until a request made after a mark has settled, or a review is admitted, instead of 1.2–1.5 s. The racing loser waits for an attempt made after the winner admitted. Where the account's review rows and stashed originals are empty or sealed, nothing can be admitted, so no window is needed. Dismiss waits for the queue to empty, which follows the durable delete. | +| Same file, a lost response | The upload's response opens, then loses its body, so Chromium cannot retry it transparently | The socket closes from the write callback of the partial body, instead of 50 ms later. Closing before the flush lets Chromium retry, and the case fails. | +| ui-react `storage-guidance.layout.tsx`, late and refused responses | A response for the prior account or a replaced root never replaces current evidence; a refused route never opens Settings | The fixture counts the responses it answers and the bodies the consumer reads. The tests wait for the held response to be read, or for the route's refused read to be answered, instead of 50 ms. The route change is committed with `flushSync`, so its open decision has run. | +| ui-react `transcript-qualifiers.offline.tsx` and `conversation-controls.offline.tsx`, tooltip and reply holds | Escape keeps a qualifier hint hidden; the pointer can rest on a hint; short playback gaps keep Speaking | The qualifier's 300 ms show and 150 ms hide timers, and the strip's 300 ms reply hold, run on vitest's fake `setTimeout`. The tests advance them or run every pending timer, instead of 350 ms windows and real gaps. | +| 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. | + ## Continuity settling boundaries Networked continuity contexts start with native offline state, create their diff --git a/docs/process/theme-parity.md b/docs/process/theme-parity.md index d6595ff0ca..38940588b3 100644 --- a/docs/process/theme-parity.md +++ b/docs/process/theme-parity.md @@ -198,6 +198,42 @@ remain independently parameterized. This gives ten tests: six responsive scenario cases, three stale-history cases and one readiness control. Cleanup, negative observation windows and timing/deadline behavior are unchanged. +## Answer and journal coverage runtime cells + +Two later families run 320px dark and 1280px light instead of all four +width/theme cells (#3329). The theme selector sets only `color-scheme`, +which picks one half of each `light-dark()` colour token. No geometry, +focus, key or settlement path in these surfaces branches on it. The removed +copies are 320px light and 1280px dark. Every assertion in them is also made +by the retained cell at the same width. Each theme still paints once in the +runtime, and two central consumer stories own the paint in both Storybook +projects. + +(`Phone`, `packages/ui-kit/stories/conversation/AnswerTheme.stories.tsx:33-57`) +mounts the actual consumer `AskUserCard` with the built consumer stylesheet. +The kit's `Decisions/AskUserCard` stories cannot stand in for it, because their +meta disables the axe contrast rule for a known selected-option gap. The +journal stories now render configuration coverage as well +(`Phone`, `packages/ui-kit/stories/conversation/JournalTheme.stories.tsx:50-129`). + +| Assertions in the removed copies | Coverage that remains | +| --- | --- | +| `answer-delivery-runtime.test.ts`, `1887: Other has explicit current-text Submit`: `OTHER_LAYOUT_USES_REAL_THEME` | Both themes: 320px dark and 1280px light in the runtime. `Conversation/Answer theme/Phone`, `Desktop`: `painted` and the Other field's computed `color-scheme`, in both projects. | +| Same case: one explicit Submit, blank text disabled, blank Enter sends nothing, draft kept across switching, keyboard reach, ≥44px Submit, no document overflow | The retained cell at each width. The story repeats aria-disabled, the ≥44px Submit and the field/Submit bounds, then runs scoped WCAG A/AA, contrast included, on the field and Submit. | +| Same case: touch tap at 320px, Space at 1280px, single settlement of the original request, one `ask_user_response` frame | The retained cell at each width. The story's Submit dispatch is a fixture callback only. | +| `turn-journal-runtime.test.ts`, `journal configuration coverage keeps small changes first and preserves inspection`: badge description, visible, outside truncation, not clipped; row order and counts; index group; Turn facts; ≥44px disclosure and search; complete, height-bounded inventory; filtering, announcement debounce, refetch retention and error | The retained cell at each width. `Conversation/Journal theme/Phone`, `Desktop` add badge visibility and truncation, the ≥44px coverage disclosure and search, the inventory count and bounds, and scoped WCAG A/AA on the journal with coverage open, in both projects. | +| Same case: no external egress | The retained cell at each width. No replacement claimed. | + +Two mutations prove the story side. A light-only typed-text colour in +`AskOtherField` fails `Answer theme/Phone` and `Desktop` in `storybook-light` +on `color-contrast` (`input`). The same mutation leaves the kit +`Decisions/AskUserCard` stories green. A light-only inventory colour in +`JournalCoverage` fails `Journal theme/Phone` and `Desktop` in +`storybook-light` (`.font-mono > .break-all`). The journal stories without +coverage stay green. Both families keep the original scenario bodies, so the +settlement, frame, keyboard, touch, filter and refetch oracles above still run +at both widths. + ## Replay assertion ownership `connection-replay.layout.tsx` keeps native Chromium, built consumer CSS, @@ -246,6 +282,7 @@ node scripts/visual.mjs --project=storybook --project=storybook-light \ --filter=ComposerTheme.stories --filter=SessionTheme.stories \ --filter=AccountTheme.stories --filter=JournalTheme.stories \ --filter=ArtifactTheme.stories \ + --filter=AnswerTheme.stories \ --filter=InPrint.stories ``` diff --git a/packages/geo/tests/routing.test.ts b/packages/geo/tests/routing.test.ts index cf74b3ecfe..c8f2eea258 100644 --- a/packages/geo/tests/routing.test.ts +++ b/packages/geo/tests/routing.test.ts @@ -26,7 +26,12 @@ const footDemo="https://routing.openstreetmap.de/routed-foot/route/v1"; const footUrls=[dataset("foot").url,footDemo].map(endpoint=>endpoint+ "/driving/20.71,38.36;20.72,38.37?geometries=geojson&overview=full&steps=false&alternatives=false"); -/** Instance-local latency observation; retain the real fsync/rename writer. */ +/** + * Instance-local latency observation; retain the real fsync/rename writer. + * Kept real time (#3332): the second admission write runs after dispatch, while + * the transport's real deadline timer is armed, so the latency itself is the + * stimulus. A barrier would order the steps but spend none of that deadline. + */ function delayAdmissionWrites(geo: GeoClient, delayMs: number, admissionDir: string) { const instrumented = (geo as unknown as {transport: {writeAtomic(path: string, value: unknown): Promise}}).transport; const original = instrumented.writeAtomic; 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-backend-claude/tests/worker-cleanup.test.ts b/packages/ui-backend-claude/tests/worker-cleanup.test.ts index 7b70034a97..864e37efbc 100644 --- a/packages/ui-backend-claude/tests/worker-cleanup.test.ts +++ b/packages/ui-backend-claude/tests/worker-cleanup.test.ts @@ -24,7 +24,7 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai mkdirSync(brain); mkdirSync(saved); mkdirSync(home); writeFileSync(join(saved, "settings.json"), "{}"); const sandbox = prepareWorkerSandbox(brain, { home, profile: "governed", areas: [] }); const original = internal.launchAgentWorkerAsync; - let gate = Promise.withResolvers(), closing = Promise.withResolvers(); + let gate = Promise.withResolvers(), closing = Promise.withResolvers(), stateClosed = Promise.withResolvers(); const retries: Array<() => Promise> = []; // The real worker and handles; only the turn temp's awaited close is held at a gate. const launch = spyOn(internal, "launchAgentWorkerAsync").mockImplementation(async input => { @@ -33,6 +33,9 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai retries.push(close); turnTemp.close = () => { throw new Error("CLAUDE_SYNC_TURN_TEMP_CLOSE_ON_AN_ASYNC_LAUNCH"); }; turnTemp.closeAsync = async () => { closing.resolve(); await gate.promise; await close(); }; + // The state handle's real close runs beside the held one; its completion is observed, not waited out. + const state = worker.state!, closeState = state.closeAsync.bind(state); + state.closeAsync = async () => { await closeState(); stateClosed.resolve(); }; return worker; }); // Retries run when the test says so, not on a timer racing the worker's release wait. @@ -50,13 +53,16 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai const confirmed = createStateLedger(); const finished = turn(confirmed); await closing.promise; - await Bun.sleep(20); + // Everything the release awaits besides the held gate has completed, and one + // macrotask runs any continuation of it: only the gate now holds the release. + await stateClosed.promise; + await new Promise(resolve => setTimeout(resolve, 0)); expect(confirmed.live, "CLAUDE_RESERVATION_HELD_WHILE_CLOSE_PENDING").toBe(1); gate.resolve(); await finished; expect(confirmed.live, "CLAUDE_CONFIRMED_CLOSE_RELEASES_RESERVATION").toBe(0); - gate = Promise.withResolvers(); closing = Promise.withResolvers(); + gate = Promise.withResolvers(); closing = Promise.withResolvers(); stateClosed = Promise.withResolvers(); const refused = createStateLedger(); const refusing = turn(refused); await closing.promise; diff --git a/packages/ui-backend-claude/tests/worker-event-loop.test.ts b/packages/ui-backend-claude/tests/worker-event-loop.test.ts index dbfb3ec4b4..20e8f8cabb 100644 --- a/packages/ui-backend-claude/tests/worker-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/worker-event-loop.test.ts @@ -112,6 +112,11 @@ test.skipIf(!native)("a started worker's failed lifecycle stays handled until th signal: new AbortController().signal } as never); child.on("error", () => {}); child.stdout.resume(); child.stdin.end(); await new Promise(done => child.once("exit", done)); + // Kept real time: a negative observation. The facade's exit is emitted + // before the lifecycle settles; its rejection follows only once the state + // handle's broker close and the FIFO release finish on Bun's IO pool, and + // nothing outside the turn exposes that settlement. Awaiting it would + // attach the very handler whose absence this test checks. await Bun.sleep(50); expect(unhandled, "WORKER_LIFECYCLE_FAILURE_HANDLED_BEFORE_FINISH").toEqual([]); await expect(spawner.finish()).rejects.toThrow("scope freezer refused"); @@ -132,7 +137,10 @@ test.skipIf(!native)("a turn abort leaves a running worker to the SDK's own clos const exit = new Promise(done => child.once("exit", (code: number | null) => { exited = true; done(code); })); await ready; turn.abort(); - await Bun.sleep(300); + // Abort listeners run synchronously inside abort(); one macrotask runs any + // continuation they scheduled. A kill sent by then stops the worker before + // it can read "grace", so the exit code and output below are the proof. + await new Promise(resolve => setImmediate(resolve)); expect(exited, "TURN_ABORT_LEAVES_WORKER_TO_SDK_CLOSE").toBe(false); child.stdin.end("grace\n"); expect(await exit).toBe(0); diff --git a/packages/ui-backend-claude/tests/worker-stdio-release.test.ts b/packages/ui-backend-claude/tests/worker-stdio-release.test.ts index 531c4a4963..29a56c5993 100644 --- a/packages/ui-backend-claude/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-claude/tests/worker-stdio-release.test.ts @@ -59,7 +59,7 @@ test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worke test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worker reports its exit before its stdio release, and settles after it", async () => { const { fifos, spawner, spawn } = fixture(); const release = Promise.withResolvers(); - let releasing = false; + let releasing = false as boolean; const workers = spawner(worker => { const real = worker.released.bind(worker); worker.released = () => { releasing = true; return release.promise.then(real); }; @@ -76,7 +76,11 @@ test.skipIf(process.platform !== "linux" || !Bun.which("bwrap"))("a Claude worke child.stdout.on("data", chunk => { output += String(chunk); }); await once(child.stdout, "end"); expect(output, "POST_EXIT_DRAIN_COMPLETES").toBe("Ithaca"); - await Bun.sleep(50); + // The release has been requested; one macrotask then runs any settlement + // that does not wait for it, since the held release is all that remains. + // The test's own timeout bounds this condition. + while (!releasing) await Bun.sleep(1); + await new Promise(resolve => setTimeout(resolve, 0)); expect({ releasing, settled }, "SETTLEMENT_WAITS_FOR_RELEASE").toEqual({ releasing: true, settled: false }); release.resolve(); await finished; diff --git a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts index 3f208c6c04..3cbfc79118 100644 --- a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts +++ b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts @@ -212,6 +212,10 @@ for (const failure of ["startup failure", "initialization timeout"] as const) { if (failure === "initialization timeout") timeout(); await reached.promise; controller.abort(); + // Kept real time: a negative observation. The release is held in memory, + // but a startup failure that stopped awaiting it would still close the + // worker's turn temp on the native broker before settling. That close has + // no in-process signal, so only a window can show the turn did not settle. await Bun.sleep(50); expect(settled, "PI_START_FAILURE_AWAITS_RELEASE_DESPITE_CANCELLATION").toBe(false); released.resolve(); diff --git a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts index 636654d6e7..3fb9e5b8e4 100644 --- a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts @@ -64,6 +64,11 @@ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "non if (pool || hold === "none" || !String(chunk).includes(`"type":"${hold}"`)) return; const held = pool = holdWorkPool(fifos.dir); const ended = (stream: NodeJS.ReadableStream) => new Promise(done => stream.once("end", done)); + // Kept real time: the delay is the stimulus. It makes Bun's own close of + // its descriptor duplicates late, so a turn that settles at exit or at + // end of output settles with them still open. Freeing the pool when the + // turn asks for release would let a turn that asks without awaiting the + // answer race the pool's close. void Promise.all([ended(launched.stdout), ended(launched.stderr)]).then(() => Bun.sleep(250)).then(held.release); })) as typeof launched.stdin.write; return launched; @@ -110,7 +115,10 @@ test.skipIf(!native)("a pi turn waits for its worker's stdio release, however lo const turn = piTurn(ANSWERING, "none", { promise: release.promise, called: calling.resolve }).then(outcome => { settled = true; return outcome; }); cleanup.push(() => release.resolve()); expect(await Promise.race([calling.promise.then(() => true), Bun.sleep(10_000).then(() => false)]), "PI_TURN_REACHES_RELEASE").toBe(true); - await Bun.sleep(100); + // The release is the turn's last teardown step and is withheld in memory. + // Everything after it is in-process work, so one macrotask after the call is + // when a turn that did not await the release would already have settled. + await new Promise(resolve => setImmediate(resolve)); expect(settled, "PI_TURN_PENDING_WHILE_RELEASE_WITHHELD").toBe(false); release.resolve(); const { open, refused, result } = await turn; diff --git a/packages/ui-kit/stories/conversation/AnswerTheme.stories.tsx b/packages/ui-kit/stories/conversation/AnswerTheme.stories.tsx new file mode 100644 index 0000000000..ca9c91110d --- /dev/null +++ b/packages/ui-kit/stories/conversation/AnswerTheme.stories.tsx @@ -0,0 +1,57 @@ +import preview from "#.storybook/preview"; +import { useEffect, useState } from "react"; +import { expect, fn, waitFor, within } from "storybook/test"; +import type { AskUserQuestion } from "@schlessera/brain-ui-sdk/protocol"; +import { BrainUiProvider } from "../../../ui-react/src/root-context.js"; +import { createBrainUiRoot } from "../../../ui-react/src/root.js"; +import { AskUserCard } from "../../../ui-react/src/components/chat/ask-user-card.js"; +import { ConsumerDocument, consumerViewport, painted, bounds, accessible } from "./_consumer-parity.js"; + +const HARBOUR = "Ithaca — Ἰθάκη"; +const questions: AskUserQuestion[] = [{ question: "Which harbour first?", header: "Harbour", multiSelect: false, options: [{ label: HARBOUR, description: "Home" }, { label: "Pylos", description: "Nestor’s court" }] }]; + +/** The actual consumer `AskUserCard`, whose Other field and Submit the + * answer-delivery runtime drives at 320px dark and 1280px light. */ +function AnswerTheme({ onSubmit }: { width: number; onSubmit: (requestId: string, answers: Record) => void }) { + const [root] = useState(() => createBrainUiRoot({ storage: null, request: async input => { + throw new Error(`Unexpected answer fixture request: ${String(input)}`); + } })); + useEffect(() => () => root.dispose(), [root]); + return + {}} /> + ; +} + +const firstCall = (spy: unknown) => (spy as { mock: { calls: unknown[][] } }).mock.calls[0]!.slice(0, 2); + +const meta = preview.meta({ + title: "Conversation/Answer theme", component: AnswerTheme, + parameters: { layout: "fullscreen" }, beforeEach: consumerViewport, + args: { width: 320, onSubmit: fn() }, +}); + +export const Phone = meta.story({ + play: async ({ args, userEvent, globals }) => { + await painted(args.width, globals.theme); + const screen = within(document.body); + await userEvent.click(screen.getByRole("radio", { name: /Other/ })); + const field = screen.getByRole("textbox", { name: "Your own answer" }); + const submit = screen.getByRole("button", { name: "Submit" }); + await expect(getComputedStyle(field).colorScheme, "Other field paints the selected theme").toBe(globals.theme); + await expect(submit).toHaveAttribute("aria-disabled", "true"); + await userEvent.type(field, "Scheria — Σχερίη"); + await expect(submit).not.toHaveAttribute("aria-disabled"); + await expect(submit.getBoundingClientRect().height, "Other Submit target height").toBeGreaterThanOrEqual(44); + const well = field.closest(".bk-field")!; + await bounds(well, "Other field"); + await bounds(submit, "Other Submit"); + // The kit card's meta-level contrast gap is the selected option's detail + // line; the typed answer and the enabled Submit carry no such exception. + await accessible(well); + await accessible(submit); + await userEvent.click(submit); + await waitFor(() => expect(args.onSubmit).toHaveBeenCalledTimes(1)); + await expect(firstCall(args.onSubmit)).toEqual(["odysseus-harbour", { "Which harbour first?": "Scheria — Σχερίη" }]); + }, +}); +export const Desktop = Phone.extend({ args: { width: 1280 } }); diff --git a/packages/ui-kit/stories/conversation/JournalTheme.stories.tsx b/packages/ui-kit/stories/conversation/JournalTheme.stories.tsx index cb36e1e6e4..ab891f331c 100644 --- a/packages/ui-kit/stories/conversation/JournalTheme.stories.tsx +++ b/packages/ui-kit/stories/conversation/JournalTheme.stories.tsx @@ -9,7 +9,7 @@ import { ConsumerDocument, consumerViewport, painted, bounds, accessible } from const turnId = "odysseus-journal"; const skill = ".claude/skills/voyage-log/SKILL.md"; -const summary: TurnJournalSummary = { state: "complete", changedFiles: 3, steeringFiles: 1, keptFiles: 3, costUsd: null, costIsEstimate: null, profile: "governed", actor: "interactive", model: null, policyHash: null, sharedAttribution: true, observedAt: Date.UTC(2026, 6, 12) }; +const summary: TurnJournalSummary = { state: "complete", changedFiles: 3, steeringFiles: 1, keptFiles: 3, costUsd: null, costIsEstimate: null, profile: "governed", actor: "interactive", model: null, policyHash: null, sharedAttribution: true, observedAt: Date.UTC(2026, 6, 12), configurationCoverage: "incomplete" }; const version = { kind: "file" as const, mode: 420, bytes: 32, hash: "odysseus-retained", ignored: false }; const observations = [3, 4].map(sequence => ({ turnId, sequence, side: "after" as const })); const changes: TurnJournalChange[] = [ @@ -17,7 +17,7 @@ const changes: TurnJournalChange[] = [ { sequence: 2, path: "notes/voyage.md", scope: "", class: "content", actor: "agent", before: version, after: version, overlappingTurnIds: [] }, ...observations.map(({ sequence }) => ({ sequence, path: "notes/crossing.md", scope: "", class: "content" as const, actor: "agent" as const, before: version, after: version, overlappingTurnIds: ["athena-journal"], conflict: { versions: observations, latest: observations[1]! } })), ]; -const details: TurnJournalDetails = { turnId, sessionId: "ithaca", summary, changes, missing: [], outwardActions: ["approved", "declined"].map((decision, i) => ({ id: i + 1, at: summary.observedAt!, tool: "Bash", action: "git_push", target: "github.com/odysseus/voyage.git", decision: decision as "approved" | "declined", historyRewrite: false, revertible: false })) }; +const details: TurnJournalDetails = { turnId, sessionId: "ithaca", summary, changes, missing: ["ithaca", "pylos"].map(name => ({ path: `workspaces/${name}/brain.config.ts`, reason: "configuration_inputs_not_fully_identified" as const })), outwardActions: ["approved", "declined"].map((decision, i) => ({ id: i + 1, at: summary.observedAt!, tool: "Bash", action: "git_push", target: "github.com/odysseus/voyage.git", decision: decision as "approved" | "declined", historyRewrite: false, revertible: false })) }; function JournalTheme({ onOperation }: { width: number; onOperation: (body: unknown) => void }) { const [root] = useState(() => { @@ -108,6 +108,21 @@ export const Phone = meta.story({ await expect(screen.getByRole("button", { name: "Undo" })).toBeVisible(); } await expect(args.onOperation).toHaveBeenCalledTimes(3); + // The configuration coverage family's runtime cells are 320px dark and + // 1280px light; this owns its badge and inventory paint in both themes. + const badge = disclosure.querySelector("[data-disclosure-badge]")!; + await expect(badge.getBoundingClientRect().width, "coverage badge is visible").toBeGreaterThanOrEqual(13); + await expect(badge.getBoundingClientRect().right, "coverage badge outside truncation").toBeLessThanOrEqual(disclosure.getBoundingClientRect().right); + const coverage = screen.getByRole("button", { name: "Configuration coverage incomplete · 2 inputs not fully identified" }); + await expect(coverage.getBoundingClientRect().height, "coverage disclosure target height").toBeGreaterThanOrEqual(44); + coverage.focus(); await userEvent.keyboard("{Enter}"); + const inventory = await screen.findByRole("region", { name: "Configuration inputs not fully identified, 2" }); + await expect(within(inventory).getAllByRole("listitem")).toHaveLength(2); + const search = screen.getByRole("searchbox", { name: "Find a path" }); + await expect(search.getBoundingClientRect().height, "coverage search target height").toBeGreaterThanOrEqual(44); + await userEvent.type(search, "pylos"); + await bounds(inventory, "coverage inventory"); + await accessible(coverage.closest("[data-turn-journal]")!); // Fixture receipts establish UI dispatch only, never real file restoration. }, }); diff --git a/packages/ui-react/tests/answer-delivery-runtime.test.ts b/packages/ui-react/tests/answer-delivery-runtime.test.ts index 9c3aac80d0..fcf5c66124 100644 --- a/packages/ui-react/tests/answer-delivery-runtime.test.ts +++ b/packages/ui-react/tests/answer-delivery-runtime.test.ts @@ -335,54 +335,57 @@ async function waitForState(page: Page, requestId: string, wanted: string, timeo const online = (page: Page) => page.evaluate(() => window.dispatchEvent(new Event("online"))); describe.skipIf(!executablePath)("answer delivery in a real browser", () => { - for (const theme of ["dark", "light"] as const) { - for (const width of [320, 1280]) { - test(`1887: Other has explicit current-text Submit at ${width}px in ${theme}`, async () => { - const { context, net } = await newContext(width === 320); - try { - const page = await openPage(context); - // The delivery harness is otherwise deliberately unstyled. These - // layout cases need the real built consumer and kit stylesheets. - for (const css of ["../../ui-kit/dist/styles.css", "../dist/styles.css"]) { - await page.addStyleTag({ content: await Bun.file(resolve(import.meta.dir, css)).text() }); - } - await page.setViewportSize({ width, height: 900 }); - await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); - expect(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), "OTHER_LAYOUT_USES_REAL_THEME").toBe(theme); - const id = await ask(page, "ask_user"); - await page.getByRole("radio", { name: /Other/ }).click(); - const field = page.getByRole("textbox", { name: "Your own answer", exact: true }); - const submit = page.getByRole("button", { name: "Submit", exact: true }); - await field.fill("Scheria — Σχερίη"); - expect(await submit.count(), "OTHER_CUSTOM_TEXT_HAS_EXPLICIT_SUBMIT").toBe(1); - await field.fill(" "); - expect(await submit.getAttribute("aria-disabled"), "BLANK_OTHER_SUBMIT_DISABLED").toBe("true"); - await field.press("Enter"); - expect(net.frames.filter(f => f.dir === "up" && f.type === "ask_user_response")).toHaveLength(0); - await field.fill("Scheria — Σχερίη"); - // Editing survives switching away and back; the predefined choice - // replaces Other in a single-select without submitting either draft. - await page.getByRole("radio", { name: new RegExp(HARBOUR) }).click(); - expect(await field.count()).toBe(0); - await page.getByRole("radio", { name: /Other/ }).click(); - expect(await field.inputValue()).toBe("Scheria — Σχερίη"); - await field.fill("Aeaea — Αἰαίη"); - await field.focus(); - await page.keyboard.press("Tab"); - await page.keyboard.press("Tab"); - expect(await submit.evaluate(el => el === document.activeElement), "OTHER_SUBMIT_KEYBOARD_REACHABLE").toBe(true); - expect(await submit.evaluate(el => el.getBoundingClientRect().height), "OTHER_SUBMIT_TOUCH_HEIGHT").toBeGreaterThanOrEqual(44); - expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "OTHER_CARD_NO_OVERFLOW").toBe(true); - if (width === 320) await submit.tap(); - else await submit.press("Space"); - await waitForState(page, id, "answered"); - expect(settlements.get(id), "OTHER_CURRENT_TEXT_SETTLES_ORIGINAL_REQUEST_ONCE").toEqual([ - { answers: { "Which harbour first?": "Aeaea — Αἰαίη" } }, - ]); - expect(net.frames.filter(f => f.dir === "up" && f.type === "ask_user_response")).toHaveLength(1); - } finally { await context.close(); } - }); - } + // Theme selects only colour tokens and `color-scheme`; no Other card + // geometry, focus or settlement path branches on it. The paired cells keep + // both painted themes and both widths (touch tap at 320px, Space at 1280px). + // `Conversation/Answer theme` owns the consumer card's paint in both themes + // (docs/process/theme-parity.md#answer-and-journal-coverage-runtime-cells). + for (const [width, theme] of [[320, "dark"], [1280, "light"]] as const) { + test(`1887: Other has explicit current-text Submit at ${width}px in ${theme}`, async () => { + const { context, net } = await newContext(width === 320); + try { + const page = await openPage(context); + // The delivery harness is otherwise deliberately unstyled. These + // layout cases need the real built consumer and kit stylesheets. + for (const css of ["../../ui-kit/dist/styles.css", "../dist/styles.css"]) { + await page.addStyleTag({ content: await Bun.file(resolve(import.meta.dir, css)).text() }); + } + await page.setViewportSize({ width, height: 900 }); + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + expect(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), "OTHER_LAYOUT_USES_REAL_THEME").toBe(theme); + const id = await ask(page, "ask_user"); + await page.getByRole("radio", { name: /Other/ }).click(); + const field = page.getByRole("textbox", { name: "Your own answer", exact: true }); + const submit = page.getByRole("button", { name: "Submit", exact: true }); + await field.fill("Scheria — Σχερίη"); + expect(await submit.count(), "OTHER_CUSTOM_TEXT_HAS_EXPLICIT_SUBMIT").toBe(1); + await field.fill(" "); + expect(await submit.getAttribute("aria-disabled"), "BLANK_OTHER_SUBMIT_DISABLED").toBe("true"); + await field.press("Enter"); + expect(net.frames.filter(f => f.dir === "up" && f.type === "ask_user_response")).toHaveLength(0); + await field.fill("Scheria — Σχερίη"); + // Editing survives switching away and back; the predefined choice + // replaces Other in a single-select without submitting either draft. + await page.getByRole("radio", { name: new RegExp(HARBOUR) }).click(); + expect(await field.count()).toBe(0); + await page.getByRole("radio", { name: /Other/ }).click(); + expect(await field.inputValue()).toBe("Scheria — Σχερίη"); + await field.fill("Aeaea — Αἰαίη"); + await field.focus(); + await page.keyboard.press("Tab"); + await page.keyboard.press("Tab"); + expect(await submit.evaluate(el => el === document.activeElement), "OTHER_SUBMIT_KEYBOARD_REACHABLE").toBe(true); + expect(await submit.evaluate(el => el.getBoundingClientRect().height), "OTHER_SUBMIT_TOUCH_HEIGHT").toBeGreaterThanOrEqual(44); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "OTHER_CARD_NO_OVERFLOW").toBe(true); + if (width === 320) await submit.tap(); + else await submit.press("Space"); + await waitForState(page, id, "answered"); + expect(settlements.get(id), "OTHER_CURRENT_TEXT_SETTLES_ORIGINAL_REQUEST_ONCE").toEqual([ + { answers: { "Which harbour first?": "Aeaea — Αἰαίη" } }, + ]); + expect(net.frames.filter(f => f.dir === "up" && f.type === "ask_user_response")).toHaveLength(1); + } finally { await context.close(); } + }); } test("1887: multi-select Other retains predefined picks and refuses composing Enter", async () => { diff --git a/packages/ui-react/tests/browser/conversation-consent.offline.tsx b/packages/ui-react/tests/browser/conversation-consent.offline.tsx index 47cd34a5f9..d4adc70e7f 100644 --- a/packages/ui-react/tests/browser/conversation-consent.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-consent.offline.tsx @@ -104,9 +104,13 @@ test("review: provider closure during pending opening settles without late captu s.deliver({ type: "conversation_closed", conversationId: PROFILE.conversationId, epoch: 1, reason: "provider_closed" }); s.client.mute(); s.opened(2); - await new Promise(resolve => setTimeout(resolve, 100)); - expect(s.client.state.getState().micOn).toBe(false); + // Frames are handled as they are delivered, and a capture opens the + // microphone synchronously, so once epoch 2 is applied any capture its + // opening or readiness allowed has already called getUserMedia. Without a + // new capture session the microphone cannot turn on later. + await expect.poll(() => s.client.state.getState().profile?.epoch).toBe(2); expect(mic.opens()).toBe(1); + expect(s.client.state.getState().micOn).toBe(false); }); test("review: hiding during replacement opening cannot delete the retained conversation", async ctx => { diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx index 3fbcbbf73b..66157993d8 100644 --- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx @@ -1,5 +1,5 @@ /// -import { afterAll, beforeAll, expect, test, type TestContext } from "vitest"; +import { afterAll, beforeAll, expect, test, vi, type TestContext } from "vitest"; import { commands, page, userEvent } from "vitest/browser"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; @@ -317,6 +317,9 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale const bounds = targets.map(node => node.getBoundingClientRect()); expect(targets[1].getAttribute("aria-disabled")).toBe("true"); for (const box of bounds) { expect(box.height).toBeGreaterThanOrEqual(44); expect(box.width).toBeGreaterThanOrEqual(44); } + // The strip holds Speaking for 300 ms after playback stops. That timer runs + // on a fake clock, so each gap is exact rather than a real wait. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); }); for (const gap of [10, 40, 100, 20]) { flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" })); await expect.element(page.getByRole("button", { name: "Stop reply", exact: true })).not.toHaveAttribute("aria-disabled", "true"); @@ -324,7 +327,7 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale await userEvent.keyboard("{Tab}"); expect(document.activeElement, "Tab reaches Stop reply in its stable slot").toBe(targets[1]); flushSync(() => s.client.state.setState({ playing: false, interaction: gap === 40 ? "Listening" : "Review before sending" })); - await new Promise(resolve => setTimeout(resolve, gap)); + flushSync(() => vi.advanceTimersByTime(gap)); expect(s.strip().children[1].textContent, "short PCM gaps retain Speaking feedback").toContain("Speaking"); expect(s.client.state.getState().micOn, "display smoothing must not mute or resume capture").toBe(true); expect(s.client.state.getState().playing, "presentation must not alter sample-level state").toBe(false); @@ -338,6 +341,8 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale expect(document.activeElement).toBe(targets[1]); } await s.capture("reply-gap"); + flushSync(() => vi.runOnlyPendingTimers()); + vi.useRealTimers(); await expect.poll(() => targets[1].getAttribute("aria-disabled")).toBe("true"); expect(s.strip().children[1].textContent).toContain("Review before sending"); flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" })); diff --git a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx index 4350363eaf..9c0c3284aa 100644 --- a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx @@ -84,6 +84,14 @@ function controlledMicrophone(ctx: TestContext, freshStreams = false) { +/** A PCM16 frame below the client's speaking threshold (RMS 0.015). */ +function silent(pcm: string) { + const bytes = Uint8Array.from(atob(pcm), char => char.charCodeAt(0)), view = new DataView(bytes.buffer); + let energy = 0; + for (let i = 0; i < bytes.length; i += 2) energy += (view.getInt16(i, true) / 32768) ** 2; + return Math.sqrt(energy / (bytes.length / 2)) <= 0.015; +} + // Real AudioWorklet capture and playback exercise the interval before the // natural 700 ms endpoint. Provider frames remain entirely offline. for (const action of ["send", "discard", "answer", "mute"] as const) for (const noisy of [false, true]) test(`manual ${action}: ${noisy ? "bounded noisy deadline" : "quiet recovery"} after interrupted speech`, async ctx => { @@ -99,9 +107,12 @@ for (const action of ["send", "discard", "answer", "mute"] as const) for (const await expect.poll(() => s.client.state.getState().playing).toBe(true); mic.speak(); await expect.poll(() => s.client.state.getState().outputRecovery).toBe("speaking"); + const quietFrom = s.socket.frames("conversation_audio").length; mic.quiet(); // Drain queued real microphone blocks, still before the 700 ms endpoint. - await new Promise(resolve => setTimeout(resolve, 200)); + // Blocks arrive in order, so the first frame below the client's speaking + // threshold follows every speaking block queued before quiet(). + await expect.poll(() => s.socket.frames("conversation_audio").slice(quietFrom).some(frame => silent(String(frame.pcm)))).toBe(true); if (action === "answer") { s.deliver({ type: "text_delta", sessionId: SESSION, turnId: "ithaca-turn", text: "Which departure works?" }); s.deliver({ type: "ask_user_request", sessionId: SESSION, turnId: "ithaca-turn", requestId: "ithaca-question", questions: [{ question: "Which day?", header: "Day", multiSelect: false, options: [{ label: "Tomorrow", description: "Before departure" }] }] }); diff --git a/packages/ui-react/tests/browser/conversation.offline.tsx b/packages/ui-react/tests/browser/conversation.offline.tsx index 3c7ebb573f..b2cbab7d7e 100644 --- a/packages/ui-react/tests/browser/conversation.offline.tsx +++ b/packages/ui-react/tests/browser/conversation.offline.tsx @@ -1258,7 +1258,8 @@ for (const reason of ["disconnected", "provider_closed"] as const) test(`recover expect(mic.streams[0]!.getTracks().every(track => track.readyState === "ended")).toBe(true); expect(s.client.state.getState().text).toBe("Ask Nestor about the ships"); // Withhold the replacement receipt: consent alone cannot reopen capture. - await new Promise(resolve => setTimeout(resolve, 30)); + // The closure was handled as it was delivered, and a capture opens the + // microphone synchronously, so no window is needed to see that none started. assertPrivate(); expect(mic.opens()).toBe(1); s.opened(2); diff --git a/packages/ui-react/tests/browser/recording-limits.offline.tsx b/packages/ui-react/tests/browser/recording-limits.offline.tsx index eea53786ed..e47a6ad41b 100644 --- a/packages/ui-react/tests/browser/recording-limits.offline.tsx +++ b/packages/ui-react/tests/browser/recording-limits.offline.tsx @@ -188,6 +188,9 @@ test("source starvation reports only encoded audio", async (ctx) => { const capture = await c.store.start({ timesliceMs: 250 }); await c.committed(2); await mic.contexts[0]!.suspend(); + // Kept: the starvation is real time under test. The suspended source must + // stay silent for longer than the 800 ms margin asserted below, while the + // wall clock runs, so no condition or fake clock can stand in for it. await new Promise(resolve => setTimeout(resolve, 1200)); await mic.contexts[0]!.resume(); await c.committed(c.committedCount() + 2); diff --git a/packages/ui-react/tests/browser/share-review/app.tsx b/packages/ui-react/tests/browser/share-review/app.tsx index 667da493f8..11f1a28a42 100644 --- a/packages/ui-react/tests/browser/share-review/app.tsx +++ b/packages/ui-react/tests/browser/share-review/app.tsx @@ -31,6 +31,26 @@ window.addEventListener("pagehide", () => { if (onlineDescriptor) Object.defineProperty(navigator, "onLine", onlineDescriptor); else delete (navigator as { onLine?: boolean }).onLine; }); +// Review admission takes the native lock `brain-ui:share-review:` with +// `ifAvailable` (`holdShareReview`, src/lib/share-review.ts). A request that +// admits the review stays open while this tab owns it; every other request +// settles once its attempt ends: the lock was taken elsewhere, the original +// could not be recovered for this account, or recovery failed. Counting +// requests and settlements lets a test wait for this tab's admission decision +// instead of a fixed window. The native lock itself is untouched. +const locks = navigator.locks; +const lockRequest = locks.request; +const admission = { requested: 0, settled: 0 }; +Object.defineProperty(locks, "request", { configurable: true, value(this: LockManager, ...args: Parameters) { + const pending = (lockRequest as (...args: Parameters) => Promise).apply(this, args); + if (String(args[0]).startsWith("brain-ui:share-review:")) { + admission.requested++; + const settle = () => { admission.settled++; }; + pending.then(settle, settle); + } + return pending; +} }); +window.addEventListener("pagehide", () => Reflect.deleteProperty(locks, "request")); let holdAdmission = false; let refuseSend = false; let pendingAdmission: { requestId: string } | undefined; @@ -81,6 +101,7 @@ const fixture = { refuseSend: () => { refuseSend = true; }, startConfirm: () => { void intake!.confirm(ui.stores.share.getState().queue[0]!); }, pending: () => pendingAdmission !== undefined, + admission: () => ({ ...admission }), accept: () => { if (!pendingAdmission) return; const { requestId } = pendingAdmission; diff --git a/packages/ui-react/tests/browser/share-review/commands.ts b/packages/ui-react/tests/browser/share-review/commands.ts index ecd6ace89e..bbd610a204 100644 --- a/packages/ui-react/tests/browser/share-review/commands.ts +++ b/packages/ui-react/tests/browser/share-review/commands.ts @@ -14,7 +14,23 @@ async function action(page: Page, method: string): Promise { return page.evaluate(method => (window as unknown as { shareProof: Record unknown> }).shareProof[method]!(), method) as Promise; } async function ready(page: Page) { await page.waitForFunction(() => "shareProof" in window); } +type Admission = { requested: number; settled: number }; +const admission = (page: Page) => action(page, "admission"); +/** + * Wait for this page's review admission to decide, instead of a fixed window. + * Decided means a review was admitted, or at least one share-review lock + * request was made after `since` and every request has settled: each attempt + * ended without holding review (see `admission` in app.tsx). + */ +async function decided(page: Page, since = 0) { + await page.waitForFunction(since => { + const proof = (window as unknown as { shareProof: { queue(): string[]; admission(): Admission } }).shareProof; + const { requested, settled } = proof.admission(); + return proof.queue().length > 0 || (requested > since && settled === requested); + }, since); +} async function queue(page: Page) { await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 1); } +async function empty(page: Page) { await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 0); } async function original(page: Page) { const originals = await action(page, "inventory"); assert.equal(originals.length, 1, "one durable original remains before authoritative handoff"); @@ -39,8 +55,8 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena if (scenario === "lost-response" && uploads === 1) { // Start the response before losing its body. An unopened response on // a reused connection can be transparently retried by Chromium. - res.writeHead(201, { "content-type": "application/json" }); res.write("{"); - setTimeout(() => res.destroy(), 50); return; + // Close only after the opened response is flushed to the socket. + res.writeHead(201, { "content-type": "application/json" }); res.write("{", () => res.destroy()); return; } res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ ...(scenario === "lost-admission" && uploads > 1 ? { filingSessionId: "odysseus-filing" } : {}), id: "odysseus-intake", receivedAt: Date.now(), dir: ".brain/inbox/odysseus-intake", text: "Penelope keeps the original loom plan.", files: scenario === "partial" ? [] : [{ name: "loom.pdf", path: ".brain/inbox/odysseus-intake/loom.pdf", mediaType: "application/pdf", bytes: 5 }] })); @@ -64,7 +80,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena const landing = await action(page, "stash"); if (scenario === "transfer" || scenario === "transfer-signout") { const faulty = new URL(landing); faulty.searchParams.set("copyFailure", "yes"); - await page.goto(faulty.href); await ready(page); await page.waitForTimeout(1200); + await page.goto(faulty.href); await ready(page); await decided(page); assert.deepEqual(await action(page, "queue"), [], "failed durable copy never admits memory-only review"); await original(page); assert.equal((await action<{ shares: number }>(page, "loss")).shares, 1, "sign-out inventory includes the interrupted transfer"); @@ -73,7 +89,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena assert.deepEqual(await action(page, "cleared"), { originals: 0, account: true }, "intentional sign-out removes the transfer remnant as well as account work"); assert.equal(uploads, 0); assert.deepEqual(egress, []); return "passed"; } - const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other); await other.waitForTimeout(1200); + const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other); await decided(other); assert.deepEqual(await action(other, "queue"), [], "transfer journal prevents cross-account adoption after a failed copy"); await other.close(); await page.goto(landing); await ready(page); await queue(page); await original(page); assert.equal(uploads, 0); assert.deepEqual(egress, [], "fixture has no external egress"); return "passed"; @@ -116,9 +132,11 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena await action(page, "expire"); assert.deepEqual(await action(page, "queue"), [], "auth lock drops the memory payload"); const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other); - await other.waitForTimeout(1500); - assert.deepEqual(await action(other, "queue"), [], "another account cannot recover this original"); + // Admission reads only this account's review rows and the stashed + // originals, which `inventory` reads too. Both are empty, so this page + // has nothing it could admit and the queue check needs no window. assert.deepEqual(await action(other, "inventory"), [], "another account cannot read this original"); + assert.deepEqual(await action(other, "queue"), [], "another account cannot recover this original"); await other.close(); assert.equal(await action(page, "restore"), true, "real auth lock restores the same account"); await queue(page); await original(page); assert.equal(uploads, 0); @@ -127,7 +145,8 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena assert.deepEqual(await action(page, "queue"), [], "unmount drops review memory when releasing ownership"); await original(page); const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await queue(peer); - await action(page, "remount"); await page.waitForTimeout(1200); + const since = (await admission(page)).requested; + await action(page, "remount"); await decided(page, since); assert.deepEqual(await action(page, "queue"), [], "a remounted root cannot show another tab's review"); await peer.close(); await queue(page); await original(page); assert.equal(uploads, 0); @@ -135,7 +154,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena await action(page, "mountSecond"); await action(page, "unmount"); assert.equal((await action(page, "queue")).length, 1, "a remaining consumer keeps the root's ownership"); await action(page, "confirm"); await original(page); - const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await peer.waitForTimeout(1200); + const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await decided(peer); assert.deepEqual(await action(peer, "queue"), [], "another tab cannot claim a root with a live consumer"); await action(page, "resume"); await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 0); @@ -159,16 +178,25 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena await page.close(); const [first, second] = await Promise.all([context.newPage(), context.newPage()]); await Promise.all([first.goto(landing), second.goto(landing)]); await Promise.all([ready(first), ready(second)]); - await first.waitForTimeout(1500); + // Wait for one tab to admit. The other's first attempt may have run while + // the closed owner still held the lock, so wait for one of its attempts + // that starts after the admission: that one meets the winner's lock. + const admitted = [first, second].map(tab => queue(tab).then(() => tab)); + admitted.forEach(wait => wait.catch(() => {})); + const loser = await Promise.race(admitted) === first ? second : first; + await decided(loser, (await admission(loser)).requested); const counts = [(await action(first, "queue")).length, (await action(second, "queue")).length]; assert.equal(counts[0]! + counts[1]!, 1, "native lock admits exactly one racing tab"); const owner = counts[0] ? first : second; const survivor = counts[0] ? second : first; await owner.close(); await queue(survivor); await original(survivor); assert.equal(uploads, 0, "abandonment does not grant consent"); } else if (scenario === "dismiss") { - await action(page, "dismiss"); await page.waitForTimeout(100); + // Dismiss removes the review from the queue only after its durable delete. + await action(page, "dismiss"); await empty(page); assert.deepEqual(await action(page, "inventory"), [], "dismiss commits durable cleanup"); - await page.reload(); await ready(page); await page.waitForTimeout(1200); + await page.reload(); await ready(page); + // Nothing is left to admit (see "auth"), so the queue check needs no window. + assert.deepEqual(await action(page, "inventory"), []); assert.deepEqual(await action(page, "queue"), []); assert.equal(uploads, 0); } else if (scenario === "signout") { assert.equal((await action<{ shares: number }>(page, "loss")).shares, 1, "sign-out warns about the retained original"); @@ -186,11 +214,14 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena await page.getByRole("button", { name: "Keep working", exact: true }).click(); await original(page); await action(page, "clear"); await page.close(); - const fresh = await context.newPage(); await fresh.goto(origin); await ready(fresh); await fresh.waitForTimeout(1200); + const fresh = await context.newPage(); await fresh.goto(origin); await ready(fresh); + // Sign-out removed the originals and sealed the account partition, so + // this page has nothing it could admit and the queue check needs no window. + assert.deepEqual(await action(fresh, "cleared"), { originals: 0, account: true }, "account sign-out clear removes retained originals"); assert.deepEqual(await action(fresh, "queue"), [], "account sign-out clear removes retained shares"); assert.equal(uploads, 0); } else if (scenario === "ttl") { - await action(page, "expireRecord"); await page.reload(); await ready(page); await page.waitForTimeout(1200); + await action(page, "expireRecord"); await page.reload(); await ready(page); await decided(page); assert.deepEqual(await action(page, "queue"), [], "expired account reviews are not admitted"); assert.deepEqual(await action(page, "inventory"), [], "existing TTL bounds retained originals"); assert.equal(uploads, 0); @@ -198,7 +229,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena await action(page, "resume"); await action(page, "confirm"); assert.equal(uploads, 1); await original(page); assert.equal(await action(page, "chats"), 0, "incomplete receipt never hands off or starts chat"); - await action(page, "dismiss"); await page.waitForTimeout(100); + await action(page, "dismiss"); await empty(page); assert.deepEqual(await action(page, "inventory"), []); } else { if (scenario === "lost-response") await action(page, "resume"); diff --git a/packages/ui-react/tests/browser/storage-guidance.layout.tsx b/packages/ui-react/tests/browser/storage-guidance.layout.tsx index a6382cb0aa..712ecf5452 100644 --- a/packages/ui-react/tests/browser/storage-guidance.layout.tsx +++ b/packages/ui-react/tests/browser/storage-guidance.layout.tsx @@ -293,8 +293,10 @@ test("A late response from the prior account cannot replace current evidence", a f.guidance.capacities[0]!.severity = "low"; ui.stores.connection.getState().setVpnStatus("connected", "athena"); await expect.poll(() => warning()?.textContent).toContain("Low space"); + const delivered = f.delivered(); release(); - await new Promise((resolve) => setTimeout(resolve, 50)); + // The late response has been read; its ownership check has run. + await expect.poll(f.delivered).toBeGreaterThan(delivered); expect( warning()?.textContent, "STORAGE_ACCOUNT_RESPONSE_OWNERSHIP" @@ -325,8 +327,12 @@ test("Indicator and authenticated tap-through honor Settings leave guards and cl refresh(); await expect.poll(warning).toBeNull(); history.replaceState(null, "", "#/settings/storage"); - window.dispatchEvent(new HashChangeEvent("hashchange")); - await new Promise((resolve) => setTimeout(resolve, 50)); + const answered = f.answered(); + // Commit the route change and its effects synchronously: the open decision + // has run when flushSync returns. Then wait for the read the route starts + // to be answered (refused) and handled, so the next refresh is a new read. + flushSync(() => window.dispatchEvent(new HashChangeEvent("hashchange"))); + await expect.poll(f.answered).toBeGreaterThan(answered); expect( ui.stores.ui.getState().settingsPanelOpen, "STORAGE_TAP_REQUIRES_AUTHORITY" @@ -449,8 +455,10 @@ test("A replaced root cannot publish its late operational response", async () => ) ); await expect.poll(() => next.reads.length).toBeGreaterThan(0); + const delivered = oldFixture.delivered(); release(); - await new Promise((resolve) => setTimeout(resolve, 50)); + // The old root's late response has been read; its ownership check has run. + await expect.poll(oldFixture.delivered).toBeGreaterThan(delivered); expect(warning(), "STORAGE_REPLACED_ROOT_HIDES_OLD_GUIDANCE").toBeNull(); old.dispose(); }); diff --git a/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx b/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx index a1467b243c..5f6f6cf983 100644 --- a/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx +++ b/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx @@ -1,5 +1,5 @@ /// -import { afterAll, beforeAll, expect, test, type TestContext } from "vitest"; +import { afterAll, beforeAll, expect, test, vi, type TestContext } from "vitest"; import { commands, page, userEvent } from "vitest/browser"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; @@ -61,7 +61,11 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280]) const box = trigger.getBoundingClientRect(); expect(box.width).toBeGreaterThanOrEqual(44); expect(box.height).toBeGreaterThanOrEqual(44); for (const [x,y] of [[box.left + 2,box.top + box.height/2],[box.right-2,box.top+box.height/2],[box.left+box.width/2,box.top+2],[box.left+box.width/2,box.bottom-2]]) expect(document.elementFromPoint(x,y)?.closest("button")).toBe(trigger); + // The qualifier's 300 ms show delay and 150 ms hide grace run on a fake + // clock, so "every pending timer has run" is a step, not a window. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); }); trigger.focus(); + flushSync(() => vi.advanceTimersByTime(300)); await expect.poll(() => document.querySelector('[role="tooltip"]')?.textContent).toContain("Words may be uncertain; speaker unverified."); const hint = document.querySelector('[role="tooltip"]')!; expect(hint.getBoundingClientRect().left).toBeGreaterThanOrEqual(0); @@ -70,8 +74,9 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280]) expect(getComputedStyle(trigger).outlineWidth).toBe("2px"); await userEvent.keyboard("{Escape}"); await expect.poll(() => document.querySelector('[role="tooltip"]')).toBeNull(); - await new Promise(r => setTimeout(r, 350)); + flushSync(() => vi.runOnlyPendingTimers()); expect(document.querySelector('[role="tooltip"]'), "Escape suppresses while still focused").toBeNull(); + vi.useRealTimers(); await userEvent.keyboard("{Enter}"); const dialog = document.querySelector('dialog[open]')!; expect(dialog, "native Enter opens evidence").not.toBeNull(); @@ -104,12 +109,16 @@ test("pointer can read tooltip then tap details; playback and restoration are in const s = await scene(ctx, 320, "light", 1, false); s.render(<>); const trigger = qualifier(s.host, "generated"); + // As above: the show delay and hide grace run on a fake clock. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); }); await userEvent.hover(trigger); + flushSync(() => vi.advanceTimersByTime(300)); await expect.poll(() => document.querySelector('[role="tooltip"]')?.textContent).toContain("Remaining reply not spoken locally. Earlier spoken portion unknown."); const hint = document.querySelector('[role="tooltip"]')!; await userEvent.hover(hint); - await new Promise(r => setTimeout(r, 350)); + flushSync(() => vi.runOnlyPendingTimers()); expect(hint.isConnected, "hoverable explanation persists").toBe(true); + vi.useRealTimers(); await userEvent.keyboard("{Escape}"); expect(document.querySelector('[role="tooltip"]')).toBeNull(); const box = trigger.getBoundingClientRect(); diff --git a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts index 011b890739..199eb9858a 100644 --- a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts +++ b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts @@ -157,6 +157,8 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { if (body.releaseValidation) releaseValidation(); if (body.identify) identify(); if (body.release) release(); + // Kept, pacing only: the reply is a snapshot, and tests poll "step" until + // their condition holds, so this drain only batches more frames into it. await Bun.sleep(10); return Response.json({ frames: frames.splice(0), sent: sent.splice(0), tasks, released, opening, validationHeld, validationCalls, historyPending: pendingHistory.length > 0, providerOpens, providerCloses, missingChatExists: catalog.hasSession!("odysseus-ithaca"), effect: existsSync(join(root, "notes/contextual-raft.md")) }); } }); diff --git a/packages/ui-react/tests/fixtures/dialogue-browser-server.ts b/packages/ui-react/tests/fixtures/dialogue-browser-server.ts index a99c7c805a..2bbed7843d 100644 --- a/packages/ui-react/tests/fixtures/dialogue-browser-server.ts +++ b/packages/ui-react/tests/fixtures/dialogue-browser-server.ts @@ -237,6 +237,10 @@ const server = Bun.serve({ if(body.parallelStarts && (frame as {type?:string}).type==="conversation_start") parallel!.handlers.onMessage({data:JSON.stringify({...frame as object,requestId:"pylos-parallel",disclosed:host.conversations!.profile(true)})} as MessageEvent,parallel!.ws); } if(body.parallelLeave && parallel){const opened=parallel.frames.find(f=>f.type==="conversation_opened");if(opened?.type!=="conversation_opened")throw Error("Parallel conversation did not open");parallel.handlers.onMessage({data:JSON.stringify({type:"conversation_stop",conversationId:opened.conversationId})} as MessageEvent,parallel.ws);} + // Kept, pacing only: each client frame's dispatch starts on a microtask + // and has no completion handle (createWsHandlers onMessage). The browser + // tests poll "step" replies until their condition holds, so this drain + // only lets one reply carry the frames' effects; it decides no outcome. await Bun.sleep(10); if(body.backendPrefix) emitPrefix?.(body.backendPrefix); if (body.seedTypedHistory) { @@ -275,6 +279,8 @@ const server = Bun.serve({ } let delivered=0; for (const frame of body.provider ?? []) { + // Kept, pacing for the interleaving under test: the task completes during + // delivery, between two provider frames. Tests poll for the outcome. if(body.finishDuring===delivered){if(body.resultText)FACT=body.resultText;complete?.();await Bun.sleep(5);} ingress.push(frame);delivered++; if (remote?.readyState === WebSocket.OPEN) remote.send(JSON.stringify(frame)); @@ -286,6 +292,9 @@ const server = Bun.serve({ backendTailQuota=body.backendTailQuota===true; multipart=body.multipart===true; failResult=body.failResult===true; if (body.release) complete?.(); + // Kept, pacing under the held writer, as above: the adapter consumes these + // frames while the quota or pressure hold is still in place. Tests poll + // for the outcome; historySettled below is the barrier when no writes are held. await Bun.sleep(20); await releaseQuota?.(); if(body.expireWrites){deadlineClock?.expire();await new Promise(resolve=>setImmediate(resolve));} diff --git a/packages/ui-react/tests/fixtures/storage-guidance.ts b/packages/ui-react/tests/fixtures/storage-guidance.ts index af50686f2f..cc64f8a464 100644 --- a/packages/ui-react/tests/fixtures/storage-guidance.ts +++ b/packages/ui-react/tests/fixtures/storage-guidance.ts @@ -167,6 +167,12 @@ export function storageGuidanceFixture() { let status = 200, hold: Promise | null = null; const reads: string[] = []; + // Guidance and history responses handed to the consumer, and those whose + // body it has read. The consumer's handling runs in the microtasks that + // follow, so a test can wait for a response to have been handled instead of + // a fixed window. A refused response is answered but never read. + let answered = 0, + delivered = 0; const request = async (url: string, init?: RequestInit) => { const path = new URL(url, "http://fixture.invalid").pathname; if (!path.endsWith("/guidance") && !path.endsWith("/history")) @@ -178,10 +184,14 @@ export function storageGuidanceFixture() { responseStatus = status, wait = hold; if (wait) await wait; // Intentionally ignores abort: exercise the consumer's response ownership guard. - return Response.json( + const response = Response.json( responseStatus === 200 ? body : { error: "Synthetic authority response" }, { status: responseStatus } ); + const json = response.json.bind(response); + response.json = () => json().finally(() => { delivered++; }); + answered++; + return response; }; return { inventory, @@ -189,6 +199,8 @@ export function storageGuidanceFixture() { history, request, reads, + answered: () => answered, + delivered: () => delivered, setStatus(value: number) { status = value; }, diff --git a/packages/ui-react/tests/runtime-hook-phases.test.ts b/packages/ui-react/tests/runtime-hook-phases.test.ts index 093a137249..895b79e027 100644 --- a/packages/ui-react/tests/runtime-hook-phases.test.ts +++ b/packages/ui-react/tests/runtime-hook-phases.test.ts @@ -39,7 +39,11 @@ test("pending output remains distinguishable from a completed channel", async () let complete = false; const observation = hook.child("package-build", { pid: 42, stdout: heldOutput, stderr: new ReadableStream({ start(controller) { controller.close(); } }), exited: Promise.resolve(0) }).then(() => { complete = true; }); - await Bun.sleep(20); + // The exit and the closed stderr are observed, and one macrotask later the + // held stdout is the only thing the completion can still be waiting on. + // The test's own timeout bounds this condition. + while (!(records.some((r) => r.event === "exit") && records.some((r) => r.event === "stderr-complete"))) await Bun.sleep(1); + await new Promise((resolve) => setTimeout(resolve, 0)); expect(records.some((r) => r.event === "exit")).toBe(true); expect(records.some((r) => r.event === "stderr-complete")).toBe(true); expect(records.some((r) => r.event === "stdout-complete")).toBe(false); diff --git a/packages/ui-react/tests/turn-journal-runtime.test.ts b/packages/ui-react/tests/turn-journal-runtime.test.ts index 464e59bd37..56e08b3aac 100644 --- a/packages/ui-react/tests/turn-journal-runtime.test.ts +++ b/packages/ui-react/tests/turn-journal-runtime.test.ts @@ -98,7 +98,7 @@ async function scene(width = 1280, theme = "dark", replay = false, conflict = fa // Keep native widths, live/replay, zoom, keyboard focus, HTTP download bytes and // real Revert/Undo file effects here with deterministic theme selection. const journalRuntimeCells = [[320, "dark"], [1280, "light"]] as const; -for (const width of [320, 1280]) for (const theme of ["dark", "light"]) test(`journal configuration coverage keeps small changes first and preserves inspection ${theme} ${width}`, async () => { +for (const [width, theme] of journalRuntimeCells) test(`journal configuration coverage keeps small changes first and preserves inspection ${theme} ${width}`, async () => { const { context, page, outside } = await scene(width, theme); let release: (() => void) | undefined, hold = false, fail = false, reads = 0; let started: (() => void) | undefined; diff --git a/packages/ui-sdk/tests/identity-broker-qualification.native.ts b/packages/ui-sdk/tests/identity-broker-qualification.native.ts index 700a8c75bc..786a344b14 100644 --- a/packages/ui-sdk/tests/identity-broker-qualification.native.ts +++ b/packages/ui-sdk/tests/identity-broker-qualification.native.ts @@ -491,6 +491,11 @@ raise SystemExit(child.wait())`); try { await until(() => existsSync(pulse) && statSync(pulse).size > 2, "IDENTITY_NESTED_PID_DID_NOT_START"); expect(workerPids().length).toBeGreaterThan(1); + // Kept real time (here and after the kill): negative observations. The + // payload appends to the pulse every 20 ms from inside a nested PID + // namespace. The broker signals the tree synchronously, but only the + // pulse shows that every writer stopped, including one outside the PIDs + // this test can list. 160 ms spans eight pulses; 100 ms spans five. worker.freeze(); const frozen = statSync(pulse).size; await sleep(160); expect(statSync(pulse).size).toBe(frozen); worker.resume(); await until(() => statSync(pulse).size > frozen + 2, "IDENTITY_NESTED_PID_DID_NOT_RESUME"); worker.kill("SIGKILL"); expect(await worker.exited).toBe(137); expect(errors()).toBe(""); @@ -515,6 +520,8 @@ with open('${pulse}','a',buffering=1) as out: } const result = await outcome; expect(result).toHaveProperty("error"); expect(String((result as { error: string }).error)).toMatch(/supervisor|control|supervision/); console.log(JSON.stringify({ supervisionMode: mode, outcome: result, stderr: errors() })); + // Kept real time below: no listed PID remains, and only the pulse, which + // grows every 20 ms, would show a writer that escaped the list. await until(() => workerPids().length === 0, "IDENTITY_SUPERVISION_LOSS_LEFT_WRITER").catch(error => { console.error("Surviving worker processes", workerPids().map(pid => ({pid, status:readFileSync(`/proc/${pid}/status`,"utf8").split("\n").filter(line=>/^(Name|State|PPid|Uid):/.test(line))}))); throw error; }); const ended = statSync(pulse).size; await sleep(100); expect(statSync(pulse).size).toBe(ended); } finally { await close(worker); } @@ -537,6 +544,7 @@ await worker.exited;`; await until(()=>existsSync(pulse)&&statSync(pulse).size>2,"IDENTITY_CHILD_SERVER_WORKER_DID_NOT_START"); server.kill("SIGKILL");expect(await server.exited).toBe(137); await until(()=>workerPids().length===0,"IDENTITY_SERVER_DEATH_LEFT_WORKER"); + // Kept real time: as above, the 20 ms pulse is the only witness of a writer outside the listed PIDs. const ended=statSync(pulse).size;await sleep(100);expect(statSync(pulse).size).toBe(ended);if(duringSetup)expect(existsSync(mustNotRun)).toBe(false); await stdout;expect(await stderr).toBe(""); } finally { if(server.exitCode===null)server.kill("SIGKILL");await server.exited; } diff --git a/packages/ui-sdk/tests/maintenance-worker-kill-child.ts b/packages/ui-sdk/tests/maintenance-worker-kill-child.ts index 465c3013ca..a2d464247e 100644 --- a/packages/ui-sdk/tests/maintenance-worker-kill-child.ts +++ b/packages/ui-sdk/tests/maintenance-worker-kill-child.ts @@ -226,6 +226,8 @@ async function settled(f: Awaited>) { if (f.o.child) expect(await until(() => !alive(f.o.child!), 1000), "OWNED_CHILD_MUST_STOP").toBe(true); } +// The zero-delay `heartbeat` timer is the observation (#3332): it fires only if +// stop confirmation yields to the event loop instead of spinning on it. test("snapshot fork ordering: first signal follows real fork acknowledgement", async () => { const f = await fixture(); let heartbeat = false; const { worker, signals } = observed(f, () => injectFork(f)); @@ -262,20 +264,22 @@ test("missing children file uses real PPid fallback", async () => { }); test("every thread must confirm stop before the snapshot", async () => { - const f = await fixture(true); injectFork(f); bind(f.outer); let heartbeat = false, nonleaderRead = false, prematureSnapshot = false; + const f = await fixture(true); injectFork(f); bind(f.outer); let nonleaderRead = false, prematureSnapshot = false; + // A non-leader thread reports itself running for its first two polls, then + // its real stopped state; counted, so no timer decides when it confirms. + let unconfirmedReads = 2, lastReadUnconfirmed = false; const original = fs.readFileSync; const spy = spyOn(fs, "readFileSync").mockImplementation(((path: unknown, ...args: unknown[]) => { const name = String(path); const value = Reflect.apply(original, fs, [path, ...args]); if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/stat") && name !== `/proc/${f.outer.pid}/task/${f.outer.pid}/stat`) { - nonleaderRead = true; - if (!heartbeat && typeof value === "string") return value.replace(/\) [Tt] /, ") S "); + nonleaderRead = true; lastReadUnconfirmed = false; + if (unconfirmedReads > 0 && typeof value === "string") { unconfirmedReads--; lastReadUnconfirmed = true; return value.replace(/\) [Tt] /, ") S "); } } - if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/children") && !heartbeat) prematureSnapshot = true; + if (name.startsWith(`/proc/${f.outer.pid}/task/`) && name.endsWith("/children") && lastReadUnconfirmed) prematureSnapshot = true; return value; }) as typeof fs.readFileSync); restores.push(() => spy.mockRestore()); - setTimeout(() => { heartbeat = true; }, 10); cancellation.killWorker(f.outer); await settled(f); await complete(f.outer); - expect(nonleaderRead && !prematureSnapshot, "ALL_THREADS_CONFIRMED_BEFORE_SNAPSHOT").toBe(true); + expect(nonleaderRead && !prematureSnapshot && unconfirmedReads === 0, "ALL_THREADS_CONFIRMED_BEFORE_SNAPSHOT").toBe(true); }); test("empty outer terminates and a fork request while stopped cannot create a child", async () => { diff --git a/packages/ui-sdk/tests/native-identity-inspector.test.ts b/packages/ui-sdk/tests/native-identity-inspector.test.ts index d5512a94e1..03268e8a1f 100644 --- a/packages/ui-sdk/tests/native-identity-inspector.test.ts +++ b/packages/ui-sdk/tests/native-identity-inspector.test.ts @@ -82,6 +82,9 @@ test("an interrupted or timed-out inspection is unknown and the next one starts // Opening a FIFO for reading blocks until a writer appears: the loop program waits. await expect(inspect.run("loop", fifo), "NATIVE_INSPECTOR_TIMEOUT_UNKNOWN").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("operation timeout exceeded") }); const controller = new AbortController(), pending = inspect.run("loop", fifo, controller.signal); + // Kept real time (#3332): the abort must land while the interpreter is blocked + // in the kernel's FIFO open. Nothing portable reports that state (the wait + // channel is not readable on every host), so the run gets 100 ms to reach it. setTimeout(() => controller.abort(new Error("Odysseus stopped the inspection")), 100); await expect(pending, "NATIVE_INSPECTOR_ABORT_UNKNOWN").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("Odysseus stopped the inspection") }); expect(lastLine((await inspect.run("root", root)).errors)).toBe("RuntimeError: not a subvolume root"); 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-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index e53171d421..8ff9a05830 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -127,16 +127,23 @@ test("a scratch mask's ignore check runs its real maintenance worker with the ev } finally { f.cleanup(); } }); -/** A supervisor request that takes `ms`, counting the ticks that fire while it is outstanding. */ +/** + * A supervisor request, counting the ticks that fire while it is outstanding. + * The blocking form holds the thread for `ms`, as a synchronous round trip + * would: no timer can fire inside it, so it counts none however long it takes. + * The awaited form is outstanding until the 1 ms ticker has actually fired, + * the one thing an event loop left free does, instead of for `ms`. + */ function statusRequests(replies: IdentityWorkerStatus[], ms: number) { const seen = { requests: 0, ticksDuringRequests: 0 }; let ticks = 0; - const timer = setInterval(() => { ticks++; }, 1); + const ticked: Array<() => void> = []; + const timer = setInterval(() => { ticks++; for (const resolve of ticked.splice(0)) resolve(); }, 1); const status = () => workerStep(() => { const before = ticks; Bun.sleepSync(ms); seen.ticksDuringRequests += ticks - before; return replies[Math.min(seen.requests++, replies.length - 1)]!; }, async () => { - const before = ticks; await Bun.sleep(ms); seen.ticksDuringRequests += ticks - before; + const before = ticks; await new Promise(resolve => { ticked.push(resolve); }); seen.ticksDuringRequests += ticks - before; return replies[Math.min(seen.requests++, replies.length - 1)]!; }); return { seen, status, stop: () => clearInterval(timer) }; @@ -177,7 +184,11 @@ test("a broker release that cannot confirm cleanup after the exit refuses that e finish: () => { finished = true; }, release: async () => { throw new identity.WorkerIdentityCleanupError("worker_identity_cleanup_unconfirmed: fixture"); } }) .then(code => code, (error: unknown) => error); expect(identity.workerCleanupUnconfirmed(refusal), "IDENTITY_EXIT_RELEASE_FAILURE_OBSERVABLE").toBe(true); - await Bun.sleep(20); + // The release rejected before the exit's refusal was observed, and every + // step here is in memory. Bun reports an unhandled rejection once the + // microtasks drain, before the next macrotask; under `bun test` the runner + // fails this test with it, as it did after the former 20 ms window. + await new Promise(resolve => setImmediate(resolve)); expect(unhandled, "IDENTITY_RELEASE_FAILURE_HANDLED").toEqual([]); } finally { process.off("unhandledRejection", record); requests.stop(); } }); @@ -205,21 +216,28 @@ test("an exit settles only once its release has, and a failed supervision is ref }); test("a supervisor lost while a status request is outstanding refuses once and ignores the late answer", async () => { - const requests = statusRequests([{ exited: true, code: 0 }], 150); + // The request is held open, so it is outstanding by construction rather + // than by a sleep shorter than its reply. + const entered = Promise.withResolvers(), reply = Promise.withResolvers(), answered = Promise.withResolvers(); + let requests = 0; + const status = () => workerStep(() => { throw new Error("IDENTITY_STATUS_MUST_NOT_BLOCK"); }, async () => { + entered.resolve(); await reply.promise; requests++; + setTimeout(answered.resolve, 0); // after the late answer's own continuation has run + return { exited: true, code: 0 }; + }); const owner = supervision(); let lose!: (code: number) => void; - try { - const exit = identityWorkerExit(requests.status, new Promise(resolve => { lose = resolve; }), owner.hooks); - await Bun.sleep(150); - expect(requests.seen.requests, "IDENTITY_REQUEST_OUTSTANDING").toBe(0); - lose(1); - const refusal = await exit.catch((error: unknown) => error); - expect((refusal as WorkerHostError).requirement).toBe("worker_identity_supervisor_lost (1)"); - await Bun.sleep(200); - expect(requests.seen.requests).toBe(1); - // The late answer neither settles again nor releases the broker a second time. - expect(owner.state()).toEqual({ finished: true, released: 0 }); - } finally { requests.stop(); } + const exit = identityWorkerExit(status, new Promise(resolve => { lose = resolve; }), owner.hooks); + await entered.promise; + expect(requests, "IDENTITY_REQUEST_OUTSTANDING").toBe(0); + lose(1); + const refusal = await exit.catch((error: unknown) => error); + expect((refusal as WorkerHostError).requirement).toBe("worker_identity_supervisor_lost (1)"); + reply.resolve(); + await answered.promise; + expect(requests).toBe(1); + // The late answer neither settles again nor releases the broker a second time. + expect(owner.state()).toEqual({ finished: true, released: 0 }); }); test("a separate-UID maintenance launch waits for its helper worker with the event loop free", async () => { @@ -591,6 +609,13 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke }; } +/** + * Kept real time. With 3000 ms it is a failure maximum. With 50 ms it is a + * negative race: the control stand-in answers a broker close only after 100 ms, + * in a separate process, so a non-final close that waited for the last + * handle's close would still be pending. No in-process event precedes that + * answer. + */ const settledWithin = (promise: Promise, ms: number) => Promise.race([promise.then(() => "settled", () => "settled"), Bun.sleep(ms).then(() => "pending")]); 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 fec4221ed0..1e3e1c7aed 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 2e395693d4..d246a67cdc 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -105,13 +105,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(); @@ -344,11 +348,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/application-index-timing.test.ts b/packages/ui-server/tests/application-index-timing.test.ts index d851d26676..59724270dd 100644 --- a/packages/ui-server/tests/application-index-timing.test.ts +++ b/packages/ui-server/tests/application-index-timing.test.ts @@ -21,9 +21,15 @@ const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floo test("twenty writes return without waiting for the index; one targeted update covers them all", async () => { await inProcessPlanner.index(root, undefined); const runs: (readonly string[] | undefined)[] = []; - // Each update is slow, as a maintenance worker over a large brain is. + // Each update is slow, as a maintenance worker over a large brain is: it is held until the + // writes are measured, and on a route where a write waits for it, each update takes 1500 ms. + let measured!: () => void; + const writesMeasured = new Promise(resolve => { measured = resolve; }); const planner: ApplicationPlanner = { planAdd: inProcessPlanner.planAdd, async index(target, signal, paths) { - runs.push(paths); await Bun.sleep(1500); return inProcessPlanner.index(target, signal, paths); + runs.push(paths); + let slow: ReturnType | undefined; + try { await Promise.race([writesMeasured, new Promise(resolve => { slow = setTimeout(resolve, 1500); })]); } finally { clearTimeout(slow); } + return inProcessPlanner.index(target, signal, paths); } }; const receipts: BrainApplicationResult[] = []; const apply = createBrainApplication({ root, planner, principalId: "odysseus", turnId: "turn-scheria", signal: new AbortController().signal, @@ -44,6 +50,7 @@ test("twenty writes return without waiting for the index; one targeted update co expect(result).toMatchObject({ ok: true, indexed: false, indexStatus: "pending" }); expect(result).not.toHaveProperty("outcome.indexError"); } + measured(); await (apply as unknown as { indexBatch: { barrier(): Promise } }).indexBatch.barrier(); expect(runs).toEqual([paths]); const core = await import("@schlessera/brain/internal"); diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts index f9d005b0c6..c27d3cf644 100644 --- a/packages/ui-server/tests/chat-lifecycle.test.ts +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -2,7 +2,7 @@ * Chat identity retirement (#3228) on an actual file-backed SQLite write * worker. Synthetic Odysseus fixtures only: no provider, backend or network. */ -import { afterEach, expect, test } from "bun:test"; +import { afterEach, expect, spyOn, test } from "bun:test"; import { Database } from "bun:sqlite"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -19,7 +19,28 @@ import * as controls from "./helpers/dialogue-test-writes.js"; const MARKER = "Odysseus hid the oar under the olive root"; const CONTROL = "Penelope kept the loom unfinished"; const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +const restores: (() => void)[] = []; +afterEach(() => { + for (const restore of restores.splice(0)) restore(); + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +/** + * Resolves once a write procedure has been posted to the real write worker, + * where it queues behind any hold: the step after it is ordered behind it. + */ +function posted(name: string): Promise { + const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "postMessage")!, send = Worker.prototype.postMessage; + let seen!: () => void; + const sent = new Promise(resolve => { seen = resolve; }); + const spy = spyOn(Worker.prototype, "postMessage").mockImplementation(function (this: Worker, ...args: [message: unknown, options?: StructuredSerializeOptions | Transferable[]]) { + const message = args[0] as { kind?: string; name?: string }; + if (message.kind === "call" && message.name === name) seen(); + return Reflect.apply(send, this, args); + }); + restores.push(() => { spy.mockRestore(); Object.defineProperty(Worker.prototype, "postMessage", descriptor); }); + return sent; +} function voice(conversationId: string, sequence: number, text: string): Extract { return { kind: "voice", conversationId, epoch: 1, providerId: "gemini-live", event: { @@ -118,8 +139,10 @@ test("revocation while admission waits on the writer refuses at commit", async ( const f = await fixture(); try { await f.host.hold(); + const submitted = posted("retireChat"); const pending = f.host.catalog.retireChat!(request(f.owner), idle); - await Bun.sleep(20); + // Admission passed the preflight and the retirement waits on the held writer. + await submitted; // Another connection, as a revocation request on another worker would be: // the held app writer cannot take its turn until the release. const other = new Database(f.path); other.exec("PRAGMA busy_timeout = 5000"); @@ -138,8 +161,9 @@ test("retirement fences every identity, refuses late writes and keeps unrelated const cost = db.query("SELECT id,total_cost_usd,num_turns FROM sessions ORDER BY id").all(); // Late callbacks already in flight when the retirement is submitted. await f.host.hold(); + const submitted = posted("retireChat"); const retired = catalog.retireChat!(request(f.owner), idle); - await Bun.sleep(20); + await submitted; const late = [ catalog.dialogueAppend!({ ownerId: owner.id, principalId: f.owner, generation: owner.generation, identity: "voice:ithaca:1", evidence: voice("ithaca", 1, MARKER) }), catalog.saveConversationTask!(f.owner, { ...task("ithaca", 1, "voyage"), delivery: "unknown" }, "replaced facts"), @@ -239,8 +263,9 @@ for (const order of ["adoption-first", "retirement-first"] as const) test(`racin bound = settle(catalog.dialogueBind!("ogygia", f.owner, "voyage")); retired = catalog.retireChat!(request(f.owner), idle); } else { + const submitted = posted("retireChat"); retired = catalog.retireChat!(request(f.owner), idle); - await Bun.sleep(20); + await submitted; bound = settle(catalog.dialogueBind!("ogygia", f.owner, "voyage")); } f.host.release(); 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/fixtures/write-worker-probe.ts b/packages/ui-server/tests/fixtures/write-worker-probe.ts index 42d05a1c90..64ed806537 100644 --- a/packages/ui-server/tests/fixtures/write-worker-probe.ts +++ b/packages/ui-server/tests/fixtures/write-worker-probe.ts @@ -3,21 +3,24 @@ import type { Database } from "bun:sqlite"; export const url = import.meta.url; +/** Marks a held procedure as entered: the test awaits `Atomics.waitAsync` on it. */ +function enter(entered?: Int32Array) { if (entered) { Atomics.store(entered, 0, 1); Atomics.notify(entered, 0); } } + export function setup(db: Database, options: { table: string }) { db.exec(`CREATE TABLE IF NOT EXISTS ${options.table} (n INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT NOT NULL)`); const insert = (label: string) => db.query(`INSERT INTO ${options.table} (label) VALUES (?)`).run(label).changes; return { log(label: string) { return db.transaction(() => insert(label)).immediate(); }, - /** Holds the commit for `ms`, as a slow fsync would. */ - slow(label: string, ms: number) { - return db.transaction(() => { insert(label); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); return 1; }).immediate(); + /** Holds the commit for `ms`, as a slow fsync would; `entered` is set once it holds the write transaction. */ + slow(label: string, ms: number, entered?: Int32Array) { + return db.transaction(() => { insert(label); enter(entered); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); return 1; }).immediate(); }, lowered(label: string) { db.exec("PRAGMA synchronous = NORMAL"); return db.transaction(() => insert(label)).immediate(); }, loweredAutocommit(label: string) { db.exec("PRAGMA synchronous = NORMAL"); return insert(label); }, /** Counts the log twice across a held gap, outside any transaction. */ - gap(ms: number) { + gap(ms: number, entered?: Int32Array) { const count = () => (db.query(`SELECT count(*) AS n FROM ${options.table}`).get() as { n: number }).n; - const before = count(); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); return [before, count()]; + const before = count(); enter(entered); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); return [before, count()]; }, level() { return (db.query("PRAGMA synchronous").get() as { synchronous: number }).synchronous; }, levelOf(schema: string) { return (db.query(`PRAGMA "${schema}".synchronous`).get() as { synchronous: number }).synchronous; }, diff --git a/packages/ui-server/tests/helpers/contextual-refusals.ts b/packages/ui-server/tests/helpers/contextual-refusals.ts index 6b30922ad3..e400270d55 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-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index 0b28ac481d..7e3d278eea 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -284,10 +284,13 @@ test("settling a failed release never overrides a newer release of the same iden records.set(id, value); return value as never; }; f.native.client.listPoolRecovery = async () => ({ records: [...records.values()] as never, next: null }); - let attempts = 0, commit: () => void = () => {}; + let attempts = 0, commit: () => void = () => {}, newer: () => void = () => {}; const committed = new Promise(resolve => { commit = resolve; }); + const newerStarted = new Promise(resolve => { newer = resolve; }); f.native.client.poolRelease = async id => { - if (++attempts === 1) { await Bun.sleep(20); throw new Error("the first reply was lost"); } + // The first reply is lost only once the newer release of the same identity has reached the pool. + if (++attempts === 1) { await newerStarted; throw new Error("the first reply was lost"); } + newer(); await committed; records.delete(id); return { id, purpose: "source", from: null, allowanceBytes: 4096, state: "reclaimed", root: null, path: null, ownerBytes: 0, reason: null, view: null, access: null } as never; diff --git a/packages/ui-server/tests/native-journal-observer.test.ts b/packages/ui-server/tests/native-journal-observer.test.ts index db11201e8a..eba4c16a7e 100644 --- a/packages/ui-server/tests/native-journal-observer.test.ts +++ b/packages/ui-server/tests/native-journal-observer.test.ts @@ -288,7 +288,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-cache.test.ts b/packages/ui-server/tests/private-index-cache.test.ts index 302f947cd1..d2113c40eb 100644 --- a/packages/ui-server/tests/private-index-cache.test.ts +++ b/packages/ui-server/tests/private-index-cache.test.ts @@ -479,15 +479,20 @@ test("the cache identity covers the brain, policy, masks, recipient, mask paths for (const [what, change] of changes) expect(privateIndexCacheKey({ ...identity, ...change }), `KEY_COVERS_${what.toUpperCase().replaceAll(" ", "_")}`).not.toBe(key); }); -/** A cache over a tiny copied brain whose builds write one file; `gate` holds every delta. */ +/** A cache over a tiny copied brain whose builds write one file; `gate` holds + * every delta. `entered` resolves when a delta reaches the gate and `running` + * when a held run starts, so a test waits for that point instead of a + * fixed interval. */ function bench(options: { entries?: number; idleMs?: number; report?: (message: string) => void } = {}) { privateTmp(); const root = mkdtempSync(join(tmpdir(), "odysseus-private-index-bound-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); mkdirSync(join(root, "brain/notes"), { recursive: true }); writeFileSync(join(root, "brain/notes/eagle.md"), "x"); - const state = { gate: Promise.resolve(), holdRuns: false, acquired: 0, failAcquire: false }; + const state = { gate: Promise.resolve(), holdRuns: false, acquired: 0, failAcquire: false, + entered: () => {}, running: () => {} }; const cache = createPrivateIndexCache({ report: options.report ?? (() => {}), entries: options.entries ?? 2, idleMs: options.idleMs ?? 200, differ: async (from, to, signal) => { // A held delta still ends when the cache closes, as the native one does. + state.entered(); await Promise.race([state.gate, new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }))]); return fixtureDiffer(from, to, signal); } }); @@ -497,7 +502,7 @@ function bench(options: { entries?: number; idleMs?: number; report?: (message: build: async () => { writeFileSync(join(index, "brain.db"), "rebuilt"); return { ok: true as const }; }, update: async () => { // A held run ends only when its signal does, as a killed worker would. - if (state.holdRuns) { await new Promise(resolve => signal.addEventListener("abort", resolve, { once: true })); return { ok: false as const, detail: "killed" }; } + if (state.holdRuns) { state.running(); await new Promise(resolve => signal.addEventListener("abort", resolve, { once: true })); return { ok: false as const, detail: "killed" }; } appendFileSync(join(index, "brain.db"), "+added"); return { ok: true as const, stdout }; } }); const prepare = async (policyHash: string, input: { partial?: boolean; maskPaths?: string[]; stdout?: string } = {}) => { @@ -520,53 +525,76 @@ function bench(options: { entries?: number; idleMs?: number; report?: (message: return { root, cache, views, prepare, live, bases, state, advance }; } +/** Resolves the first time the bench reaches `point`. */ +function reached(b: ReturnType, point: "entered" | "running"): Promise { + return new Promise(resolve => { b.state[point] = resolve; }); +} + test("the cache keeps a bounded number of bases and releases their checkpoints on eviction, idle expiry and close", async () => { - const { cache, views, prepare, live, bases } = bench(); - expect((await prepare("one")).kind).toBe("built"); - expect((await prepare("two")).kind).toBe("built"); - expect(views.map(live), "EACH_BASE_RETAINS_ITS_CHECKPOINT").toEqual([true, true]); - expect((await prepare("three")).kind).toBe("built"); - expect(views.map(live), "THE_LEAST_RECENT_BASE_IS_EVICTED").toEqual([false, true, true]); - expect((await prepare("three")).kind, "A_KEPT_BASE_IS_REUSED").toBe("reused"); - expect(views.map(live), "REUSE_MOVES_THE_BASE_TO_THE_NEWER_CHECKPOINT").toEqual([false, true, false, true]); - await Bun.sleep(400); - expect(views.map(live), "IDLE_BASES_RELEASE_THEIR_CHECKPOINTS").toEqual([false, false, false, false]); - expect((await prepare("two")).kind, "AN_EXPIRED_BASE_REBUILDS").toBe("built"); - await cache.close(); - expect(views.map(live), "CLOSE_RELEASES_EVERY_CHECKPOINT").toEqual([false, false, false, false, false]); - expect(bases(), "CLOSE_REMOVES_EVERY_BASE").toEqual([]); + // The cache's idle timers run on a test clock; checkpoints and files stay native. + const clock = privateIndexClock(); + try { + const { cache, views, prepare, live, bases } = bench(); + expect((await prepare("one")).kind).toBe("built"); + expect((await prepare("two")).kind).toBe("built"); + expect(views.map(live), "EACH_BASE_RETAINS_ITS_CHECKPOINT").toEqual([true, true]); + expect((await prepare("three")).kind).toBe("built"); + expect(views.map(live), "THE_LEAST_RECENT_BASE_IS_EVICTED").toEqual([false, true, true]); + expect((await prepare("three")).kind, "A_KEPT_BASE_IS_REUSED").toBe("reused"); + expect(views.map(live), "REUSE_MOVES_THE_BASE_TO_THE_NEWER_CHECKPOINT").toEqual([false, true, false, true]); + expect(clock.deadlines().length, "IDLE_TIMERS_REGISTERED").toBe(2); + await clock.advance(400); + expect(views.map(live), "IDLE_BASES_RELEASE_THEIR_CHECKPOINTS").toEqual([false, false, false, false]); + expect((await prepare("two")).kind, "AN_EXPIRED_BASE_REBUILDS").toBe("built"); + await cache.close(); + expect(views.map(live), "CLOSE_RELEASES_EVERY_CHECKPOINT").toEqual([false, false, false, false, false]); + expect(bases(), "CLOSE_REMOVES_EVERY_BASE").toEqual([]); + } finally { clock.restore(); } }); test("concurrent keys keep the bound, and a base a turn is reconciling is neither evicted nor expired under it", async () => { - const b = bench({ entries: 1, idleMs: 150 }); - expect((await b.prepare("one")).kind).toBe("built"); - let release!: () => void; - b.state.gate = new Promise(resolve => { release = resolve; }); - const slow = b.prepare("one"); - // Two other keys build and seal while "one" is being reconciled, and its - // idle time runs out. - expect((await Promise.all([b.prepare("two"), b.prepare("three")])).map(outcome => outcome.kind)).toEqual(["built", "built"]); - await Bun.sleep(300); - expect(b.live(b.views[0]!), "AN_ACTIVE_BASE_IS_NEITHER_EVICTED_NOR_EXPIRED").toBe(true); - release(); - expect((await slow).kind, "THE_ACTIVE_BASE_STAYS_USABLE").toBe("reused"); - expect(b.bases().length, "THE_BOUND_HOLDS_ONCE_TURNS_FINISH").toBe(1); + const clock = privateIndexClock(); + try { + const b = bench({ entries: 1, idleMs: 150 }); + expect((await b.prepare("one")).kind).toBe("built"); + let release!: () => void; + b.state.gate = new Promise(resolve => { release = resolve; }); + const slow = b.prepare("one"); + // Two other keys build and seal while "one" is being reconciled, and its + // idle time runs out. + expect((await Promise.all([b.prepare("two"), b.prepare("three")])).map(outcome => outcome.kind)).toEqual(["built", "built"]); + // Deliver the active base's own idle timer, not just some time passing. + const expiry = clock.now + 151; + expect(clock.deadlines(), "THE_ACTIVE_BASES_IDLE_TIMER_IS_ARMED").toContain(expiry); + await clock.advance(300); + expect(clock.deadlines(), "EVERY_IDLE_TIMER_FIRED").toEqual([]); + expect(b.live(b.views[0]!), "AN_ACTIVE_BASE_IS_NEITHER_EVICTED_NOR_EXPIRED").toBe(true); + release(); + expect((await slow).kind, "THE_ACTIVE_BASE_STAYS_USABLE").toBe("reused"); + expect(b.bases().length, "THE_BOUND_HOLDS_ONCE_TURNS_FINISH").toBe(1); + } finally { clock.restore(); } }); test("an expiry skipped while a turn reconciles applies once that turn finishes", async () => { - const b = bench({ idleMs: 150 }); - expect((await b.prepare("one")).kind).toBe("built"); - writeFileSync(join(b.root, "brain/notes/chart.txt"), "x"); - let release!: () => void; - b.state.gate = new Promise(resolve => { release = resolve; }); - // This turn rebuilds and gets only a partial index, so it never renews the base. - const slow = b.prepare("one", { partial: true }); - await Bun.sleep(300); - expect(b.live(b.views[0]!), "NOT_EXPIRED_WHILE_ACTIVE").toBe(true); - release(); - expect((await slow).kind).toBe("partial"); - expect(b.live(b.views[0]!), "THE_SKIPPED_EXPIRY_APPLIES_AFTERWARDS").toBe(false); - expect(b.bases(), "NO_BASE_OUTLIVES_ITS_EXPIRY").toEqual([]); + const clock = privateIndexClock(); + try { + const b = bench({ idleMs: 150 }); + expect((await b.prepare("one")).kind).toBe("built"); + const expiry = clock.now + 151; + writeFileSync(join(b.root, "brain/notes/chart.txt"), "x"); + let release!: () => void; + b.state.gate = new Promise(resolve => { release = resolve; }); + // This turn rebuilds and gets only a partial index, so it never renews the base. + const slow = b.prepare("one", { partial: true }); + expect(clock.deadlines(), "THE_IDLE_TIMER_IS_ARMED").toEqual([expiry]); + await clock.advance(300); + expect(clock.deadlines(), "THE_IDLE_TIMER_FIRED_DURING_THE_TURN").toEqual([]); + expect(b.live(b.views[0]!), "NOT_EXPIRED_WHILE_ACTIVE").toBe(true); + release(); + expect((await slow).kind).toBe("partial"); + expect(b.live(b.views[0]!), "THE_SKIPPED_EXPIRY_APPLIES_AFTERWARDS").toBe(false); + expect(b.bases(), "NO_BASE_OUTLIVES_ITS_EXPIRY").toEqual([]); + } finally { clock.restore(); } }); test("bases are kept only where no worker can see them, and a crashed server's are swept", async () => { @@ -605,10 +633,12 @@ test("a turn arriving during an advance waits for it and reuses what it made", a writeFileSync(join(b.root, "brain/notes/scheria.md"), "x"); let release!: () => void; b.state.gate = new Promise(resolve => { release = resolve; }); + const entered = reached(b, "entered"); const advancing = b.advance(); - await Bun.sleep(50); + // The advance holds the base's queue once its delta is running. + await entered; + // The turn queues behind it synchronously, before anything is released. const arriving = b.prepare("one"); - await Bun.sleep(100); release(); expect((await advancing).map(result => result.kind), "THE_ADVANCE_UPDATES").toEqual(["updated"]); expect((await arriving).kind, "THE_TURN_REUSES_THE_ADVANCED_BASE").toBe("reused"); @@ -623,8 +653,9 @@ test("an advance whose update rewrote rows keeps the old base, and close stops a expect(readFileSync(join(tmpdir(), b.bases()[0]!, "brain.db"), "utf8"), "THE_OLD_BASE_STAYS").toBe("one"); expect(b.live(b.views[0]!), "STILL_BOUND_TO_ITS_OWN_CHECKPOINT").toBe(true); b.state.gate = new Promise(() => {}); + const entered = reached(b, "entered"); const stuck = b.advance(); - await Bun.sleep(50); + await entered; await b.cache.close(); expect(await stuck, "CLOSE_ENDS_THE_ADVANCE").toMatchObject([{ kind: "kept", reason: "closing" }]); expect(b.views.map(b.live), "CLOSE_RELEASES_EVERY_CHECKPOINT").toEqual(b.views.map(() => false)); @@ -688,8 +719,9 @@ test("close stops an advance whose build is running", async () => { expect((await b.prepare("one")).kind).toBe("built"); writeFileSync(join(b.root, "brain/notes/scheria.md"), "x"); b.state.holdRuns = true; + const started = reached(b, "running"); const running = b.advance(); - await Bun.sleep(100); + await started; await b.cache.close(); expect(await running, "THE_RUN_IS_STOPPED").toMatchObject([{ kind: "kept", reason: "the incremental index failed: killed" }]); expect(b.bases(), "NOTHING_IS_KEPT").toEqual([]); 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 0cf4d196ae..7375e8644c 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 df727fad84..3c72fbb182 100644 --- a/packages/ui-server/tests/reference-source.test.ts +++ b/packages/ui-server/tests/reference-source.test.ts @@ -23,13 +23,23 @@ const grant = (principalId: string, by: string, prefix = "https://github.com/ody createReferenceGrant(db, { brain: BRAIN, principalId, repositoryPrefix: prefix, credential, createdBy: by, now: Date.now() }); function deferred() { let resolve!: () => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; } +/** + * Every collaborator here is in memory: the scripted transport, the pool double and inline + * reference writes. One macrotask turn therefore runs all pending work up to its next held + * barrier, and a step that has not happened after it is waiting on that barrier. + */ +const drain = () => new Promise(resolve => setImmediate(resolve)); +/** Turn the event loop until `condition` holds; the caller's assertion reports a miss. */ +async function until(condition: () => boolean, turns = 100) { for (let turn = 0; turn < turns && !condition(); turn++) await drain(); } /** Scripted repositories: anonymous access only to public ones; the private one needs an accepted fixture token. */ function scripted() { const repos = new Map([[PUBLIC, { private: false, tip: "1".repeat(40) }], [PRIVATE, { private: true, tip: "2".repeat(40) }], ["https://github.com/odysseus/argo", { private: false, tip: "3".repeat(40) }], ["https://github.com/odysseus/scylla", { private: false, tip: "4".repeat(40) }]]); const state = { resolves: [] as { repository: string; token: string | null }[], fetches: [] as { repository: string; token: string | null }[], active: 0, maxActive: 0, - gate: null as null | ReturnType, unavailable: false, fetchFailure: null as null | Error, checkoutFailure: null as null | Error, settleDelayMs: 0, + gate: null as null | ReturnType, unavailable: false, fetchFailure: null as null | Error, checkoutFailure: null as null | Error, + /** Holds a fetch's teardown after it stopped, the way a real worker takes time to exit after an abort. */ + settle: null as null | ReturnType, events: [] as string[], onResolve: null as null | ((token: string | null) => void), tokens: new Set([TOKEN]), /** Holds one fetch until the returned promise settles, so concurrent operations can be released one at a time. */ hold: null as null | ((call: { repository: string; token: string | null }) => Promise | undefined) }; @@ -55,8 +65,7 @@ function scripted() { writeFileSync(join(target, "README.md"), `${repository.canonical}@${repo.tip}\n`); return { commit: repo.tip }; } finally { - // A real worker needs time to tear down after an abort. - if (state.settleDelayMs) await Bun.sleep(state.settleDelayMs); + if (state.settle) await state.settle.promise; state.active--; state.events.push("fetch-settled"); } }, @@ -121,14 +130,15 @@ describe("authority and sharing domains", () => { const mine = sources.request({ principalId: telemachus.id, repository: PRIVATE, revision: "main" }); const theirs = sources.request({ principalId: eurycleia.id, repository: PRIVATE, revision: "main" }).finally(() => { theirsSettled = true; }); try { - await Bun.sleep(10); + await until(() => state.fetches.filter(call => call.repository === PRIVATE).length === 2); // The first fetch is still in flight when the second principal asks: both run, each under its own principal's credential. expect(state.fetches.filter(call => call.repository === PRIVATE).map(call => call.token).sort(), "REFERENCE_SOURCE_PRIVATE_CONCURRENT_NOT_JOINED") .toEqual([SECOND, TOKEN].sort()); expect(sources.activity()).toEqual({ active: 2, waiting: 0 }); gates.get(TOKEN)!.resolve(); const first = await mine; - await Bun.sleep(10); + // Anything settled by the first domain's operation has settled after this turn. + await drain(); expect(theirsSettled, "REFERENCE_SOURCE_PRIVATE_NOT_SETTLED_BY_OTHER_DOMAIN").toBe(false); gates.get(SECOND)!.resolve(); const second = await theirs; @@ -242,7 +252,7 @@ describe("admission, cancellation and eviction", () => { const penelope = owner(), telemachus = agent(penelope.id); state.gate = deferred(); const requests = [penelope.id, telemachus.id, penelope.id, telemachus.id].map(principalId => sources.request({ principalId, repository: PUBLIC, revision: "main" })); - await Bun.sleep(10); + await until(() => state.fetches.length > 0); state.gate.resolve(); const leases = await Promise.all(requests); expect(state.fetches, "REFERENCE_SOURCE_SINGLE_FLIGHT").toHaveLength(1); @@ -256,7 +266,7 @@ describe("admission, cancellation and eviction", () => { const requests = [PUBLIC, "https://github.com/odysseus/argo", "https://github.com/odysseus/scylla"] .map(repository => sources.request({ principalId: penelope.id, repository, revision: "main" })); try { - await Bun.sleep(10); + await until(() => state.fetches.length >= 2); expect(sources.activity(), "REFERENCE_SOURCE_TWO_OPERATIONS").toEqual({ active: 2, waiting: 1 }); expect(state.maxActive).toBe(2); } finally { state.gate.resolve(); await Promise.allSettled(requests); } @@ -276,10 +286,10 @@ describe("admission, cancellation and eviction", () => { let stalledSettled = false; const stalled = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" }).finally(() => { stalledSettled = true; }); // The stalled acquisition is admitted first, so it is the oldest active operation. - await Bun.sleep(5); + await until(() => state.fetches.some(call => call.repository === PUBLIC)); const moving = sources.request({ principalId: penelope.id, repository: ARGO, revision: "main" }); try { - await Bun.sleep(10); + await until(() => state.fetches.some(call => call.repository === ARGO)); expect(sources.activity()).toEqual({ active: 2, waiting: 0 }); gates.get(ARGO)!.resolve(); const lease = await Promise.race([moving, Bun.sleep(1_000).then(() => null)]); @@ -303,8 +313,9 @@ describe("admission, cancellation and eviction", () => { state.gate = deferred(); const running = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" }); const waiting = sources.request({ principalId: penelope.id, repository: "https://github.com/odysseus/argo", revision: "main" }); - await Bun.sleep(10); + 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]); @@ -314,13 +325,17 @@ describe("admission, cancellation and eviction", () => { test("cancellation releases staging only after the transport worker stopped, and never publishes", async () => { const { sources, state, pool } = service(); const penelope = owner(); - state.gate = deferred(); state.settleDelayMs = 30; + state.gate = deferred(); state.settle = deferred(); const controller = new AbortController(); const request = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main", signal: controller.signal }); - await Bun.sleep(10); + await until(() => state.fetches.length === 1); controller.abort(); - try { await expect(request).rejects.toMatchObject({ code: "cancelled" }); } - finally { state.gate.resolve(); await sources.close(); } + try { + await expect(request).rejects.toMatchObject({ code: "cancelled" }); + // The aborted fetch is still tearing down: everything else has run, and the reservation is still held. + await drain(); + expect(state.events, "REFERENCE_SOURCE_RESERVATION_HELD_WHILE_WORKER_TEARS_DOWN").toEqual([]); + } finally { state.settle.resolve(); state.gate.resolve(); await sources.close(); } const settled = state.events.indexOf("fetch-settled"), released = state.events.findIndex(event => event.startsWith("release:")); expect(settled, "REFERENCE_SOURCE_RESERVATION_HELD_UNTIL_WORKER_STOPS").toBeGreaterThanOrEqual(0); expect(released, "REFERENCE_SOURCE_RESERVATION_HELD_UNTIL_WORKER_STOPS").toBeGreaterThan(settled); @@ -333,9 +348,10 @@ describe("admission, cancellation and eviction", () => { const record = grant(telemachus.id, penelope.id); state.gate = deferred(); const request = sources.request({ principalId: telemachus.id, repository: PRIVATE, revision: "main" }); - await Bun.sleep(10); + 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"); @@ -376,7 +392,7 @@ describe("admission, cancellation and eviction", () => { (await sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" })).release(); expect([...pool.records.values()].filter(record => record.state === "sealed"), "REFERENCE_SOURCE_READER_DOES_NOT_BLOCK_REFRESH").toHaveLength(2); reader.release(); - await Bun.sleep(5); + await until(() => [...pool.records.values()].filter(record => record.state === "sealed").length === 1); expect([...pool.records.values()].filter(record => record.state === "sealed"), "REFERENCE_SOURCE_SUPERSEDED_RELEASED_AFTER_READERS").toHaveLength(1); }); @@ -415,7 +431,7 @@ describe("review regressions", () => { expect(readdirSync(reader.viewPath), "REFERENCE_SOURCE_WITHDRAWN_IDENTITY_GONE").not.toContain(root); expect(pool.records.get(root)?.state, "REFERENCE_SOURCE_LEASED_STORAGE_KEPT").toBe("sealed"); reader.release(); - await Bun.sleep(5); + await until(() => pool.records.get(root)?.state === "reclaimed"); expect(pool.records.get(root)?.state).toBe("reclaimed"); }); @@ -428,9 +444,9 @@ describe("review regressions", () => { // The private refresh waits for admission behind another operation; its principal is revoked meanwhile. state.gate = deferred(); const holding = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" }); - await Bun.sleep(10); + await until(() => state.fetches.length > 0); const queued = sources.request({ principalId: telemachus.id, repository: PRIVATE, revision: "main" }); - await Bun.sleep(10); + await until(() => sources.activity().waiting === 1); expect(sources.activity()).toEqual({ active: 1, waiting: 1 }); revokePrincipal(db, telemachus.id, Date.now()); const credentialed = state.resolves.filter(call => call.repository === PRIVATE && call.token).length; @@ -511,9 +527,10 @@ describe("review regressions", () => { let pausing = true; pool.poolUnpublish = async (...args) => { if (pausing) { pausing = false; await paused.promise; } return unpublish(...args); }; const third = sources.request({ principalId: penelope.id, repository: "https://github.com/odysseus/scylla", revision: "main" }); - await Bun.sleep(10); + await until(() => !pausing); const raced = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" }); - await Bun.sleep(10); + // The raced request runs as far as it can while the eviction is held inside its unpublish. + await drain(); paused.resolve(); const [victim] = await Promise.allSettled([raced, third]); expect(victim.status === "fulfilled" && existsSync(join(victim.value.viewPath, victim.value.name, "README.md")), "REFERENCE_SOURCE_EVICTION_FENCED").toBe(true); @@ -528,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 e535977792..975e4bbc9a 100644 --- a/packages/ui-server/tests/reference-tools.test.ts +++ b/packages/ui-server/tests/reference-tools.test.ts @@ -141,6 +141,11 @@ describe("shared reference source", () => { /** What the public view holds: names and root identities alike. */ const publicEntries = (views: { public: string } | null) => views ? readdirSync(views.public).sort() : null; +/** + * The transport, the pool double and the reference writes are in memory, so one macrotask + * turn runs all pending work up to its next held barrier. + */ +const drain = () => new Promise(resolve => setImmediate(resolve)); const nameOf = (result: ReferenceToolResult) => ok>(result).source.path!.split("/").at(-1)!; describe("binding a view is a new mount (#2432, option 1)", () => { @@ -239,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(); @@ -330,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(); }); @@ -351,7 +359,8 @@ describe("exposure changes are serialized (#2432 review)", () => { const binding = sources.bindable(telemachus.id); while (!paused) await Bun.sleep(1); const lease = sources.request({ principalId: penelope.id, repository: PUBLIC, revision: "main" }); - await Bun.sleep(5); + // The request runs until it waits behind the held suspension. + await drain(); open(); const views = await binding; const held = await lease; @@ -435,7 +444,8 @@ describe("exposure changes are serialized (#2432 review)", () => { while (!paused) await Bun.sleep(1); let bound = false; const binding = sources.bindable(telemachus.id).then(views => { bound = true; return views; }); - await Bun.sleep(20); + // Everything not held behind the paused publication has run after this turn. + await drain(); expect(bound, "REFERENCE_TOOLS_BIND_WAITS_FOR_INITIAL_PUBLICATION").toBe(false); open(); const held = await acquiring; @@ -478,7 +488,8 @@ describe("exposure changes are serialized (#2432 review)", () => { while (!paused) await Bun.sleep(1); revokeReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, id: issued.id, now: Date.now() }); const revoking = sources.revoke({ grantIds: [issued.id], principalIds: [] }); - await Bun.sleep(5); + // The revocation runs until it waits behind the held restoration. + await drain(); open(); await Promise.allSettled([restoring, revoking]); (await restoring.catch(() => null))?.release(); 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 4bae93a852..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); @@ -243,7 +246,10 @@ for (const mode of ["sync", "async"] as const) test(`sampling retains ${mode} fl const sampling = createStorageSampling(f.db, storage, history, shared, notices, { deliverStorage: async () => 0 }, start); try { sampling.tick(start + 60_000); - await new Promise(resolve => setTimeout(resolve, 20)); + // The tick calls all three synchronously; their rejections and the sampler's + // handlers are microtasks, so they have all settled after one macrotask turn. + expect([flush, sweep, clean].map(spy => spy.mock.calls.length), "SAMPLER_TICK_STARTED_EVERY_FAILING_STEP").toEqual([1, 1, 1]); + await new Promise(resolve => setImmediate(resolve)); const closing = sampling.close(); expect(sampling.close(), "SAMPLER_CONCURRENT_CLOSE_JOINS").toBe(closing); const error = await closing.then(() => undefined, error => error); diff --git a/packages/ui-server/tests/storage-scan-offloop.test.ts b/packages/ui-server/tests/storage-scan-offloop.test.ts index 76eb81efb4..727b38b768 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); @@ -170,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" }); @@ -182,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")); @@ -221,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(); } @@ -269,9 +278,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/turn-egress.test.ts b/packages/ui-server/tests/turn-egress.test.ts index bdcae4f807..aade8af6a8 100644 --- a/packages/ui-server/tests/turn-egress.test.ts +++ b/packages/ui-server/tests/turn-egress.test.ts @@ -323,7 +323,9 @@ test("on the write worker, a connection's bytes wait for its taint commit and a // A slow commit ahead of the taint, as an fsync under load would be. const slow = held.call("slow", "Calypso", 400), started = Date.now(); const first = get(proxy.socketPath, harbour.url.href); - await Bun.sleep(100); + // Until the proxy accepted the connection and submitted its taint, behind the + // slow commit; the bound stays well inside the 400 ms hold, so the taint seen is pending. + for (const end = Date.now() + 300; !writes.taint("turn-harbour", "ithaca") && Date.now() < end;) await Bun.sleep(1); expect(writes.taint("turn-harbour", "ithaca")?.source, "TURN_EGRESS_PENDING_TAINT_IN_FORCE").toBe("egress_connection"); expect(await get(proxy.socketPath, island.url.href), "TURN_EGRESS_PENDING_TAINT_NARROWS_NEW_HOST").toBe(403); expect(await first).toBe(200); diff --git a/packages/ui-server/tests/write-worker.test.ts b/packages/ui-server/tests/write-worker.test.ts index 908184e75b..8d69708a02 100644 --- a/packages/ui-server/tests/write-worker.test.ts +++ b/packages/ui-server/tests/write-worker.test.ts @@ -8,6 +8,12 @@ import { createUiDb } from "../src/db/client.js"; import { openSqliteWriter } from "../src/db/write-worker.js"; import * as probe from "./fixtures/write-worker-probe.js"; +/** A flag a held probe procedure sets once it runs, and a promise for that moment. */ +function entry() { + const flag = new Int32Array(new SharedArrayBuffer(4)); + return { flag, async entered() { const waiting = Atomics.waitAsync(flag, 0, 0); if (waiting.async) await waiting.value; } }; +} + function fixture() { const root = mkdtempSync(join(tmpdir(), "write-worker-odysseus-")), path = join(root, "ui.db"), db = createUiDb(path), writer = openSqliteWriter(db); const log = (table = "odysseus_log") => (db.query(`SELECT label FROM ${table} ORDER BY n`).all() as { label: string }[]).map(row => row.label); @@ -67,8 +73,8 @@ test("an app-connection transaction that reads, then writes, waits for its turn const voyage = f.writer.channel(probe, { table: "odysseus_log" }); await voyage.ready; f.db.exec("CREATE TABLE IF NOT EXISTS odysseus_harbour (port TEXT)"); // The worker commits while the app's transaction sits between its read and its write. - const commit = voyage.call("slow", "Aeolus", 150); - await Bun.sleep(20); + const worker = entry(), commit = voyage.call("slow", "Aeolus", 150, worker.flag); + await worker.entered(); f.db.transaction(() => { f.db.query("SELECT count(*) FROM odysseus_log").get(); Bun.sleepSync(300); @@ -83,8 +89,8 @@ test("app writes, autocommit or not, never land while a worker procedure runs", const f = fixture(); try { const voyage = f.writer.channel(probe, { table: "odysseus_log" }); await voyage.ready; - const gap = voyage.call<[number, number]>("gap", 300); - await Bun.sleep(50); + const worker = entry(), gap = voyage.call<[number, number]>("gap", 300, worker.flag); + await worker.entered(); f.db.query("INSERT INTO odysseus_log (label) VALUES ('Aeolus')").run(); f.db.transaction(() => f.db.query("INSERT INTO odysseus_log (label) VALUES ('Circe')").run())(); f.db.run("INSERT INTO odysseus_log (label) VALUES ('Scylla')"); @@ -148,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 e43884fc5f..238848d132 100644 --- a/packages/ui-server/tests/writer-gate-offloop.test.ts +++ b/packages/ui-server/tests/writer-gate-offloop.test.ts @@ -1,5 +1,5 @@ /** The writer gate's transactions commit on the write worker (#2850). */ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -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. @@ -95,9 +95,16 @@ test("a host writer runs only after its downgrade commits, and not if the bounda const ran = join(f.root, `ran-${method}`); // Once the hold is granted, a slow commit queues ahead of the downgrade // and the boundary turns isolated while it waits. + // The boundary turns isolated as the downgrade is posted to the worker, behind the slow commit. + const send = Worker.prototype.postMessage, descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "postMessage")!; + const posted = spyOn(Worker.prototype, "postMessage").mockImplementation(function (this: Worker, ...args: [message: unknown, options?: StructuredSerializeOptions | Transferable[]]) { + const message = args[0] as { kind?: string; name?: string }; + if (message.kind === "call" && message.name === "unpinned") history = true; + return Reflect.apply(send, this, args); + }); const racing = { ...gate, async acquire(...args: Parameters) { const granted = await gate.acquire(...args); - slow = commits.hold(300); setTimeout(() => { history = true; }, 50); + slow = commits.hold(300); return granted; } }; const boundary = createHostBoundary({ brainPath: f.brain, dbPath: f.path, requireGate: true, gate: () => racing, history: () => history, @@ -105,7 +112,9 @@ test("a host writer runs only after its downgrade commits, and not if the bounda expect(boundary.isolated()).toBe(false); const execution = { argv: [process.execPath, "--config=/dev/null", "--no-env-file", "-e", `require("node:fs").writeFileSync(${JSON.stringify(ran)}, "ran")`], env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "shared" as const, purpose: "Odysseus host writer" }; - await expectRejection(boundary[method](execution), "worker boundary changed", `GATE_HOST_REFUSED_WHEN_BOUNDARY_CHANGED_DURING_ADMISSION_${method}`); + try { await expectRejection(boundary[method](execution), "worker boundary changed", `GATE_HOST_REFUSED_WHEN_BOUNDARY_CHANGED_DURING_ADMISSION_${method}`); } + finally { posted.mockRestore(); Object.defineProperty(Worker.prototype, "postMessage", descriptor); } + expect(history, `GATE_BOUNDARY_TURNED_ISOLATED_AT_THE_DOWNGRADE_${method}`).toBe(true); expect(existsSync(ran), `GATE_HOST_CHILD_NEVER_SPAWNED_${method}`).toBe(false); await slow; await gate.settled(); diff --git a/tests/build-concurrency.test.ts b/tests/build-concurrency.test.ts index 4882b8f604..4890de89a9 100644 --- a/tests/build-concurrency.test.ts +++ b/tests/build-concurrency.test.ts @@ -48,6 +48,7 @@ const args=process.argv.slice(2), directory=dirname(args[args.indexOf("-p")+1]), writeFileSync(join(${JSON.stringify(root)},name+"-started"), String(process.pid)); const compiler=Bun.spawn([process.execPath,${JSON.stringify(join(repo, "node_modules/typescript/bin/tsc"))},...args],{stdout:"inherit",stderr:"inherit"}); const code=await compiler.exited; +writeFileSync(join(${JSON.stringify(root)},name+"-exited"),String(code)); if(name==="beta" && code===0){writeFileSync(join(${JSON.stringify(root)},"peer-ready"),"");while(!existsSync(${JSON.stringify(release)})) await Bun.sleep(10);writeFileSync(join(${JSON.stringify(root)},"peer-drained"),"");} process.exitCode=code; `); @@ -77,6 +78,14 @@ process.exitCode=code; expect(running[0].state, "LIVE_PEER_RECEIPT_REMAINS_PARTIAL").toBe("running"); expect(running[0].packages.find((pkg: {name: string}) => pkg.name === "beta").children[0].code).toBeUndefined(); } + // The window starts only once alpha's compiler has actually failed, so it + // always follows the error it is about. + while (!existsSync(join(root, "alpha-exited")) && !exited && Date.now() < deadline) await Bun.sleep(10); + expect(existsSync(join(root, "alpha-exited")) && readFileSync(join(root, "alpha-exited"), "utf8"), "FAILING_COMPILER_EXITED_BEFORE_WINDOW").toBe("2"); + // Kept real time: a negative observation. A build that stopped waiting for + // its live peer would report alpha's failure and exit as a process. Correct + // code never exits here, so nothing marks the moment; 300 ms is the window + // in which that exit would be observed. await Bun.sleep(300); expect(exited, "PARALLEL_BUILD_WAITS_LIVE_COMPILER_PEER_AFTER_ERROR").toBe(false); writeFileSync(release, ""); @@ -132,11 +141,28 @@ async function successfulBuild(storageFailure?: StorageFailure) { } mkdirSync(join(root, "node_modules/.bin"), { recursive: true }); const wrapper = join(root, "node_modules/.bin/tsc"); + // The optional dependency holds until a peer has finished and its slot has + // been refilled. Correct order refills it with the other peer; a consumer + // started there instead compiles, and fails, before the dependency's output + // exists. Both peers are ready from the start, so with two jobs a correct + // order never waits on the consumer. writeFileSync(wrapper, `#!${process.execPath} -const args=process.argv.slice(2); -if(args.some(arg=>arg.includes("/z-dependency/"))) await Bun.sleep(500); +import { existsSync, writeFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +const args=process.argv.slice(2), name=basename(dirname(args[args.indexOf("-p")+1])); +const marker=(package_,state)=>join(${JSON.stringify(root)},package_+"-"+state); +writeFileSync(marker(name,"started"),""); +if(name==="z-dependency"){ + const peers=["b-peer","c-peer"]; + // Bounded by the owning test process: once it is gone, this hold ends. + while(!(peers.some(peer=>existsSync(marker(peer,"done"))) && (peers.every(peer=>existsSync(marker(peer,"started"))) || existsSync(marker("a-consumer","done"))))){ + if(!existsSync("/proc/${process.pid}")){console.error("NO_PEER_SLOT_REFILLED_BEFORE_THE_DEPENDENCY");process.exit(3);} + await Bun.sleep(5); + } +} const compiler=Bun.spawn([process.execPath,${JSON.stringify(join(repo, "node_modules/typescript/bin/tsc"))},...args],{stdout:"inherit",stderr:"inherit"}); process.exitCode=await compiler.exited; +writeFileSync(marker(name,"done"),String(process.exitCode)); `); chmodSync(wrapper, 0o755); for (const name of ["a-consumer", "b-peer", "c-peer", "z-dependency"]) { diff --git a/tests/helpers/planning-observer.ts b/tests/helpers/planning-observer.ts index 54ad8a7acc..09d39c4828 100644 --- a/tests/helpers/planning-observer.ts +++ b/tests/helpers/planning-observer.ts @@ -71,9 +71,16 @@ export async function observePlanning(root: string, label: string, call: () = let sampler: Worker | undefined; try { sampler = new Worker(new URL("./planning-sampler.ts", import.meta.url), { workerData: { mainTid: process.pid, ...PLANNING_OBSERVER_LIMITS } }); - // Let the sampler take its first reading before the call blocks this thread. - await new Promise(resolve => setTimeout(resolve, PLANNING_OBSERVER_LIMITS.intervalMs)); - } catch (error) { incomplete.push(`sampler did not start: ${String(error)}`); sampler = undefined; } + // The sampler reports its first reading before the call blocks this thread. + const started = sampler; + let timer: ReturnType | undefined; + try { + await new Promise((resolve, reject) => { + started.once("message", () => resolve()); started.once("error", reject); + timer = setTimeout(() => reject(new Error(`no first reading within ${PLANNING_OBSERVER_LIMITS.stopMs} ms`)), PLANNING_OBSERVER_LIMITS.stopMs); + }); + } finally { clearTimeout(timer); } + } catch (error) { incomplete.push(`sampler did not start: ${String(error)}`); void sampler?.terminate(); sampler = undefined; } const before = { at: performance.now(), cpu: process.cpuUsage(), children: childrenCpuMs(), main: mainSchedstat(), pressure: pressureUs(), load: loadAverage() }; let outcome: PlanningRecord["outcome"] = "returned"; let result: T | undefined; diff --git a/tests/helpers/planning-sampler.ts b/tests/helpers/planning-sampler.ts index 0150c52a4f..3de8e66536 100644 --- a/tests/helpers/planning-sampler.ts +++ b/tests/helpers/planning-sampler.ts @@ -51,6 +51,8 @@ const sample = () => { }; sample(); const timer = setInterval(sample, intervalMs); +// The first reading is taken: the observer may now block its thread. +parentPort!.postMessage("ready"); parentPort!.once("message", () => { clearInterval(timer); diff --git a/tests/test-invocation-lifetime.test.ts b/tests/test-invocation-lifetime.test.ts index ccbfff855c..cca5d4d0e8 100644 --- a/tests/test-invocation-lifetime.test.ts +++ b/tests/test-invocation-lifetime.test.ts @@ -211,6 +211,7 @@ try { const ready=Date.now()+10000;while((!existsSync("tmp/orphan")||!output.includes(${JSON.stringify(phase === "build" ? '"event":"build-exit"' : "TEST_LEADER_EXIT")}))&&Date.now()