/** * READ COST 2 (coordinator, 28 Nov 2026): on a file over ORDER_INDEX_MAX_BYTES no index is made, so log_session, * list_bin and the prompts' keep read along shadows the alarm fills a bounded step at a time (src/order_shadow.ts, * Store.lookup). The file pretends to be over the limit (Store.indexTooBig answers true for this file's run), the * account's shadow switch is on, and about 155k invented rows sit beside the three lookups. Each door's first call asks * for its shadow and reads as before; the alarm's steps fill them; then each door reads a bounded number of rows, finds * the right rows, and sees a write made after the fill (the triggers). Synthetic rows only. */ import { env, runInDurableObject } from "cloudflare:test"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { keepPrompts, PROMPTS_KEPT } from "../src/erase.ts"; import { Store } from "../src/store.ts"; import { ADMIN, http, personalObject, tool } from "./personal.ts"; const SLUG = "read-cost-shadows"; const SESSIONS = 50_000; const PROMPTS = 25_000; const OLD_PROMPTS = 10; const NOTES = 60_000; const BINNED = 20_000; const BOUND = 5_000; /** The alarm's step on a busy object (business.ts GENTLE_SHADOW_ROWS). */ const STEP = 2_500; const stub = () => env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)); type Cursor = SqlStorageCursor>; type Patched = { exec: (...a: unknown[]) => Cursor; __cursors?: Cursor[]; __said?: string[]; __exec?: (...a: unknown[]) => Cursor }; /** The rows SQLite reads while `run` goes. */ async function costOf(run: () => Promise): Promise<{ rowsRead: number; answer: unknown }> { await runInDurableObject(stub(), (_i, state) => { const sql = state.storage.sql as unknown as Patched; const exec = (sql.__exec ??= sql.exec.bind(sql)); const cursors: Cursor[] = []; const said: string[] = []; sql.__cursors = cursors; sql.__said = said; sql.exec = (...a: unknown[]) => { const c = exec(...a); cursors.push(c); said.push(String(a[0]).replace(/\s+/g, " ").slice(0, 200)); return c; }; }); const answer = await run(); const rowsRead = await runInDurableObject(stub(), (_i, state) => { const sql = state.storage.sql as unknown as Patched; if (sql.__exec) sql.exec = sql.__exec; sql.__cursors!.forEach((c, i) => { if (c.rowsRead > 1_000) console.log(`READ COST 2 heavy: ${c.rowsRead} rows: ${sql.__said![i]}`); }); return sql.__cursors!.reduce((n, c) => n + c.rowsRead, 0); }); return { rowsRead, answer }; } const proto = Store.prototype as unknown as { indexTooBig(): boolean }; const tooBig = proto.indexTooBig; describe("over the index limit, the lookups read along shadows the alarm fills (READ COST 2)", { timeout: 900_000 }, () => { let owner = ""; const said: string[] = []; const keep = (sql: SqlStorage, store: Store) => { store.setMeta(PROMPTS_KEPT, null); return keepPrompts(store, sql, new Date()); }; beforeAll(async () => { // The file is over ORDER_INDEX_MAX_BYTES as far as the store can tell: no index is made, none is asked of the alarm. proto.indexTooBig = () => true; owner = (await personalObject(SLUG, { open: ["note"] })).owner; expect((await http(SLUG, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200); const now = new Date().toISOString(); await runInDurableObject(stub(), (_i, state) => { const fill = (table: string, n: number, data: string, prefix = table) => state.storage.sql.exec( `WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT ?, ? || '-' || i, ${data}, NULL, 1, 0, ?, ? FROM n`, n, table, prefix, now, now, ); fill("session", SESSIONS, `json_object('tool', 'claude-code', 'external_id', 'invented-ext-' || i, 'title', 'session ' || i, 'machine', 'invented-mac')`); fill("prompt", PROMPTS, `json_object('ts', '${now}', 'text', 'invented')`); fill("note", NOTES, `json_object('title', 'note ' || i)`); // Binned a second apart by their number, so the newest are known. fill("note", BINNED, `json_object('title', 'binned ' || i, 'trashed_at', strftime('%Y-%m-%dT%H:%M:%fZ', '2026-11-01', '+' || i || ' seconds'))`, "binned-note"); }); // Its row counts counted, as on his object long since (a recount under way reads a page of rows a request). await runInDurableObject(stub(), (i) => { const store = (i as unknown as { store: Store }).store; // Filled by hand, past the store, so their counts are made again (READ COST 3's order-shadow answer reads a count, // which counts the file as it stood before the fill). for (const table of ["session", "prompt", "note"]) store.recountTable(table); while (store.carryCounts(10_000)); }); }, 900_000); afterAll(() => { proto.indexTooBig = tooBig; console.log(["READ COST 2:", ...said].join("\n")); }); it("reads as before until the shadows are filled, then each door reads a bounded number of rows", async () => { const logSession = (ext: string) => tool(SLUG, owner, "log_session", { tool: "claude-code", externalId: ext, machine: "invented-mac", lastActiveAt: new Date().toISOString() }); const listBin = () => tool(SLUG, owner, "list_bin", { limit: 5 }); const promptsKeep = () => runInDurableObject(stub(), (i, state) => keep(state.storage.sql, (i as unknown as { store: Store }).store)); // First calls: each asks for its shadow and walks as before. const before = { log_session: (await costOf(() => logSession("invented-ext-777"))).rowsRead, list_bin: (await costOf(listBin)).rowsRead, prompts_keep: (await costOf(promptsKeep)).rowsRead, }; console.log(`READ COST 2 after first calls: ${JSON.stringify((await http(SLUG, "GET", "/v1/admin/order-shadow", undefined, ADMIN)).body)}`); // The alarm's share: its order_shadow job, a step at a time, until nothing is filling. const fill = await runInDurableObject(stub(), (i) => { const store = (i as unknown as { store: Store }).store; let steps = 0; while (store.shadowStep(STEP)) steps++; return { steps: steps + 1, shadows: store.shadowProgress().shadows }; }); for (const s of fill.shadows) expect(s.ready, `${s.name} filled`).toBe(true); const names = fill.shadows.map((s) => s.name).sort(); expect(names).toEqual(expect.arrayContaining(["bin_note__trashed_at", "eq_session__external_id", "prompt_ts"])); // log_session: the session it names is found (updated, not made twice), reading a handful of rows. const ls = await costOf(() => logSession("invented-ext-777")); const sessions = await runInDurableObject(stub(), (_i, s) => s.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'session' AND json_extract(data, '$.external_id') = 'invented-ext-777' AND deleted = 0").one().n); expect(Number(sessions)).toBe(1); // list_bin: the newest binned notes, newest first; a note binned after the fill comes first (the triggers keep it). await runInDurableObject(stub(), (_i, s) => { s.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('note', 'binned-late', ?, NULL, 1, 0, ?, ?)", JSON.stringify({ title: "binned late", trashed_at: "2026-11-27T00:00:00.000Z" }), new Date().toISOString(), new Date().toISOString()); s.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.trashed_at', NULL) WHERE table_id = 'note' AND id = ?", `binned-note-${BINNED}`); }); const lb = await costOf(listBin); const ids = JSON.stringify(lb.answer).match(/binned-(late|note-\d+)/g) ?? []; expect(ids.slice(0, 3)).toEqual(["binned-late", `binned-note-${BINNED - 1}`, `binned-note-${BINNED - 2}`]); // The prompts' keep: only the old ones go, laid after the fill (the triggers carry them into the shadow). await runInDurableObject(stub(), (_i, s) => { const old = new Date(Date.now() - 40 * 86_400_000).toISOString(); for (let i = 1; i <= OLD_PROMPTS; i++) { s.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('prompt', ?, ?, NULL, 1, 0, ?, ?)", `old-prompt-${i}`, JSON.stringify({ ts: old, text: "invented old" }), old, old); } }); const pk = await costOf(promptsKeep); expect((pk.answer as { gone: number }).gone).toBe(OLD_PROMPTS); const after = { log_session: ls.rowsRead, list_bin: lb.rowsRead, prompts_keep: pk.rowsRead }; said.push(`fill: ${fill.steps} alarm steps of ${STEP} rows; ${fill.shadows.map((s) => `${s.name} ${s.rows} rows in ${s.steps} steps`).join("; ")}`); for (const door of Object.keys(after) as (keyof typeof after)[]) said.push(`| ${door} | ${before[door]} | ${after[door]} |`); for (const door of Object.keys(after) as (keyof typeof after)[]) expect(after[door], `${door} read ${after[door]} rows`).toBeLessThan(BOUND); }); });