import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { Store, type SyncScope } from "../src/store.ts"; import { BIG, personalShape, watchStatements, writeShape, type Shape } from "./big_object.ts"; /** * THE RECOUNT OF ROW_COUNTS ON A VERY LARGE OBJECT (live, 21 Nov 2026: one * GROUP BY over every row of a table ran out of SQLite's memory on the * personal object, and every sync answered 500 for hours). A recount now * walks each table along its primary key in steps of `recountChunk` rows, * its place in meta, so no statement reads more than a step's rows, a step * can be the last thing a request does and the next request goes on, writes * between steps are counted once, and only a table whose date column changed * is counted again. * * The normal suite builds the invented object at 1/40 of the personal one * (about 20,000 rows); `BIG_OBJECT=1 npx vitest run test/row-counts-big.test.ts` * builds it whole (about 800,000 rows, 1.4 GB), each request there a step of the alarm, timed. */ const SCALE = BIG ? 1 : 1 / 40; const CHUNK = BIG ? 500 : 250; const NOW = new Date("2026-11-21T10:00:00Z"); const dates = (shape: Shape[]): Map => new Map(shape.filter((t) => t.dated).map((t) => [t.table, t.dated!])); /** One request's store, as the object makes it: the definitions' date columns given, the step lowered for the test's scale. */ function storeOf(sql: SqlStorage, columns: Map): Store { const store = new Store(sql, () => NOW); store.setDateColumns(columns); store.recountChunk = CHUNK; return store; } /** What `row_counts` must hold, counted the old way (one GROUP BY: the test may, the object never does). */ function truth(sql: SqlStorage, columns: Map): Record { const out: Record = {}; for (const r of sql.exec<{ table_id: string; deleted: number; n: number }>("SELECT table_id, deleted, COUNT(*) AS n FROM rows GROUP BY table_id, deleted")) { out[`${r.table_id}|${r.deleted}|*`] = Number(r.n); } for (const [table, column] of columns) { for (const r of sql.exec<{ day: string; n: number }>(`SELECT substr(json_extract(data, '$."${column}"'), 1, 10) AS day, COUNT(*) AS n FROM rows WHERE table_id = ? AND deleted = 0 AND json_type(data, '$."${column}"') = 'text' AND json_extract(data, '$."${column}"') <> '' GROUP BY day`, table)) { out[`${table}|0|${r.day}`] = Number(r.n); } } return out; } /** `row_counts` read back the same way as `truth`. */ function held(sql: SqlStorage, columns: Map): Record { const out: Record = {}; for (const r of sql.exec<{ table_id: string; deleted: number; n: number }>("SELECT table_id, deleted, SUM(n) AS n FROM row_counts GROUP BY table_id, deleted")) { if (Number(r.n) !== 0) out[`${r.table_id}|${r.deleted}|*`] = Number(r.n); } for (const [table] of columns) { for (const r of sql.exec<{ day: string; n: number }>("SELECT day, n FROM row_counts WHERE table_id = ? AND deleted = 0 AND day NOT IN ('', '0')", table)) { if (Number(r.n) !== 0) out[`${table}|0|${r.day}`] = Number(r.n); } } return out; } const pending = (store: Store): boolean => store.countsPending(); const owner: SyncScope = { kind: "all", except: new Set() }; describe("row_counts on a very large object", () => { it(`counts every table again in steps of ${CHUNK} rows across requests, none reading more, writes between steps counted once`, async () => { const stub = env.BUSINESS.get(env.BUSINESS.idFromName("row-counts-big")); await runInDurableObject(stub, (_instance, state) => { const sql = state.storage.sql; const shape = personalShape(SCALE); let version = writeShape(sql, shape); const columns = dates(shape); const total = shape.reduce((n, t) => n + t.rows, 0); // The state the live object was left in: an old basis in meta, its counts half deleted by a recount that ran out of memory. sql.exec("INSERT INTO meta (key, value) VALUES ('row_counts_by', '{}') ON CONFLICT (key) DO UPDATE SET value = excluded.value"); sql.exec("INSERT INTO row_counts (table_id, day, deleted, n) VALUES ('message', '', 0, 17)"); let requests = 0; let most = 0; let mostQuery = ""; let slowest = 0; for (; requests < 10_000; requests++) { // A request: a fresh store, a pass that counts its figures (in SQL while the recount runs, carrying it one step). // At full size every 25th request is a pass (each counts the whole object in SQL); the rest are the alarm's single steps, timed. const store = storeOf(sql, columns); const t = Date.now(); const { result, statements } = watchStatements(sql, () => (BIG && requests % 25 ? store.carryCounts(1) : store.syncCounts({ since: 0, upto: version, scope: owner, windows: [] }))); if (BIG && requests % 25) slowest = Math.max(slowest, Date.now() - t); if (typeof result === "object") expect(result.total, "the pass is counted either way").toBeGreaterThan(0); // Every statement that reads `rows` is a step's, a seek, or the pass's own count in SQL (the old way, until the recount ends). // (Since SLOW READ, 26 Nov 2026, the count in SQL is of the tables still queued alone: `AS live, COUNT(*) AS "all"`; here every table is.) for (const s of statements) if (/FROM rows /.test(s.query) && !/SUM\(deleted = 0\) AS (total|live)/.test(s.query) && !/COUNT\(\*\) AS n FROM rows WHERE table_id = \? AND version <= \?/.test(s.query) && s.rowsRead > most) [most, mostQuery] = [s.rowsRead, s.query]; if (!pending(store)) break; // Between requests a phone writes: a row the walk passed, one it has not reached, one revived, one tombstoned. const writer = storeOf(sql, columns); const pick = (table: string, i: number): string => `${table}-${String(1 + ((requests * 7919 + i * 104_729) % shape.find((t) => t.table === table)!.rows)).padStart(8, "0")}`; for (const [i, table] of ["message", "email", "photo", "person_handle"].entries()) { const row = writer.any(table, pick(table, i)); if (!row) continue; version += 1; if (row.deleted) writer.insert(table, row.id, { sent_at: "2026-11-21T09:00:00Z", received_at: "2026-11-21", taken_at: "2026-11-20" }, null, version); else if (requests % 3 === 0) writer.tombstone(row, version); else writer.update(row, { ...row.data, sent_at: "2026-11-21T09:00:00Z", taken_at: "" }, null, version); } version += 1; writer.insert("message", `message-new-${requests}`, { sent_at: "2026-11-21T09:30:00Z" }, null, version); } expect(pending(storeOf(sql, columns)), "the recount ends").toBe(false); expect(requests, "in about the steps its rows need").toBeLessThanOrEqual(Math.ceil(total / CHUNK) + shape.length + 2 + (BIG ? Math.ceil(total / CHUNK / 24) : 0)); expect(most, `no statement reads more than a step's rows (and the seek past it): ${mostQuery}`).toBeLessThanOrEqual(CHUNK + 1); if (BIG) console.log(`row_counts recount: ${total} rows in ${requests} requests, the slowest step ${slowest} ms (steps of ${CHUNK})`); expect(held(sql, columns)).toEqual(truth(sql, columns)); // Counted, the pass reads row_counts and never a row. const store = storeOf(sql, columns); const { result, statements } = watchStatements(sql, () => store.syncCounts({ since: 0, upto: version, scope: owner, windows: [{ table: "message", column: "sent_at", from: "2026-01-01" }] })); expect(statements.filter((s) => /FROM rows/.test(s.query)), "no row read").toEqual([]); const sqlStore = storeOf(sql, columns); const member: SyncScope = { kind: "tables", whole: new Set(shape.map((t) => t.table)), own: new Set(), person: "member-invented", except: new Set() }; expect(result).toEqual(sqlStore.syncCounts({ since: 0, upto: version, scope: member, windows: [{ table: "message", column: "sent_at", from: "2026-01-01" }] })); }); }, 3_000_000); it("counts again only the table whose date column changed, and folds a table that lost its date without reading a row", async () => { const stub = env.BUSINESS.get(env.BUSINESS.idFromName("row-counts-basis")); await runInDurableObject(stub, (_instance, state) => { const sql = state.storage.sql; const shape = personalShape(SCALE / 4); writeShape(sql, shape); const before = dates(shape); while (storeOf(sql, before).carryCounts(1000)); expect(held(sql, before)).toEqual(truth(sql, before)); // The kit gains a dated table (person_handle by `verified_at`, none of whose rows carry it) and `event` loses its date. const after = new Map(before); after.set("person_handle", "verified_at"); after.delete("event"); const store = storeOf(sql, after); const { statements } = watchStatements(sql, () => store.carryCounts(0)); const plan = JSON.parse(store.meta("row_counts_plan")!) as { queue: { table: string }[] }; expect(plan.queue.map((q) => q.table), "only person_handle is counted again").toEqual(["person_handle"]); expect(statements.reduce((n, s) => n + (/FROM rows/.test(s.query) ? s.rowsRead : 0), 0), "event folds from its counts, person_handle is only queued").toBeLessThanOrEqual(2); while (storeOf(sql, after).carryCounts(1000)); expect(held(sql, after)).toEqual(truth(sql, after)); // Every other table's counts stood: the message table was never read again. const again = watchStatements(sql, () => storeOf(sql, after).syncCounts({ since: 0, upto: 1e9, scope: owner, windows: [] })); expect(again.statements.filter((s) => /FROM rows/.test(s.query))).toEqual([]); }); }, 600_000); });