Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions packages/ui-server/tests/dialogue-queue-adoption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { createSessionCatalog } from "../src/ws/session-catalog.js";
import { DialogueJournal } from "../src/ws/dialogue.js";
import type { DialogueOwner } from "../src/ws/dialogue-storage.js";
import * as controls from "./helpers/dialogue-test-writes.js";
import { storageDeadlineClock } from "./helpers/storage-deadline-clock.js";

type Queue = { count: number; bytes: number };
function queues(journal: DialogueJournal): Map<DialogueOwner, Queue> {
Expand All @@ -23,6 +24,12 @@ function evidence(sequence: number, text = "The mast is ready."): Extract<Dialog
} };
}
async function fixture() {
// Each case holds the native writer while it fills the admission bound with
// up to 256 writes, and every write's real 10 s storage budget runs from its
// submission until the worker drains the queue after release. How long that
// takes depends on the host's load. The budget is not what these cases claim,
// so it fires only when a case expires it, never because a host was slow (#3561).
const clock = storageDeadlineClock({ manual: true });
const dir = mkdtempSync(join(tmpdir(), "odysseus-queue-adoption-"));
const db = createUiDb(join(dir, "ui.db")), writer = openSqliteWriter(db);
const catalog = createSessionCatalog(() => db, undefined, undefined, {
Expand All @@ -34,6 +41,11 @@ async function fixture() {
const holds: { gate: Int32Array; done: Promise<unknown> }[] = [];
const release = () => { for (const { gate } of holds) { Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); } };
return { db, writer, catalog, journal, failures, pages, release, control,
/** Every armed budget was cleared by its write settling, none by the clock. */
budgetsSettled() {
expect(clock.registered, "STORAGE_BUDGET_ARMED_DURING_HOLD").toBeGreaterThan(0);
expect(clock.pending, "STORAGE_BUDGET_CLEARED_BY_SETTLEMENT").toBe(0);
},
async hold() {
const gate = new Int32Array(new SharedArrayBuffer(8));
const done = control.call("hold", gate);
Expand All @@ -46,9 +58,11 @@ async function fixture() {
expect(writer.offloop).toBe(true);
},
async close() {
release(); await Promise.all(holds.map(h => h.done)); await journal.settled();
await catalog.settled!(); await control.close(); await writer.close(); db.close();
rmSync(dir, { recursive: true, force: true });
try {
release(); await Promise.all(holds.map(h => h.done)); await journal.settled();
await catalog.settled!(); await control.close(); await writer.close(); db.close();
rmSync(dir, { recursive: true, force: true });
} finally { clock.restore(); }
},
};
}
Expand Down Expand Up @@ -81,6 +95,7 @@ for (const merge of [false, true]) test(`native adoption retires idle queue book
expect(saved).toEqual([true, true]);
expect(queues(f.journal).size).toBe(0);
expect(f.db.query("SELECT closed FROM dialogue_conversations WHERE id='ithaca'").get()).toEqual({ closed: 1 });
f.budgetsSettled();
} finally { await f.close(); }
});

Expand Down Expand Up @@ -128,6 +143,7 @@ for (const bound of ["count", "bytes"] as const) test(`native alias adoption can
expect(f.db.query("SELECT coverage FROM dialogue_owners").get()).toEqual({ coverage: "partial" });
expect((await f.catalog.dialogueRead!("odysseus", { sessionId: "voyage" }))!.coverage).toBe("partial");
await expect(f.journal.settled(true)).rejects.toThrow("pending writes exceeded");
f.budgetsSettled();
} finally { f.release(); releaseCallbacks(); await f.close(); }
});

Expand Down Expand Up @@ -165,6 +181,7 @@ for (const bound of ["count", "bytes"] as const) for (const merge of [false, tru
expect(queues(f.journal).size, "ALL_CANONICAL_QUEUE_ENTRIES_RETIRE").toBe(0);
expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records").get()).toEqual({ n: count });
if (bound === "bytes") expect(count).toBeLessThan(CONVERSATION_LIMITS.maxPendingDialogueObservations);
f.budgetsSettled();
} finally { f.release(); releaseCallbacks(); await f.close(); }
});

Expand Down Expand Up @@ -193,6 +210,7 @@ for (const merge of [false, true]) test(`native rejected writes retire drained q
expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records").get()).toEqual({ n: saved.filter(Boolean).length });
expect(f.pages.flatMap(page => page.records).map(row => row.sequence)).toEqual(Array.from({ length: saved.filter(Boolean).length }, (_, i) => i + 1));
expect((await f.catalog.dialogueRead!("odysseus", { sessionId: "voyage" }))!.coverage).toBe("partial");
f.budgetsSettled();
} finally { await f.close(); }
});

Expand Down Expand Up @@ -258,5 +276,6 @@ test(`fresh-owner ${route} shares ${bound} admission with its canonical target o
expect(f.failures.length, "SETTLED_CALLBACKS_RESTORE_ADMISSION").toBe(failures);
expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records").get()).toEqual({ n: count + 100 });
expect(queues(f.journal).size).toBe(0);
f.budgetsSettled();
} finally { await f.close(); }
});
18 changes: 15 additions & 3 deletions packages/ui-server/tests/helpers/storage-deadline-clock.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
import { STORAGE_SETTLEMENT_MS } from "../../src/db/settlement.js";

/** Advance only the production storage budget; native I/O remains genuinely held. */
export function storageDeadlineClock() {
/**
* Advance only the production storage budget; native I/O remains genuinely held.
*
* By default a registered budget still fires after its real interval. With
* `manual`, it fires only through `expire()` or `captureLatest()`. That suits a
* test whose claim is not the budget, but whose held writes take a
* load-dependent time to settle, so a slow host cannot expire them (#3561).
*/
export function storageDeadlineClock(options: { manual?: boolean } = {}) {
const timeout = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!;
const clear = Object.getOwnPropertyDescriptor(globalThis, "clearTimeout")!;
const nativeSet = globalThis.setTimeout, nativeClear = globalThis.clearTimeout;
const pending = new Map<ReturnType<typeof setTimeout>, () => void>();
let registered = 0;
Object.defineProperty(globalThis, "setTimeout", { ...timeout, value: (callback: (...args: unknown[]) => void, ms?: number, ...args: unknown[]) => {
if (ms !== STORAGE_SETTLEMENT_MS) return nativeSet(callback, ms, ...args);
const timer = nativeSet(() => { pending.delete(timer); callback(...args); }, ms);
registered++;
// A manual budget keeps a real handle, so clearTimeout behaves natively, but its expiry does nothing.
const timer = options.manual ? nativeSet(() => {}, ms) : nativeSet(() => { pending.delete(timer); callback(...args); }, ms);
pending.set(timer, () => callback(...args));
return timer;
} });
Object.defineProperty(globalThis, "clearTimeout", { ...clear, value: (timer: ReturnType<typeof setTimeout>) => { pending.delete(timer); nativeClear(timer); } });
return {
get pending() { return pending.size; },
/** Every production budget armed since installation, settled or not. */
get registered() { return registered; },
/** Capture one concrete deadline; cancellation must not expire a different timer. */
captureLatest() {
const timer = [...pending.keys()].at(-1);
Expand Down
Loading