Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
fa2eacc
test(ui-server): release the boot writer once the turn's wait has see…
schlessera Nov 8, 2026
7cdc37c
test(ui-react): open the unsupported-marks window after both lookups …
schlessera Nov 8, 2026
06acb30
test(ui-react): await the attach tip's transitions instead of 300 ms …
schlessera Nov 8, 2026
5ab947e
test(core): open the compute stage once the run logs its signal (#3332)
schlessera Nov 8, 2026
3a4825c
test(core): wait on answered driver visits instead of fixed windows (…
schlessera Nov 8, 2026
3b35cf0
test(core): release the admission race once every racer is ready (#3332)
schlessera Nov 8, 2026
571a8ad
test(core): check the driver keeps a running job after each answered …
schlessera Nov 8, 2026
8477b36
test(ui-server): wait on causal signals instead of fixed windows (#3332)
schlessera Nov 8, 2026
06f9481
test(ui-server): state why the kept real-time waits stay (#3332)
schlessera Nov 8, 2026
8a41175
test(ui-server): run held-admission continuations before the status m…
schlessera Nov 8, 2026
ae8a181
test(ui-server): check the safety hook's contact order where contact …
schlessera Nov 8, 2026
ee8a0ac
test(ui-react): accept the held send instead of a 1.2 s window (#3332)
schlessera Nov 8, 2026
453f1e0
test(ui-react): wait on the foreign preview's scan instead of fixed w…
schlessera Nov 8, 2026
c6eae01
test(ui-react): advance the draft save debounce instead of sleeping 9…
schlessera Nov 8, 2026
56a19af
test(ui-react): run the attachment queue's busy timer on a fake clock…
schlessera Nov 8, 2026
2a54e43
test(ui-sdk): wait for the gated sandbox's death instead of 1.2 s win…
schlessera Nov 8, 2026
876c0b0
test: state why the kept real-time waits stay real (#3332)
schlessera Nov 8, 2026
0980c8e
docs(test-waits): record the second wait re-census and its slices (#3…
schlessera Nov 8, 2026
809cf80
test: bound new readiness waits and order admission by its steps (#3332)
schlessera Nov 8, 2026
688a886
docs(test-waits): pin the second re-census bundle link (#3332)
schlessera Nov 8, 2026
04da313
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
2b6bd3b
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
45667ba
test: queue the second heavy command by construction, not a 0.4 s rac…
schlessera Nov 8, 2026
651483e
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
6233044
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
cbe1c93
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
65b5365
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
8432fab
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
e46e610
Merge remote-tracking branch 'origin/main' into test/3332-final-census
schlessera Nov 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,27 @@ any reclassification and its mutation receipts.
| ui-react `conversation-endpoint`, `conversation-consent` and `conversation.offline.tsx` | No speech block arrives after the drain; consent alone, or a pending opening after Mute, never reopens capture | The first audio frame below the speaking threshold follows every queued speaking block, instead of a 200 ms drain. Frames are handled on delivery and a capture calls `getUserMedia` synchronously, so the consent cases read the open count once epoch 2 is applied, or at once, instead of after 100 ms or 30 ms. |
| Kept, reason in source | ui-react `recording-limits` source starvation; the drains in `dialogue-browser-server` and `contextual-conversation-browser-server` | The starvation is the real-time stimulus. The fixture drains only pace or batch frames: tests poll step replies for every outcome. |
| Reclassified, no change | `hygiene-lifecycle-command` 234 (cancellation-safety release cap); `storage-server-command` 39 (startup failure maximum); `liveness-clock` 53 (the page timer under the controlled clock) | Each is a maximum or the timer under test, and its reason is in source. |
| Claude `worker-event-loop.test.ts` and Pi `worker-stdio-release.test.ts`, a turn abort and a withheld stdio release | A worker survives its turn's abort; a turn stays pending while its last teardown step is withheld | The abort listeners run inside `abort()`, and everything after the withheld release runs in-process, so one macrotask replaces the 300 ms and 100 ms windows. |
| ui-sdk `worker-steps-event-loop.test.ts`, identity polls and a rejected release | A timer fires while an identity poll is outstanding; a rejected release is handled | The awaited status request stays outstanding until the 1 ms ticker has fired, instead of 30 ms. One macrotask lets Bun report an unhandled rejection, instead of 20 ms. |
| Negative windows and stimuli kept, reason in source | Claude `worker-event-loop` broker close; Pi `early-cancel-lifecycle` temp close and `worker-stdio-release` late descriptor close; ui-sdk `identity-broker-qualification.native` pulse spans and `worker-steps-event-loop` blocking hold and `settledWithin`; root `build-concurrency` live-peer window and `test-invocation-lifetime` orphan window | The broker close, the native temp close and process exits have no event outside the turn, and awaiting one would attach the handler whose absence is checked. The pulse file is the only witness that a writer outside the listed PIDs stopped. The blocking hold and the late close are the stimulus. The `build-concurrency` window opens only after the failing compiler has exited. |
| ui-server `private-index.test.ts`, the first type-selector turn after server start | The turn's peer-plan wait admits it once the server-start writer finishes, rather than refusing | The gate worker answers in submission order, so a peer check submitted after the wait's first check marks the point where the wait has seen the writer. The writer is released then, instead of 300 ms after the wait starts, and the wait must settle after the release. |
| ui-react `untrusted-marks-runtime.test.ts`, an unsupported server | No cue, control, unknown note or entry row is drawn | The window starts once the detail and list lookups have been answered with the generic 404, instead of when the toolbar appears. An unsupported server draws nothing, so no element marks the answer as rendered; the 200 ms window stays, with that reason in source. |
| ui-react `conversation-controls.offline.tsx`, the pointer resting on the attach tooltip | The tip stays visible while the pointer is on it | A tip that lost its host's hover runs a 150 ms visibility transition to hidden. The test reads the style, then awaits the tip's running animations, instead of 300 ms. |

The second re-census runs the same expression at `a63e564f02f9b1ab0462bb0ac02dbf8ea6eacee7`. It covers the 66 files that started matching after `3984040f` (128 lines), and the 35 lines added since then to files that already matched. The [bundle](https://github.com/schlessera/brain-kit/tree/e3b6a50630f7dc04322af2ec609af8982a4ec8e1/scripts/measurements/wait-census-3332-2026-11-08) records both lists, the rule-based classification and the reviewed outcome of every row the rules called replaceable or a negative observation.

| Source / assertion | Attributed role and retained proof | Completion control / native boundary |
| --- | --- | --- |
| core `compute-cli.test.ts`, a signal while a job starts | The signal is recorded while the job is still starting, and the run settles cancelled | The test reads the child's stderr until its handler logs the signal, then opens the stage gate, instead of 200 ms. |
| core `compute-ops.test.ts`, the background driver | A running job stays tracked after each visit; `stop()` during a visit ends visiting | A wrapper on `status` counts answered visits. The test checks after each answered visit, and stops right after one, instead of 30–40 ms. The windows after settle and after stop stay, with their reason in source: no event marks that no timer is armed. |
| core `compute-race.test.ts`, racing admissions | Exactly one of six racers is admitted | Each racer prints `ready` before it polls for the barrier; the barrier is written once all six are ready, instead of after 300 ms. The runner's 50 ms ledger gap stays: it is the stimulus that widens a broken lock's window. |
| ui-server `apify-runs`, `attachment-sweep`, `attachment-extract`, `attachment-reads-delivery` | Racing processes hold the ledger; concurrent uploads hold their reservations; cancel reaches a running extract; a read follows the hello | Ready files from each race child, a poll on `attachment_reservations`, a `Bun.spawn` observer (descriptor restored) and a `ping`/`pong` barrier replace 20–300 ms windows. |
| ui-server `compute-host`, `contextual-status`, `relay-recording-settlement`, `safety-ledger`, `session-run-stages`, `ws-turn-budgets` | In-flight calls finish before cancel settles; no provider acceptance before durable admission; a relay waits for its own egress recording; backend contact waits for safety admission; the turn timeout drains; a late response returns with every report submitted | The host's `clock` option, a marker on the same ordered socket after one macrotask, an egress wrapper recording `admit()`, a pending-count poll plus a contact-time check, the controller's `abort` event and the report count at return replace 5–200 ms windows. |
| Kept, reason in source (ui-server) | `contextual-status` after the provider socket closes; `tainted-destination-ask` shared-card and late-contact windows; `policy-observation-pause` 600 ms against a `Date.now()` deadline; the misbehaving extract worker's hold; `journal-idle-maintenance`, `turn-coordinator` and `ws-turn-budgets` maxima | A closed socket or a loopback contact has no later frame to mark it. The pause deadline is read from `Date.now()`, which no clock in the file reaches. The worker hold is the measured input. The maxima are never awaited on success. |
| ui-react `draft-files.test.ts`, `attachment-queue.test.ts` | The draft is saved only after the 800 ms debounce; the queue asks again only after its busy retry | Fake timers advance the debounce (799 ms, then 1 ms) and the 2 s busy retry, instead of 900 ms sleeps and a real 2 s retry. |
| ui-react `composer-files.offline.tsx`, `hygiene-media.layout.tsx` and its fixture | A held send is sent once on acceptance; `a` sends nothing while checking; a busy preview is ready once the foreign preview frees the scan | The fixture socket delivers the host's acceptance, the key handler's synchronous send is read at once, and the fixture answers `releasePlans` after the foreign preview has finished, instead of 50 ms–1.2 s. The native-loader windows stay with their reason: no page event marks a request that is never made. |
| ui-sdk `refused-launch-gate.test.ts`, a refused or orphaned gated payload | The payload never starts once its gate is refused | The test polls `/proc/<pid>/stat` (PID and start time) until each gated sandbox is gone, with a 10 s failure maximum, instead of 1.2 s windows. The signal delays stay: they stand in for scheduler latency. |
| Kept real time, reason in source (other packages) | Claude `transcript-archive-event-loop` fsync delay; ui-sdk `inference-relay` and `provider-relay` native socket idle timer; ui-kit `ghost-handoff` and `streaming-handoff` long tasks | Each is the stimulus: slow IO, Bun's native idle timer, which no JS clock advances, and a long task that must also delay the browser's own frames. |

## Continuity settling boundaries

Expand Down
45 changes: 35 additions & 10 deletions packages/core/tests/compute-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,15 +253,45 @@ describe("a run interrupted or left unclean", () => {
throw new Error(`no new job reached ${state}`);
}

/**
* Read `reader` until the text seen so far contains `needle`, the stream
* ends or 10 s pass (a failure maximum, cleared once a read answers); return
* everything read. The run logs a signal from its handler, so that line is
* on stderr once the signal has been recorded.
*/
async function readUntil(reader: ReadableStreamDefaultReader<Uint8Array>, needle: string, seen = ""): Promise<string> {
const decoder = new TextDecoder();
const deadline = Date.now() + 10_000;
while (!seen.includes(needle) && Date.now() < deadline) {
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<undefined>((resolve) => (timer = setTimeout(resolve, deadline - Date.now(), undefined)));
const chunk = await Promise.race([reader.read(), late]);
clearTimeout(timer);
if (!chunk || chunk.done) break;
seen += decoder.decode(chunk.value, { stream: true });
}
return seen;
}

/** The rest of `reader`'s stream, after `seen`. */
async function readToEnd(reader: ReadableStreamDefaultReader<Uint8Array>, seen: string): Promise<string> {
const decoder = new TextDecoder();
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) seen += decoder.decode(chunk.value, { stream: true });
return seen + decoder.decode();
}

test("a signal while the job is still starting is kept: the job is cancelled once it has started", async () => {
rmSync(gate(), { force: true });
const before = new Set(jobIds(faults));
const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/raft.md", "--json", "--", "sleep", "60"]);
const id = await newJobIn(before, "staging");
proc.kill("SIGTERM");
await Bun.sleep(200);
// Open the stage only once the run has recorded the signal, so it arrives while the job is starting.
const reader = proc.stderr.getReader();
const logged = await readUntil(reader, "SIGTERM received");
expect(logged).toContain("SIGTERM received");
writeFileSync(gate(), "");
const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), readToEnd(reader, logged), proc.exited]);
rmSync(gate(), { force: true });
expect(code).toBe(3);
expect(stderr).toContain("SIGTERM received, cancelling");
Expand All @@ -276,16 +306,11 @@ describe("a run interrupted or left unclean", () => {
const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/route.md", "--human", "--", "sleep", "60"]);
const id = await newJobIn(before, "staging");
const reader = proc.stderr.getReader();
let seen = "";
const deadline = Date.now() + 10_000;
while (!seen.includes(id) && Date.now() < deadline) {
const chunk = await Promise.race([reader.read(), Bun.sleep(500).then(() => undefined)]);
if (chunk?.value) seen += new TextDecoder().decode(chunk.value);
if (chunk?.done) break;
}
const seen = await readUntil(reader, id);
expect(seen).toContain(id);
proc.kill("SIGINT");
await Bun.sleep(200);
// Open the stage only once the run has recorded the signal, so it arrives while the job is starting.
expect(await readUntil(reader, "SIGINT received", seen)).toContain("SIGINT received");
writeFileSync(gate(), "");
reader.releaseLock();
const [stdout, code] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
Expand Down
45 changes: 40 additions & 5 deletions packages/core/tests/compute-ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,21 +214,51 @@ describe("caller binding", () => {
});

describe("the background driver", () => {
/**
* `ops` whose `status` answers count as visits: `visited(n)` resolves once
* the driver's nth status call has answered, before the driver continues.
*/
function counted(ops: ComputeOps) {
let visits = 0;
const waiting: { n: number; resolve: () => void }[] = [];
const wrapped: ComputeOps = {
...ops,
status: async (input) => {
const result = await ops.status(input);
visits++;
for (const w of waiting.filter((w) => w.n <= visits)) w.resolve();
return result;
},
};
const visited = (n: number) => (visits >= n ? Promise.resolve() : new Promise<void>((resolve) => waiting.push({ n, resolve })));
return { ops: wrapped, visited };
}
/** One macrotask: the driver's continuation after an answered visit has run. */
const macrotask = () => new Promise<void>((resolve) => setImmediate(resolve));

test("advances tracked jobs through status until settled, then stops visiting", async () => {
const { ops, clock, memory } = setup();
const o = ops(TELEMACHUS);
const run = await o.run({ provider: "pylos-memory", argv: ["sleep", "5"] });
if (!run.ok) throw new Error(run.error.code);
const driver = createComputeDriver(o, { initialDelayMs: 5, maxDelayMs: 20 });
const visits = counted(o);
const driver = createComputeDriver(visits.ops, { initialDelayMs: 5, maxDelayMs: 20 });
driver.track(run.job.id);
expect(driver.tracked()).toEqual([run.job.id]);
await Bun.sleep(40);
expect(driver.tracked()).toEqual([run.job.id]);
// Each visit answers "running"; the next is armed at least 8 ms later, after this macrotask.
for (const n of [1, 2]) {
await visits.visited(n);
await macrotask();
expect(driver.tracked()).toEqual([run.job.id]);
}
clock.advance(6_000);
for (let i = 0; i < 100 && driver.tracked().length > 0; i++) await Bun.sleep(10);
expect(driver.tracked()).toEqual([]);
expect(await o.status({ job: run.job.id })).toMatchObject({ ok: true, job: { state: "succeeded", cleanup: { state: "released" } } });
const polls = memory.calls.filter((c) => c.method === "poll").length;
// Nothing is tracked, so the driver arms no timer and no visit is due.
// A visit it wrongly scheduled would fire within maxDelayMs (20 ms); the
// window gives it three of those, and there is no event for "no timer".
await Bun.sleep(60);
expect(memory.calls.filter((c) => c.method === "poll").length).toBe(polls);
driver.stop();
Expand All @@ -239,11 +269,16 @@ describe("the background driver", () => {
const o = ops(TELEMACHUS);
const run = await o.run({ provider: "pylos-memory", argv: ["sleep", "600"] });
if (!run.ok) throw new Error(run.error.code);
const driver = createComputeDriver(o, { initialDelayMs: 5, maxDelayMs: 5 });
const visits = counted(o);
const driver = createComputeDriver(visits.ops, { initialDelayMs: 5, maxDelayMs: 5 });
driver.track(run.job.id);
await Bun.sleep(30);
// Stop once a visit has answered, before the driver re-tracks the job.
await visits.visited(1);
driver.stop();
const calls = memory.calls.length;
// Stopped, the driver clears its timer and arms no other. A visit it still
// ran would come within its 5 ms delay; the window gives it eight, and
// there is no event for "no timer".
await Bun.sleep(40);
expect(memory.calls.length).toBe(calls);
expect(memory.calls.some((c) => c.method === "kill" || c.method === "release")).toBe(false);
Expand Down
5 changes: 4 additions & 1 deletion packages/core/tests/compute-race.run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* process, and assert its exit. It installs the repository network guard
* itself, since a plain `bun` child does not run the test preload.
*
* race <spec> wait for a barrier file, then run one job; print the result
* race <spec> print "ready", wait for a barrier file, then run one job;
* print the result
* hold <path> take a compute lock, print "held", and keep it until killed
* crash <spec> run a job on the local-process provider and SIGKILL this
* process at a named point, leaving the record mid-lifecycle
Expand Down Expand Up @@ -57,6 +58,8 @@ if (mode === "race") {
budget: fileBudget(spec.ledger, spec.cap),
config: { compute: { providers: { ithaca: { provider: memory.provider, lease: { maxSeconds: 600 }, maxConcurrent: spec.maxConcurrent, hourlyCeilingUsd: spec.ceiling } } } },
});
// Every racer reports "ready" here; the test writes the barrier only once all have.
console.log("ready");
while (!existsSync(spec.barrier)) await Bun.sleep(2);
const result = await svc.run(PENELOPE, { instance: "ithaca", argv: ["sleep", "3600"] });
console.log(JSON.stringify(result.ok ? { ok: true, id: result.job.id } : { ok: false, code: result.code }));
Expand Down
37 changes: 32 additions & 5 deletions packages/core/tests/compute-race.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,26 @@ afterEach(async () => {
box?.dispose();
});

/** A child's stdout one line at a time; `next()` is undefined once the stream ends without one. */
function lines(stream: ReadableStream<Uint8Array>) {
const reader = stream.getReader();
const decoder = new TextDecoder();
let buffered = "";
return {
async next(): Promise<string | undefined> {
while (!buffered.includes("\n")) {
const chunk = await reader.read();
if (chunk.done) return undefined;
buffered += decoder.decode(chunk.value, { stream: true });
}
const at = buffered.indexOf("\n");
const line = buffered.slice(0, at);
buffered = buffered.slice(at + 1);
return line;
},
};
}

async function race(spec: { maxConcurrent: number; ceiling?: number; cap: number }) {
box = sandbox();
const barrier = join(box.base, "go");
Expand All @@ -35,15 +55,22 @@ async function race(spec: { maxConcurrent: number; ceiling?: number; cap: number
const racers = Array.from({ length: RACERS }, () => {
const child = Bun.spawn([process.execPath, RUNNER, "race", file], { stdout: "pipe", stderr: "pipe", stdin: "ignore" });
children.push(child);
return child;
return { child, stdout: lines(child.stdout) };
});
await Bun.sleep(300);
// Release the barrier only once every racer is waiting at it, so all of them contend for admission.
// Bounded, so a racer that never reports ready fails here; the file's
// teardown kills every child it spawned.
let bound: ReturnType<typeof setTimeout> | undefined;
try {
const timedOut = new Promise<string>(resolve => { bound = setTimeout(() => resolve("RACER_NEVER_READY"), 10_000); });
for (const racer of racers) expect(await Promise.race([racer.stdout.next(), timedOut])).toBe("ready");
} finally { clearTimeout(bound); }
writeFileSync(barrier, "");
const results = await Promise.all(
racers.map(async (child) => {
const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
racers.map(async ({ child, stdout }) => {
const [result, stderr] = await Promise.all([stdout.next(), new Response(child.stderr).text(), child.exited]);
expect({ code: child.exitCode, stderr: child.exitCode === 0 ? "" : stderr }).toEqual({ code: 0, stderr: "" });
return JSON.parse(stdout.trim()) as { ok: boolean; code?: string };
return JSON.parse(result ?? "null") as { ok: boolean; code?: string };
})
);
return { admitted: results.filter((r) => r.ok).length, refused: results.filter((r) => !r.ok).map((r) => r.code) };
Expand Down
Loading
Loading