import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { declarations, FIRST, planFirst } from "../src/first.ts"; import { KITS } from "../src/kits.ts"; import type { SyncAnswer } from "../src/protocol.ts"; import { http, NOTES_OPEN, PEOPLE_OPEN, personalObject, put } from "./personal.ts"; import { Store, type Cursor, type FirstAt, type FirstPlan, type StoredRow, type SyncScope, type SyncWindow } from "../src/store.ts"; /** * RULE (owner, 21 Nov 2026): a first pull gives each app what a person looks * at first before the long tail. Chat: every chat's row and its newest * messages, the most recent chats first, then the rest newest to oldest; * Notes: the list newest first; Days: the days around today; Story: the * script last opened. A kit declares it per table (src/first.ts). * * An invented object of chats, notes, days and other tables, tombstones * among them, is pulled page by page from the cursor alone (through JSON) * while rows are written, deleted and added between pages. Every seed must * carry each row of the pass at most once, every row that stayed in the pass * exactly once, and each run in its order. */ 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 TODAY = "2026-11-21"; const N = 5; const WINDOWED = "chat_line"; const FROM = "2026-03-01"; const DECLS = declarations({ test: { first: { thread: { by: "last_message_at", unless: ["trashed_at"] }, message: { by: "sent_at", per: "thread_id", of: "thread", rows: N, early: 2 }, note: { by: "updated_at", unless: ["archived_at"], rows: 12 }, event: { by: "starts_at", around: [2, 3] }, scene: { by: "position", order: "asc", per: "story", of: "story", groups: 1 }, story: { by: "chosen_at" }, }, }, }); const key = (r: { table: string; id: string }): string => `${r.table}/${r.id}`; const day = (n: number): string => new Date(Date.UTC(2026, 10, 21) + n * 86_400_000).toISOString().slice(0, 10); function build(store: Store, seed: number): { upto: number } { const next = rng(seed); const pick = (n: number): number => Math.floor(next() * n); let version = 0; const written: StoredRow[] = []; const write = (table: string, id: string, data: Record): void => { version += pick(3) === 0 ? 0 : 1 + pick(2); written.push(store.insert(table, id, data, null, Math.max(1, version))); }; const threads = 6 + pick(8); for (let t = 0; t < threads; t++) write("thread", `th-${t}`, { last_message_at: `2026-${String(1 + pick(11)).padStart(2, "0")}-${String(1 + pick(28)).padStart(2, "0")}T00:00:00Z`, ...(pick(6) === 0 ? { trashed_at: "2026-11-01" } : {}) }); const messages = 40 + pick(120); for (let m = 0; m < messages; m++) { const sent = `2026-${String(1 + pick(11)).padStart(2, "0")}-${String(1 + pick(28)).padStart(2, "0")}T${String(pick(24)).padStart(2, "0")}:00:00Z`; // Some messages share a moment, some name a chat the object does not hold, some have no time. write("message", `m-${String(pick(1e6)).padStart(6, "0")}-${m}`, { thread_id: pick(15) === 0 ? "th-gone" : `th-${pick(threads)}`, ...(pick(20) === 0 ? {} : { sent_at: pick(8) === 0 ? "2026-05-05T05:00:00Z" : sent }) }); } for (let n = 0; n < 20 + pick(20); n++) write("note", `n-${n}`, { updated_at: day(-pick(300)), ...(pick(4) === 0 ? { archived_at: "2026-10-01" } : {}) }); for (let e = 0; e < 15 + pick(30); e++) write("event", `e-${e}`, { starts_at: `${day(pick(40) - 20)}T09:00:00Z` }); for (let s = 0; s < 3; s++) write("story", `s-${s}`, { chosen_at: `2026-11-0${1 + s}` }); for (let c = 0; c < 10 + pick(20); c++) write("scene", `sc-${c}`, { story: `s-${pick(3)}`, position: pick(30) }); for (const table of ["person", "todo", "bulk"]) for (let r = 0; r < (table === "bulk" ? 60 : 8); r++) write(table, `${table}-${r}`, { n: r }); for (let n = 0; n < 30; n++) write(WINDOWED, `cl-${n}`, { sent_at: n < 20 ? "2026-01-01T00:00:00Z" : "2026-10-20T00:00:00Z" }); written.sort(() => next() - 0.5); for (const row of written.slice(0, Math.floor(written.length / 4))) { version += 1; if (pick(4) === 0) store.tombstone(row, version); else store.update(row, { ...row.data, again: true }, null, version); } return { upto: version }; } 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: new Set() }, 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 }; } } const inPass = (row: StoredRow, upto: number): boolean => row.version <= upto && !(row.table === WINDOWED && !row.deleted && String(row.data.sent_at) < FROM); type Pass = { carried: StoredRow[]; touched: Set; plan: FirstPlan; pages: number }; function pull(store: Store, seed: number, upto: number, scope: SyncScope): Pass { const next = rng(seed * 31 + 7); const windows: SyncWindow[] = [{ table: WINDOWED, column: "sent_at", from: FROM }]; const limit = 1 + Math.floor(next() * 25); const held = new Map(); for (const r of all(store).filter((r) => inPass(r, upto))) held.set(r.table, (held.get(r.table) ?? 0) + 1); const specs = planFirst((t) => held.get(t) ?? 0, TODAY, 10, DECLS); store.firstIndexes(specs); store.firstPass(`pass-${seed}`, 1000, 0); const small = store.smallFirst({ since: 0, upto, scope, windows, most: 10 }).filter((t) => !specs.some((s) => s.table === t)); let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass: `pass-${seed}`, small, specs, cuts: specs.map(() => null) }, at: null }; const plan = cursor.plan; const carried: StoredRow[] = []; const touched = new Set(); let version = upto + 1000; let pages = 0; for (;;) { pages++; const got = store.firstPage({ since: 0, upto, limit, scope, windows, ...cursor }); expect(got.rows.length).toBeLessThanOrEqual(limit); carried.push(...got.rows); if (!got.more) break; cursor = JSON.parse(JSON.stringify({ plan: got.plan, at: got.at })) as typeof cursor; // Between pages: rows written again, deleted, and new ones (each past `upto`, so for the next pass). for (const row of all(store)) { if (row.version > upto || next() >= 0.03) continue; version += 1; touched.add(key(row)); if (next() < 0.3) store.tombstone(row, version); else store.update(row, { ...row.data, mid: true, ...(row.table === "message" && next() < 0.5 ? { sent_at: "2026-12-31T00:00:00Z" } : {}) }, null, version); } if (next() < 0.3) store.insert("message", `m-new-${version}`, { thread_id: "th-0", sent_at: "2026-12-30T00:00:00Z" }, null, ++version); } return { carried, touched, plan, pages }; } async function withStore(name: string, run: (store: Store) => T): Promise { const stub = env.BUSINESS.get(env.BUSINESS.idFromName(name)); return runInDurableObject(stub, (_instance, state) => { const store = new Store(state.storage.sql, () => new Date("2026-11-21T10:00:00Z")); store.setDateColumns(new Map([[WINDOWED, "sent_at"]])); return run(store); }); } /** SQLite's order of a first order's value (`IFNULL(by, '')`): numbers before text, then the id. */ const sqlKey = (r: StoredRow, by: string): [number | string, string] => { const v = r.data[by]; return [v === undefined || v === null ? "" : (v as number | string), r.id]; }; const cmp = (by: string) => (a: StoredRow, b: StoredRow): number => { const [[x, i], [y, j]] = [sqlKey(a, by), sqlKey(b, by)]; if (typeof x !== typeof y) return typeof x === "number" ? -1 : 1; return x < y ? -1 : x > y ? 1 : i < j ? -1 : i > j ? 1 : 0; }; const ordered = (rows: StoredRow[], by: string, asc: boolean): boolean => rows.every((r, i) => i === 0 || (asc ? cmp(by)(rows[i - 1]!, r) < 0 : cmp(by)(rows[i - 1]!, r) > 0)); describe("a pass from nothing carries what each app shows first, then the long tail", () => { const SEEDS = Array.from({ length: 16 }, (_, i) => i + 1); const owner: SyncScope = { kind: "all", except: new Set() }; it("neither repeats nor skips a row, resumed from its cursor alone, while rows are written, deleted and added between pages", async () => { for (const seed of SEEDS) { await withStore(`sync-first-${seed}`, (store) => { const { upto } = build(store, seed); const expected = new Map(all(store).filter((r) => inPass(r, upto)).map((r) => [key(r), r])); const pass = pull(store, seed, upto, owner); const keys = pass.carried.map(key); expect(new Set(keys).size, `seed ${seed}: no row comes twice`).toBe(keys.length); for (const k of keys) expect(expected.has(k), `seed ${seed}: ${k} was in the pass`).toBe(true); const got = new Set(keys); for (const k of expected.keys()) if (!pass.touched.has(k)) expect(got.has(k), `seed ${seed}: ${k} stayed in the pass and came`).toBe(true); }); } }, 600_000); it("carries each run in its order: the chats' rows, the notes list and the days around today; the small tables; each chat's newest messages, most recent chat first; the rest; then the tail", async () => { for (const seed of SEEDS) { await withStore(`sync-first-order-${seed}`, (store) => { const { upto } = build(store, seed + 500); const held = new Map(all(store).filter((r) => r.version <= upto).map((r) => [key(r), r])); // A quiet pass, no writes between pages, so each run can be read whole; the writes are the test above's. const next = rng(seed); const limit = 1 + Math.floor(next() * 25); const specs = planFirst((t) => [...held.values()].filter((r) => r.table === t).length, TODAY, 10, DECLS); store.firstIndexes(specs); const small = store.smallFirst({ since: 0, upto, scope: owner, windows: [], most: 10 }).filter((t) => !specs.some((s) => s.table === t)); let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass: `order-${seed}`, small, specs, cuts: specs.map(() => null) }, at: null }; const carried: StoredRow[] = []; for (;;) { const got = store.firstPage({ since: 0, upto, limit, scope: owner, windows: [], ...cursor }); carried.push(...got.rows); if (!got.more) break; cursor = JSON.parse(JSON.stringify({ plan: got.plan, at: got.at })) as typeof cursor; } const twice = carried.map(key).filter((k, i, ks) => ks.indexOf(k) !== i); expect(twice.map((k) => `${k} ${JSON.stringify(held.get(k))}`), `seed ${seed}: nothing twice`).toEqual([]); expect(carried.length).toBe(held.size); const live = [...held.values()].filter((r) => !r.deleted); const desc = (by: string) => (a: StoredRow, b: StoredRow): number => -cmp(by)(a, b); // The lead: every chat's row newest first (not a trashed one), the 12 newest live notes not archived, the days around today. const threads = live.filter((r) => r.table === "thread" && !r.data.trashed_at).sort(desc("last_message_at")); const notes = live.filter((r) => r.table === "note" && !r.data.archived_at).sort(desc("updated_at")).slice(0, 12); const events = live.filter((r) => r.table === "event" && String(r.data.starts_at) >= day(-2) && String(r.data.starts_at) < day(4)).sort(desc("starts_at")); const stories = live.filter((r) => r.table === "story").sort(desc("chosen_at")); const leadOrder = specs.filter((s) => !s.per).map((s) => s.table); const lead = leadOrder.flatMap((t) => ({ event: events, note: notes, story: stories, thread: threads })[t as "event"] ?? []); expect(carried.slice(0, lead.length).map(key), `seed ${seed}: the lead`).toEqual(lead.map(key)); let at = lead.length; // Each chat's newest N, the chats newest first (every chat the pass holds, trashed too); the first story's scenes by // position. The first `early` groups of a spec come before the small tables, the others after. const early: StoredRow[] = []; const later: StoredRow[] = []; for (const sp of specs.filter((s) => s.per)) { const of = live.filter((r) => r.table === sp.per!.of).sort(desc(sp.per!.by)); (sp.per!.groups === null ? of : of.slice(0, sp.per!.groups)).forEach((g, n) => { const mine = live.filter((r) => r.table === sp.table && r.data[sp.per!.column] === g.id).sort(desc(sp.by)); if (sp.asc) mine.reverse(); (sp.per!.early !== null && n < sp.per!.early ? early : later).push(...(sp.rows === null ? mine : mine.slice(0, sp.rows))); }); } // The early groups in spec order, then the rest of the groups: the spec order is kept within each. const groups = [...early, ...later]; expect(carried.slice(at, at + early.length).map(key), `seed ${seed}: the early groups' first rows`).toEqual(early.map(key)); at += early.length; // The small tables whole, each by id. for (const t of small) { const rows = [...held.values()].filter((r) => r.table === t).sort((a, b) => (a.id < b.id ? -1 : 1)); expect(carried.slice(at, at + rows.length).map(key), `seed ${seed}: ${t} whole`).toEqual(rows.map(key)); at += rows.length; } expect(carried.slice(at, at + later.length).map(key), `seed ${seed}: each other group's first rows`).toEqual(later.map(key)); at += later.length; // Then each small spec's tail and rest; the others in change order; each other spec's tail, then its rest. const firstTables = new Set([...small, ...specs.map((s) => s.table)]); let rest = carried.slice(at); const sliced = (sp: (typeof specs)[number]): string[] => [...new Set(groups.filter((r) => r.table === sp.table).map((r) => String(r.data[sp.per!.column])))]; const runsBy = (rows: StoredRow[], column: string): StoredRow[][] => rows.reduce((out, r) => { const last = out[out.length - 1]; if (last && last[0]!.data[column] === r.data[column]) last.push(r); else out.push([r]); return out; }, []); const takeWhile = (ok: (r: StoredRow) => boolean): StoredRow[] => { const end = rest.findIndex((r) => !ok(r)); const run = rest.slice(0, end < 0 ? rest.length : end); rest = rest.slice(run.length); return run; }; const tails = (soon: boolean): void => { for (const sp of specs.filter((x) => x.soon === soon)) { if (!sp.per) { const run = takeWhile((r) => r.table === sp.table); expect(ordered(run, sp.by, sp.asc), `seed ${seed}: ${sp.table}'s tail in its order`).toBe(true); continue; } // Group by group, in the order the groups came first, each in its order. const came = sliced(sp); const runs = runsBy(takeWhile((r) => r.table === sp.table && came.includes(String(r.data[sp.per!.column]))), sp.per.column); for (const g of runs) expect(ordered(g, sp.by, sp.asc), `seed ${seed}: ${sp.table}'s tail of a group in its order`).toBe(true); expect(runs.map((g) => String(g[0]!.data[sp.per!.column])), `seed ${seed}: ${sp.table}'s tail, the groups in their order`).toEqual(came.filter((g) => runs.some((x) => String(x[0]!.data[sp.per!.column]) === g))); } // The rest: each grouped spec's rows of no group first, then every group that never came first. for (const sp of specs.filter((x) => x.per && x.soon === soon)) { const came = new Set(sliced(sp)); for (const g of runsBy(takeWhile((r) => r.table === sp.table), sp.per!.column)) { expect(ordered(g, sp.by, sp.asc)).toBe(true); expect(came.has(String(g[0]!.data[sp.per!.column])), `seed ${seed}: a group that came first has nothing left for the rest`).toBe(false); } } }; tails(true); const change = takeWhile((r) => !firstTables.has(r.table)); for (let i = 1; i < change.length; i++) expect(change[i - 1]!.version <= change[i]!.version, `seed ${seed}: change order`).toBe(true); tails(false); expect(rest.map(key), `seed ${seed}: nothing after the tails`).toEqual([]); }); } }, 600_000); it("keeps an app to its tables: Chat's pass carries only Chat's tables, its chats' rows first", async () => { await withStore("sync-first-chat", (store) => { const { upto } = build(store, 77); const chat: SyncScope = { kind: "tables", whole: new Set(["thread", "message", "person"]), own: new Set(), person: null, except: new Set() }; const pass = pull(store, 77, upto, chat); expect(new Set(pass.carried.map((r) => r.table))).toEqual(new Set(["thread", "message", "person"])); expect(pass.carried[0]!.table).toBe("thread"); }); }); }); describe("the kits' first orders", () => { it("are declared in Comms (its chats and mail), Words, Days, Story and Cinemas, each column one the object holds in the clear", () => { expect([...FIRST.keys()].sort()).toEqual(["email", "email_thread", "event", "film", "film_episode", "film_season", "message", "note", "story_line", "story_scene", "story_story", "thread", "todo", "watch"]); const tables = new Map(Object.values(KITS).flatMap((k) => k.tables).map((t) => [String(t.id), t])); for (const [table, d] of FIRST) { const t = tables.get(table)!; const seal = t.seal as { clear?: string[] } | undefined; const clear = new Set([...(seal?.clear ?? []), String(t.date ?? ""), String((t.sort as { column?: string } | undefined)?.column ?? "")]); for (const column of [d.by, ...(d.per ? [d.per] : []), ...(d.unless ?? [])]) expect(clear.has(column), `${table}.${column} is clear`).toBe(true); } }); // RULE (FIRST FILL, CONTRACT-2): a new phone's Cinemas pass carries his whole film table first (Home is cut from it), // then the 200 episodes watched most lately, the seasons whole; the plays wait behind everything. Tables other apps // share (the lists, people, photos) are not declared by Cinemas: their order is every app's, and they are small. it("carry Cinemas' films first, then lately watched episodes and the seasons, the plays last", () => { const held = new Map([["film", 2000], ["film_episode", 20000], ["film_season", 900], ["watch", 5000], ["person", 300]]); const specs = planFirst((t) => held.get(t) ?? 0, "2026-11-26", 1000, FIRST); expect(specs.map((s) => [s.table, s.by, s.rows, s.late])).toEqual([ ["film", "added_on", null, false], ["film_episode", "position_at", 200, false], ["film_season", "number", null, false], ["watch", "started_at", null, true], ]); expect(specs.find((s) => s.table === "film_season")!.soon, "the seasons stand whole as early as a small table").toBe(true); for (const shared of ["record_group", "group_member", "person", "photo", "media", "vault_key"]) expect(FIRST.has(shared), shared).toBe(false); }); it("refuse a declaration that does not read", () => { expect(() => declarations({ k: { first: { message: { by: "sent at" } } } })).toThrow(/by names a column/); expect(() => declarations({ k: { first: { message: { by: "sent_at", per: "thread_id" } } } })).toThrow(/per and of/); expect(() => declarations({ k: { first: { message: { by: "sent_at", per: "thread_id", of: "thread" } } } })).toThrow(/no kit orders/); expect(() => declarations({ a: { first: { note: { by: "updated_at" } } }, b: { first: { note: { by: "made_at" } } } })).toThrow(/otherwise/); }); it("let two kits differ in late alone, and keep the table late (Post and Comms both order mail, 25 Nov 2026)", () => { const either = (a: boolean, b: boolean) => declarations({ a: { first: { email_thread: { by: "last_at", rows: 500, ...(a ? { late: true } : {}) } } }, b: { first: { email_thread: { by: "last_at", rows: 500, ...(b ? { late: true } : {}) } } } }).get("email_thread"); expect(either(false, true)).toEqual({ by: "last_at", rows: 500, late: true }); expect(either(true, false)).toEqual({ by: "last_at", rows: 500, late: true }); expect(either(false, false)).toEqual({ by: "last_at", rows: 500 }); expect(() => declarations({ a: { first: { email_thread: { by: "last_at", rows: 500 } } }, b: { first: { email_thread: { by: "last_at", rows: 50, late: true } } } })).toThrow(/otherwise/); // Comms' mail stays behind its chats: in the builds before COMMS WITHOUT MAIL that still pull it (OLD_COMMS_FIRST). expect(FIRST.get("email")?.late).toBe(true); expect(FIRST.get("email_thread")?.late).toBe(true); }); }); describe("a phone of any build gets the first order from the Worker", () => { const SLUG = "sync-first-http"; const decode = (t: string): Record => JSON.parse(atob(t.replace(/-/g, "+").replace(/_/g, "/"))) as Record; const encode = (o: unknown): string => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); it("carries Notes' list newest first before the archived notes and the small tables, follows its cursor alone, and refuses a forged plan", async () => { const { credential } = await personalObject(SLUG, { open: [...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }); const auth = { authorization: `Bearer ${credential}` }; const notes = Array.from({ length: 30 }, (_, i) => ({ verb: "put", table: "note", id: `note-${String(i).padStart(2, "0")}`, data: { title: `Note ${i}`, body: "…", updated_at: `2026-${String(1 + (i % 11)).padStart(2, "0")}-${String(1 + i).padStart(2, "0")}`, ...(i % 3 === 0 ? { archived_at: "2026-11-01" } : {}) } })); await put(SLUG, notes); await put(SLUG, Array.from({ length: 4 }, (_, i) => ({ verb: "put", table: "person", id: `pp-${i}`, data: { full_name: `Person ${i}` } }))); const pages: SyncAnswer[] = []; for (let query = "since=0&tables=note,person&limit=6"; ; ) { const res = await http(SLUG, "GET", `/v1/sync?${query}`, undefined, auth); expect(res.status, JSON.stringify(res.body)).toBe(200); pages.push(res.body); if (!res.body.next) break; query = `cursor=${res.body.next}`; } const rows = pages.flatMap((p) => p.rows); expect(decode(pages[0]!.next!).first, "the cursor carries the plan").toBeTruthy(); const live = notes.filter((n) => !(n.data as { archived_at?: string }).archived_at).sort((a, b) => (a.data.updated_at < b.data.updated_at ? 1 : -1)); expect(rows.slice(0, live.length).map((r) => r.id), "the list newest first").toEqual(live.map((n) => n.id)); expect(new Set(rows.map((r) => `${r.table}/${r.id}`)).size, "nothing twice").toBe(rows.length); expect(rows.filter((r) => r.table === "note").length).toBe(30); expect(pages[pages.length - 1]!.done, "the last page says it whole").toBe(pages[0]!.total); for (const p of pages.slice(0, -1)) expect(p.done, "never whole before the end").toBeLessThan(p.total); // A cursor whose plan names a table as SQL is refused, never run. const made = decode(pages[0]!.next!); const plan = (made.first as { plan: { specs: { table: string }[] } }).plan; plan.specs[0]!.table = "note' OR 1=1 --"; const res = await http<{ error: string }>(SLUG, "GET", `/v1/sync?cursor=${encode(made)}`, undefined, auth); expect(res.status).toBe(400); }); });