/** * ORDER INDEX (coordinator, 24 Nov 2026). An order shadow stands in for a partial order index on a file too big to * make one (src/order_shadow.ts): made empty with its triggers, filled a bounded step an alarm, then walked by reads * exactly as the index was. Off by default, per account. */ import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { FIRST_INDEX_NOW_BYTES, type Store } from "../src/store.ts"; import * as orderShadow from "../src/order_shadow.ts"; import { personalShape, writeShape } from "./big_object.ts"; import { ADMIN, http, personalObject } from "./personal.ts"; type Instance = { store: Store }; const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const shadowTables = (sql: SqlStorage): string[] => sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE name LIKE 'shadow_%' ORDER BY name").toArray().map((r) => r.name); const firstIndexes = (sql: SqlStorage): string[] => sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'rows_first_%'").toArray().map((r) => r.name); /** A personal object past the size at which an index is made in the request, of the invented shape. */ async function bigEnough(slug: string): Promise<{ phone: Record; owner: string }> { const { credential, owner } = await personalObject(slug); await runInDurableObject(stub(slug), (_i, s) => { const last = writeShape(s.storage.sql, personalShape(1 / 300)); s.storage.sql.exec("UPDATE meta SET value = CAST(? AS TEXT) WHERE key = 'version'", last); s.storage.sql.exec("CREATE TABLE IF NOT EXISTS filler (b BLOB)"); while (s.storage.sql.databaseSize < FIRST_INDEX_NOW_BYTES + 4 * 1024 * 1024) s.storage.sql.exec("INSERT INTO filler (b) SELECT randomblob(1048576) FROM (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4)"); for (const name of firstIndexes(s.storage.sql)) s.storage.sql.exec(`DROP INDEX ${name}`); }); // Its row counts counted, as on his object long since: a pass from nothing plans its first tables by them, and a // recount still under way (the alarm's, under load) plans none and asks for nothing. await runInDurableObject(stub(slug), (o) => { const store = (o as unknown as { store: { carryCounts(steps: number): boolean } }).store; while (store.carryCounts(10_000)); }); return { phone: { authorization: `Bearer ${credential}` }, owner }; } /** Alarms run by hand until every shadow asked is ready; answers how many ran. */ async function fill(slug: string, most = 400): Promise { for (let i = 0; i < most; i++) { const p = await runInDurableObject(stub(slug), (o) => (o as unknown as Instance).store.shadowProgress()); if (p.shadows.length && p.shadows.every((s) => s.ready)) return i; await runDurableObjectAlarm(stub(slug)); } throw new Error("the shadows never filled"); } const passIds = async (slug: string, phone: Record): Promise => { const out: string[] = []; let path = "/v1/sync?since=0&limit=400"; for (let i = 0; i < 8; i++) { const page = await http<{ rows: { id: string; table: string }[]; next?: string | null }>(slug, "GET", path, undefined, phone); expect(page.status, JSON.stringify(page.body).slice(0, 300)).toBe(200); out.push(...page.body.rows.map((r) => `${r.table}/${r.id}`)); if (!page.body.next) break; path = `/v1/sync?cursor=${encodeURIComponent(page.body.next)}`; } return out; }; describe("order shadows", { timeout: 900_000 }, () => { it("are off by default: a big file asks for nothing and makes nothing", async () => { const slug = "order-shadow-off"; const { phone, owner } = await bigEnough(slug); expect((await http(slug, "GET", "/v1/sync?since=0", undefined, phone)).status).toBe(200); const after = await runInDurableObject(stub(slug), (o, s) => ({ tables: shadowTables(s.storage.sql), progress: (o as unknown as Instance).store.shadowProgress() })); expect(after.tables).toEqual([]); expect(after.progress).toMatchObject({ on: false, shadows: [] }); // The switch takes the admin token; on the dev and test Workers the account's own owner too (this is the test // Worker), never a caller with no credential. expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true })).status).not.toBe(200); expect((await http(slug, "GET", "/v1/admin/order-shadow", undefined, phone)).status).toBe(403); expect((await http(slug, "GET", "/v1/admin/order-shadow", undefined, { authorization: `Bearer ${owner}` })).status).toBe(200); }); it("fill a bounded step an alarm, keep every write made meanwhile, and are walked as the index was", async () => { const slug = "order-shadow-on"; const { phone } = await bigEnough(slug); expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200); // Small steps, so the filling takes several alarms. await runInDurableObject(stub(slug), (o) => (o as unknown as Instance).store.setMeta(orderShadow.STEP_META, "500")); // A pass from nothing asks; nothing is made in it, and it is answered in its own order meanwhile. const before = await passIds(slug, phone); expect(before.length).toBeGreaterThan(0); const asked = await runInDurableObject(stub(slug), (o, s) => ({ indexes: firstIndexes(s.storage.sql), p: (o as unknown as Instance).store.shadowProgress() })); expect(asked.indexes).toEqual([]); expect(asked.p.shadows.length).toBeGreaterThan(0); // (The pool runs the object's alarm at its time too, so some may already be filling: the checks below hold either way.) // Two alarms: the first makes the first shadow empty with its triggers, the second lays its first step. await runDurableObjectAlarm(stub(slug)); await runDurableObjectAlarm(stub(slug)); // Meanwhile: a row added, one moved in its order, one gone, one tombstoned, by any writer (here plain SQL). const moved = await runInDurableObject(stub(slug), (_o, s) => { const sql = s.storage.sql; const t = "message"; const ids = sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = ? ORDER BY id LIMIT 3", t).toArray().map((r) => r.id); sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, 'zz-new', json_object('sent_at', '2031-01-01T00:00:00Z', 'thread_id', 't00001'), NULL, 999999, 0, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')", t); sql.exec("UPDATE rows SET data = json_set(data, '$.sent_at', '2030-06-01T00:00:00Z'), version = 999998 WHERE table_id = ? AND id = ?", t, ids[0]); sql.exec("DELETE FROM rows WHERE table_id = ? AND id = ?", t, ids[1]); sql.exec("UPDATE rows SET deleted = 1, data = '{}', version = 999997 WHERE table_id = ? AND id = ?", t, ids[2]); return { t, ids }; }); await fill(slug); // Every shadow holds exactly what its index would: each row of its table, by the same values, in the same order. const held = await runInDurableObject(stub(slug), (o, s) => { const sql = s.storage.sql; const p = (o as unknown as Instance).store.shadowProgress(); const out: { name: string; shadow: string[]; truth: string[]; steps: number; rows: number }[] = []; for (const sh of p.shadows) { const spec = orderShadow.ready({ get: (k) => sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", k).toArray()[0]?.value ?? null, set: () => {} }, sh.name)!; const values = spec.terms.map((t, i) => (t.expr === "id" ? "o.sid" : `o.c${i}`)); const shadow = sql.exec<{ v: string }>(`SELECT ${values.map((v) => `quote(${v})`).join(" || '|' || ")} AS v FROM ${orderShadow.names(spec.name).table} AS o ORDER BY ${orderShadow.orderBy(spec)}`).toArray().map((r) => r.v); const exprs = spec.terms.map((t) => t.expr); const truth = sql.exec<{ v: string }>(`SELECT ${exprs.map((e) => `quote(${e})`).join(" || '|' || ")} AS v FROM rows WHERE table_id = ?${spec.live ? " AND deleted = 0" : ""} ORDER BY ${spec.terms.map((t) => `${t.expr}${t.collate ? ` COLLATE ${t.collate}` : ""}${t.desc ? " DESC" : ""}`).join(", ")}`, spec.table).toArray().map((r) => r.v); out.push({ name: sh.name, shadow, truth, steps: sh.steps, rows: sh.rows }); } return out; }); for (const h of held) { expect(h.shadow, h.name).toEqual(h.truth); // A step reads at most its 500 rows of its own table. expect(h.steps, h.name).toBeGreaterThanOrEqual(Math.ceil(h.rows / 500)); } const mine = held.find((h) => h.name === `rows_first_${moved.t}`)!; expect(mine.shadow.some((v) => v.includes("'zz-new'"))).toBe(true); expect(mine.shadow.some((v) => v.includes(`'${moved.ids[1]}'`))).toBe(false); // A pass from nothing now walks the shadows; with the real indexes made it carries the same rows in the same order. const shadowed = await passIds(slug, phone); const walked = await runInDurableObject(stub(slug), (_o, s) => firstIndexes(s.storage.sql)); expect(walked).toEqual([]); await runInDurableObject(stub(slug), (o) => { const store = (o as unknown as Instance).store; store.setShadows(false); store.setMeta(orderShadow.SWITCH, null); }); // Off: every shadow, trigger and record of them is gone. expect(await runInDurableObject(stub(slug), (_o, s) => s.storage.sql.exec("SELECT name FROM sqlite_master WHERE name LIKE 'shadow_%'").toArray().length)).toBe(0); await runInDurableObject(stub(slug), (_o, s) => { // The real indexes, made by hand (a small table here), as a small file makes them. for (const t of ["message", "email", "photo", "person_handle", "message_contact_handle", "event", "thread"]) s.storage.sql.exec(`DROP INDEX IF EXISTS rows_first_${t}`); }); const plain = await passIds(slug, phone); expect(shadowed.length).toBeGreaterThan(before.length / 2); // The same rows whichever way they were walked (the order is the first orders' either way once a walk stands). expect([...shadowed].sort()).toEqual([...plain].sort()); }); it("serve list_records' order and older mail exactly as a sort does", async () => { const slug = "order-shadow-list"; await bigEnough(slug); expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200); const order = "NULLIF(json_extract(data, '$.sent_at'), '') IS NULL, NULLIF(json_extract(data, '$.sent_at'), '') COLLATE NOCASE DESC, updated_at DESC, id"; const cond = [{ sql: "json_extract(data, '$.thread_id') <> ?", args: ["t00002"] }]; const sorted = await runInDurableObject(stub(slug), (o) => { const store = (o as unknown as Instance).store; return [0, 40, 400].map((offset) => store.select("message", cond, order, 20, offset).map((r) => r.id)); }); const first = await runInDurableObject(stub(slug), (o) => (o as unknown as Instance).store.selectOrdered("message", cond, order, 20, 0)); expect(first).toBeNull(); // Older mail before its shadow is ready: a sort, never an index made in the request. const olderBefore = await runInDurableObject(stub(slug), (o, s) => ({ page: (o as unknown as Instance).store.olderPage("email", "received_at", { before: ["2024-06-01T08:00:00Z", "email-00000500"], from: null, to: null, eq: null, limit: 25 }).map((r) => r.id), indexes: firstIndexes(s.storage.sql) })); expect(olderBefore.indexes).toEqual([]); await fill(slug); const walked = await runInDurableObject(stub(slug), (o) => { const store = (o as unknown as Instance).store; return [0, 40, 400].map((offset) => store.selectOrdered("message", cond, order, 20, offset)!.map((r) => r.id)); }); expect(walked).toEqual(sorted); const olderAfter = await runInDurableObject(stub(slug), (o) => (o as unknown as Instance).store.olderPage("email", "received_at", { before: ["2024-06-01T08:00:00Z", "email-00000500"], from: null, to: null, eq: null, limit: 25 }).map((r) => r.id)); expect(olderAfter).toEqual(olderBefore.page); expect(olderAfter.length).toBe(25); }); it("turn off whole or not at all: an off that meets an open read changes nothing, and the next off takes everything", async () => { const slug = "order-shadow-off-whole"; const { phone } = await bigEnough(slug); expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200); await passIds(slug, phone); await fill(slug); const was = await runInDurableObject(stub(slug), (_o, s) => shadowTables(s.storage.sql)); expect(was.length).toBeGreaterThan(0); // As the route runs it: in one transaction. With a read left open, SQLite refuses the first DROP and all of it rolls back. const after = await runInDurableObject(stub(slug), (o, s) => { const store = (o as unknown as Instance).store; const open = s.storage.sql.exec("SELECT id FROM rows"); try { expect(() => s.storage.transactionSync(() => store.setShadows(false))).toThrow(/SQLITE_LOCKED/); } finally { // The rollback ends that read too (SQLITE_ABORT_ROLLBACK): nothing is left to drain. try { open.toArray(); } catch { // ended by the rollback } } return { tables: shadowTables(s.storage.sql), p: store.shadowProgress() }; }); expect(after.tables).toEqual(was); expect(after.p.on).toBe(true); expect(after.p.shadows.length).toBeGreaterThan(0); expect(after.p.shadows.every((sh) => sh.ready)).toBe(true); // A pass still walks them, every table there. expect((await passIds(slug, phone)).length).toBeGreaterThan(0); // The same call again, with nothing open: everything goes. const off = await http<{ on: boolean; shadows: unknown[] }>(slug, "POST", "/v1/admin/order-shadow", { on: false }, ADMIN); expect(off.status).toBe(200); expect([off.body.on, off.body.shadows]).toEqual([false, []]); expect(await runInDurableObject(stub(slug), (_o, s) => shadowTables(s.storage.sql))).toEqual([]); }); it("take half the rows a step after an alarm was reset while one filled (the bell), never under the least", async () => { const slug = "order-shadow-bell"; await bigEnough(slug); expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200); const steps = await runInDurableObject(stub(slug), (o) => { const store = (o as unknown as Instance).store; const nothing = store.shadowReset(); orderShadow.ask({ get: (k) => store.meta(k), set: (k, v) => store.setMeta(k, v) }, { name: "rows_first_message", table: "message", terms: [{ expr: "id" }], live: false }); const out = [nothing]; for (let i = 0; i < 8; i++) out.push(store.shadowReset()); return out; }); expect(steps).toEqual([null, 10_000, 5_000, 2_500, 1_250, 625, 500, 500, 500]); }); });