import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { Store, typeCursor, typeStoredRow, typeSyncScope, typeSyncWindow } from"../src/store.ts";/** * RULE (owner, 2 Nov 2026): a fresh install holds the small tables whole in * its first minutes — people, todos, notes, money — then the big ones * (messages, email); the window rule stays as it is. * * A synthetic object of about twenty tables, some big, some windowed, some * with tombstones, written under many versions, is pulled page by page as a * phone pulls it — each page from the cursor alone — while writes land * between pages. Every seed must carry each row of the pass at most once, * every row that stayed in the pass exactly once, and the small tables whole, * fewest rows first, before any row of a big one. *//** A small fast generator, so a failing seed fails the same way again. */function rng(seed: number): () => number {let s = seed >>> 0;return () => { s = (s + 0x6d2b79f5) >>> 0;let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61);return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };}const MOST = 30;const INTERNAL = "token";const WINDOWED = "chat_line";const FROM = "2026-10-01";const key = (r: { table: string; id: string }): string => `${r.table}/${r.id}`;/** One seed's object: its rows written into a fresh store, and the version it ends at. */function build(store: Store, seed: number): { upto: number } {const next = rng(seed);const pick = (n: number): number => Math.floor(next() * n);const tables = Array.from({ length: 20 }, (_, i) => `t${String(i).padStart(2, "0")}`);// A few big tables; the rest small, some empty-ish, two the same size so the name breaks the tie.const sizes = tables.map((_, i) => (i % 6 === 0 ? MOST + 10 + pick(80) : 1 + pick(MOST))); sizes[3] = sizes[4] = 7;let version = 0;const written: StoredRow[] = [];const write = (table: string, id: string, data: Record<string, unknown>): void => { version += pick(3) === 0 ? 0 : 1 + pick(2); written.push(store.insert(table, id, data, null, Math.max(1, version))); }; tables.forEach((table, i) => {for (let n = 0; n < sizes[i]!; n++) write(table, `${table}-${String(pick(1e6)).padStart(6, "0")}-${n}`, { n }); });// A windowed table, big before its window and small within it: counted as the window keeps it.for (let n = 0; n < MOST * 3; n++) write(WINDOWED, `cl-${n}`, { sent_at: n < MOST * 3 - 10 ? "2026-01-01T00:00:00Z" : "2026-10-20T00:00:00Z" });for (let n = 0; n < 5; n++) write(INTERNAL, `tok-${n}`, {});// Shuffle the change order: every row written again at a later version, some deleted. written.sort(() => next() - 0.5);for (const row of written.slice(0, Math.floor(written.length / 3))) { version += 1;if (pick(4) === 0) store.tombstone(row, version);else store.update(row, { ...row.data, again: true }, null, version); }return { upto: version };}/** Every row the store holds, as it holds it. */function all(store: Store): StoredRow[] {const rows: StoredRow[] = [];for (let after: Cursor | null = null; ; ) {const page = store.changedPage({ since: -1, upto: Number.MAX_SAFE_INTEGER, limit: 10_000, scope: { kind: "all", except: newSet() }, windows: [], small: [], floor: null, after }); rows.push(...page.rows);if (!page.more) return rows;const last = page.rows[page.rows.length - 1]!; after = { version: last.version, table: last.table, id: last.id }; }}/** Whether `row` is in a pass up to `upto` under the test's scope and window. */function inPass(row: StoredRow, upto: number): boolean {if (row.table === INTERNAL || row.version > upto) returnfalse;if (row.table === WINDOWED && !row.deleted && String(row.data.sent_at) < FROM) returnfalse;returntrue;}typePass = { carried: StoredRow[]; touched: Set<string>; small: string[] };/** * One pass from nothing as the phone pulls it, every page from the cursor its * last page made (through JSON, as the wire carries it). From page `bridgeAt` * on, a pass begun in change order goes on small tables first from where it * got to, as an old cursor does. Between pages some rows are written again. */function pull(store: Store, seed: number, upto: number, opts: { bridgeAt: number | null }): Pass {const next = rng(seed * 31 + 7);const scope: SyncScope = { kind: "all", except: newSet([INTERNAL]) };const windows: SyncWindow[] = [{ table: WINDOWED, column: "sent_at", from: FROM }];const limit = 1 + Math.floor(next() * 40);const plan = (): string[] => store.smallFirst({ since: 0, upto, scope, windows, most: MOST });typeWire = { small: string[]; floor: Cursor | null; after: Cursor | null };let cursor: Wire = opts.bridgeAt === null ? { small: plan(), floor: null, after: null } : { small: [], floor: null, after: null };const small = cursor.small;const carried: StoredRow[] = [];const touched = newSet<string>();let version = upto;for (let page = 0; ; page++) {if (opts.bridgeAt !== null && page === opts.bridgeAt) cursor = { small: plan(), floor: cursor.after, after: null };const got = store.changedPage({ since: 0, upto, limit, scope, windows, ...cursor }); expect(got.rows.length).toBeLessThanOrEqual(limit); carried.push(...got.rows);if (!got.more) break;const last = got.rows[got.rows.length - 1]!; cursor = JSON.parse(JSON.stringify({ ...cursor, after: { version: last.version, table: last.table, id: last.id } })) asWire;// Writes between pages: a row written again moves past `upto`.for (const row of all(store)) {if (row.version <= upto && next() < 0.02) { version += 1; touched.add(key(row)); store.update(row, { ...row.data, mid: true }, null, version); } } }return { carried, touched, small: opts.bridgeAt === null ? small : [] };}asyncfunction withStore<T>(name: string, run: (store: Store) => T): Promise<T> {const stub = env.BUSINESS.get(env.BUSINESS.idFromName(name));return runInDurableObject(stub, (_instance, state) => {const store = newStore(state.storage.sql, () => newDate("2026-11-02T10:00:00Z")); store.setDateColumns(newMap([[WINDOWED, "sent_at"]]));return run(store); });}/** The pass's rows as the object held them when it began. */function before(store: Store, upto: number): Map<string, StoredRow> {returnnewMap(all(store).filter((r) => inPass(r, upto)).map((r) => [key(r), r]));}function noneTwiceNoneSkipped(pass: Pass, expected: Map<string, StoredRow>): void {const keys = pass.carried.map(key); expect(newSet(keys).size, "no row comes twice").toBe(keys.length);for (const k of keys) expect(expected.has(k), `${k} was in the pass`).toBe(true);const got = newSet(keys);for (const k of expected.keys()) if (!pass.touched.has(k)) expect(got.has(k), `${k} stayed in the pass and came`).toBe(true);}describe("a pass from nothing carries its small tables first", () => {const SEEDS = Array.from({ length: 12 }, (_, i) => i + 1); it("picks the small tables by their rows in the pass, the window and tombstones counted, the fewest first, then by name", async () => {await withStore("sync-order-plan", (store) => {const { upto } = build(store, 99);const scope: SyncScope = { kind: "all", except: newSet([INTERNAL]) };const windows: SyncWindow[] = [{ table: WINDOWED, column: "sent_at", from: FROM }];const counts = newMap<string, number>();for (const row of before(store, upto).values()) counts.set(row.table, (counts.get(row.table) ?? 0) + 1);const want = [...counts].filter(([, n]) => n <= MOST).sort(([a, x], [b, y]) => x - y || a.localeCompare(b)).map(([t]) => t); expect(store.smallFirst({ since: 0, upto, scope, windows, most: MOST }), "the owner's plan, from row_counts").toEqual(want); expect(want).toContain(WINDOWED); expect(want).not.toContain(INTERNAL); expect(want.indexOf("t03"), "a tie goes by name").toBe(want.indexOf("t04") - 1); expect(want.some((t) => counts.get(t)! > MOST)).toBe(false); expect([...counts.keys()].filter((t) => !want.includes(t)).length, "the big tables are left to after").toBeGreaterThan(0);// A narrower scope counts in SQL and says the same of the same rows.const tables: SyncScope = { kind: "tables", whole: newSet(counts.keys()), own: newSet(), person: null, except: newSet([INTERNAL]) }; expect(store.smallFirst({ since: 0, upto, scope: tables, windows, most: MOST })).toEqual(want); }); }); it("counts an owner's tables= pass from row_counts, never a scan of rows, and says what a scan says (launch-fast)", async () => {await withStore("sync-order-owner-tables", (store) => {const { upto } = build(store, 7);const windows: SyncWindow[] = [{ table: WINDOWED, column: "sent_at", from: FROM }];const named = newSet([...newSet(all(store).map((r) => r.table))].filter((t) => t !== INTERNAL).slice(0, 5));const owner: SyncScope = { kind: "tables", whole: named, own: newSet(), person: null, except: newSet([INTERNAL]) };// The same rows, under a scope only SQL can count: a member who owns no rows of their own.const member: SyncScope = { ...owner, person: "member-invented" };// `row_counts` is counted once by the definitions' date columns, in steps (the alarm's); every pass after reads it.while (store.carryCounts(1000));const sql = (store as unknown as { sql: SqlStorage }).sql;const asked: string[] = [];const exec = sql.exec.bind(sql); (sql as unknown as { exec: typeof sql.exec }).exec = ((query: string, ...args: SqlStorageValue[]) => { asked.push(query);return exec(query, ...args); }) astypeof sql.exec;try {for (const since of [0, Math.floor(upto / 2)]) { asked.length = 0;const counts = store.syncCounts({ since, upto, scope: owner, windows });const tables = store.passTables({ since, upto, scope: owner, windows });if (since === 0) expect(asked.filter((q) => /FROM rows WHERE/.test(q)), `no scan of rows from nothing: ${asked.join(" | ")}`).toEqual([]); expect(asked.some((q) => /FROM row_counts/.test(q)), "row_counts is read").toBe(true); expect(asked.filter((q) => /SUM\(deleted = 0\) AS total/.test(q)), "the total is never a scan").toEqual([]); expect(counts).toEqual(store.syncCounts({ since, upto, scope: member, windows })); expect(tables).toEqual(store.passTables({ since, upto, scope: member, windows })); } } finally { (sql as unknown as { exec: typeof sql.exec }).exec = exec; } }); }); it("orders, resumes from its cursor alone, and neither repeats nor skips a row, over many seeds and page sizes", async () => {for (const seed of SEEDS) {await withStore(`sync-order-${seed}`, (store) => {const { upto } = build(store, seed);const expected = before(store, upto);const pass = pull(store, seed, upto, { bridgeAt: null }); noneTwiceNoneSkipped(pass, expected);// Small tables whole, one after another in the plan's order, then the big ones in change order.const small = newSet(pass.small);const firstBig = pass.carried.findIndex((r) => !small.has(r.table));const head = firstBig < 0 ? pass.carried : pass.carried.slice(0, firstBig);const tail = firstBig < 0 ? [] : pass.carried.slice(firstBig); expect(tail.some((r) => small.has(r.table)), `seed ${seed}: no small row after a big one`).toBe(false);const runs = head.map((r) => r.table).filter((t, i, ts) => i === 0 || ts[i - 1] !== t); expect(runs, `seed ${seed}: each small table whole, in the plan's order`).toEqual(pass.small.filter((t) => runs.includes(t)));for (const t of runs) {const ids = head.filter((r) => r.table === t).map((r) => r.id); expect(ids).toEqual([...ids].sort((a, b) => (a < b ? -1 : 1))); }const order = tail.map((r) => [r.version, r.table, r.id] asconst);for (let i = 1; i < order.length; i++) {const [a, b] = [order[i - 1]!, order[i]!]; expect(a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || (a[1] === b[1] && a[2] < b[2]))), `seed ${seed}: the big tables come in change order`).toBe(true); } }); } }); it("takes a cursor made in change order (THE ONE BRIDGE) and goes on small tables first from where it got to, nothing twice, nothing skipped", async () => {for (const seed of SEEDS) {await withStore(`sync-order-bridge-${seed}`, (store) => {const { upto } = build(store, seed + 1000);const expected = before(store, upto);const pass = pull(store, seed + 1000, upto, { bridgeAt: 1 + (seed % 3) }); noneTwiceNoneSkipped(pass, expected); }); } });});