import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { declarations, FIRST, planFirst, typeFirstDecl } from"../src/first.ts";import { Store, typeFirstAt, typeFirstPlan, typeStoredRow, typeSyncScope, typeSyncWindow } from"../src/store.ts";import { BIG, personalShape, watchStatements, writeShape } from"./big_object.ts";/** * COMMS' FIRST PULL WITH MAIL BESIDE ITS CHATS (MAIL.md, 21 Nov 2026): "it must * not slow chats arriving". The invented object of the personal one's shape * (test/big_object.ts) with its chats made real, as sync-first-big's, and * 110,000 invented emails in 80,000 conversations of mail beside them, every * mail row sealed with a 3,000-byte body as the object holds it. A phone pulls * Comms' tables from nothing, page by page, three ways: * * without mail Comms' tables before mail joined (the time to beat); * mail, not late mail declared as the chats are, with no `late`; * mail, late Comms' order as the Worker serves its builds that pull mail * (src/first.ts FIRST, OLD_COMMS_FIRST). * * Measured: rows, pages and milliseconds of the object's own work until the 20 * most recent chats' newest 50 messages are all on the phone, and until the * newest 500 conversations of mail and their newest 2 messages are; and the * whole pass. Printed (`--disableConsoleIntercept`); `BIG_OBJECT=1` runs it at * full size. */const SCALE = BIG ? 1 : 1 / 40;const CHATS = BIG ? 3000 : 120;const EMAILS = Math.round(110_000 * SCALE);const MAIL_THREADS = Math.round(80_000 * SCALE);const NEWEST = 50;const RECENT = 20;const MAIL_FIRST = 500;const MAIL_ROWS = 2;/** Minutes between emails: 110,000 of them over about twelve years, ending on the day the store says it is. */const STEP = Math.round(57 / SCALE);const END = "2026-11-21T09:00:00Z";const WINDOW_FROM = "2026-08-23";describe("Comms' first pull with mail beside its chats, on a very large object", () => { it("brings every recent chat's newest messages as soon with mail as without it", async () => {const stub = env.BUSINESS.get(env.BUSINESS.idFromName("sync-mail-big"));await runInDurableObject(stub, (_instance, state) => {const sql = state.storage.sql;const shape = personalShape(SCALE).filter((t) => t.table !== "thread" && t.table !== "email");let upto = writeShape(sql, shape);const messages = shape.find((t) => t.table === "message")!.rows; sql.exec(`UPDATE rows SET data = json_set(data, '$.thread_id', printf('thread-%05d', 1 + CAST(substr(id, 9) AS INTEGER) % ?), '$.sent_at', strftime('%Y-%m-%dT%H:%M:%SZ', '2024-01-01', '+' || CAST(substr(id, 9) AS INTEGER) || ' minutes')) WHERE table_id = 'message' AND deleted = 0`, CHATS, ); sql.exec(`WITH RECURSIVE c(t) AS (SELECT 1 UNION ALL SELECT t + 1 FROM c WHERE t < ?) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT 'thread', printf('thread-%05d', t), json_object('last_message_at', strftime('%Y-%m-%dT%H:%M:%SZ', '2024-01-01', '+' || (? - ((? - (t - 1)) % ?)) || ' minutes'), 'sealed_enc', 's1:' || hex(randomblob(100)), 'dek_enc', 'd1:x', 'seal_v', 1), NULL, ? + t, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, CHATS, messages, messages, CHATS, upto, ); upto += CHATS;// The mail: email x (1…EMAILS) is in conversation 1 + (x - 1) % MAIL_THREADS, sent 3x minutes after the start (so// mail spans the chats' years); a conversation's last_at is its newest email's. Written after the chats, as mail// the Mac reads lands, and as rows of the object's sealed tables: clear columns, the sealed block and its key.for (let start = 1; start <= EMAILS; start += 10_000) { sql.exec(`WITH RECURSIVE c(x) AS (SELECT ? UNION ALL SELECT x + 1 FROM c WHERE x < ?) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT 'email', printf('email-%07d', x), json_object('thread_id', printf('mail-%06d', 1 + (x - 1) % ?), 'sent_at', strftime('%Y-%m-%dT%H:%M:%SZ', ?, '-' || ((? - x) * ?) || ' minutes'), 'trashed_at', NULL, 'sealed_enc', 's1:' || hex(randomblob(1500)), 'dek_enc', 'd1:' || hex(randomblob(30)), 'seal_v', 1), NULL, ? + x, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, start,Math.min(EMAILS, start + 9_999), MAIL_THREADS, END, EMAILS, STEP, upto, ); } upto += EMAILS; sql.exec(`WITH RECURSIVE c(t) AS (SELECT 1 UNION ALL SELECT t + 1 FROM c WHERE t < ?) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT 'email_thread', printf('mail-%06d', t), json_object('last_at', strftime('%Y-%m-%dT%H:%M:%SZ', ?, '-' || ((? - (CASE WHEN t + ? <= ? THEN t + ? ELSE t END)) * ?) || ' minutes'), 'first_at', strftime('%Y-%m-%dT%H:%M:%SZ', ?, '-' || ((? - t) * ?) || ' minutes'), 'sender_kind', CASE WHEN t % 9 = 0 THEN 'person' ELSE 'service' END, 'sealed_enc', 's1:' || hex(randomblob(150)), 'dek_enc', 'd1:x', 'seal_v', 1), NULL, ? + t, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, MAIL_THREADS, END, EMAILS, MAIL_THREADS, EMAILS, MAIL_THREADS, STEP, END, EMAILS, STEP, upto, ); upto += MAIL_THREADS;const total = Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows").one().n);const store = newStore(sql, () => newDate("2026-11-21T10:00:00Z")); store.setDateColumns(newMap([...shape.filter((t) => t.dated).map((t) => [t.table, t.dated!] as [string, string]), ["email", "sent_at"], ["email_thread", "last_at"]]));while (store.carryCounts(10_000));const chatTables = ["thread", "message", "message_contact_handle", ...shape.filter((t) => t.table.startsWith("small_")).slice(0, 6).map((t) => t.table)];const mailTables = ["email_thread", "email"];// What the phone waits for: the 20 most recent chats' newest 50 messages; the newest 500 conversations of mail and their newest 2.const recent = sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'thread' ORDER BY json_extract(data, '$.last_message_at') DESC, id DESC LIMIT ?", RECENT).toArray().map((r) => r.id);const chatsWanted = newSet<string>();for (const t of recent) for (const r of sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.thread_id') = ? ORDER BY json_extract(data, '$.sent_at') DESC, id DESC LIMIT ?", t, NEWEST)) chatsWanted.add(`message/${r.id}`);const mailWanted = newSet<string>();for (const t of sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'email_thread' ORDER BY json_extract(data, '$.last_at') DESC, id DESC LIMIT ?", MAIL_FIRST).toArray()) { mailWanted.add(`email_thread/${t.id}`);for (const r of sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'email' AND json_extract(data, '$.thread_id') = ? ORDER BY json_extract(data, '$.sent_at') DESC, id DESC LIMIT ?", t.id, MAIL_ROWS)) mailWanted.add(`email/${r.id}`); }// Of those, what a 90-day window holds: what the windowed pass waits for.const inWindow = newSet<string>();for (const k of mailWanted) {const [table, id] = k.split("/") as [string, string];const at = sql.exec<{ at: string }>(`SELECT json_extract(data, '$.${table === "email" ? "sent_at" : "last_at"}') AS at FROM rows WHERE table_id = ? AND id = ?`, table, id).one().at;if (at >= WINDOW_FROM) inWindow.add(k); }typeUntil = { rows: number; pages: number; ms: number; bytes: number };typeRun = { chats: Until; mail: Until | null; rows: number; pages: number; ms: number; bytes: number };const pass = (name: string, tables: string[], decls: Map<string, FirstDecl>, windows: SyncWindow[] = [], mailWant: Set<string> = mailWanted): Run => {const scope: SyncScope = { kind: "tables", whole: newSet(tables), own: newSet(), person: null, except: newSet() };const counts = store.passTables({ since: 0, upto, scope, windows });const planned = planFirst((t) => counts.get(t) ?? 0, "2026-11-21", 10_000, decls);// Past ORDER_INDEX_MAX_BYTES (his object; this one at full size) no order index is made: ORDER INDEX's// shadows stand in, filled a bounded step at a time as the alarm fills them, and the pass walks them.if (!store.firstIndexes(planned).length || store.firstIndexes(planned).length < planned.length) { store.setShadows(true); store.firstIndexes(planned);while (store.shadowStep()); }const specs = store.firstIndexes(planned); expect(specs.length, "every first table stands, by its index or its shadow").toBe(planned.length); store.firstPass(name, 1, 0);const small = store.smallFirst({ since: 0, upto, scope, windows, most: 10_000 });let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass: name, small: small.filter((t) => !specs.some((s) => s.table === t)), specs, cuts: specs.map(() => null) }, at: null };const run: Run = { chats: { rows: 0, pages: 0, ms: 0, bytes: 0 }, mail: null, rows: 0, pages: 0, ms: 0, bytes: 0 };const chatsLeft = newSet(chatsWanted);const mailLeft = newSet(tables.includes("email") ? mailWant : []);const begun = Date.now();for (let more = true; more; ) {const { result } = watchStatements(sql, () => store.firstPage({ since: 0, upto, limit: run.pages === 0 ? 200 : 5000, scope, windows, ...cursor })); cursor = JSON.parse(JSON.stringify({ plan: result.plan, at: result.at })) astypeof cursor; run.pages++; result.rows.forEach((r: StoredRow, i) => {const k = `${r.table}/${r.id}`;const bytes = JSON.stringify(r.data).length; run.bytes += bytes;if (chatsLeft.delete(k) && chatsLeft.size === 0) Object.assign(run.chats, { rows: run.rows + i + 1, pages: run.pages, ms: Date.now() - begun, bytes: run.bytes });if (mailLeft.delete(k) && mailLeft.size === 0) run.mail = { rows: run.rows + i + 1, pages: run.pages, ms: Date.now() - begun, bytes: run.bytes }; }); run.rows += result.rows.length; more = result.more; } run.ms = Date.now() - begun;return run; };const comms = FIRST;const withoutMail = newMap([...comms].filter(([t]) => !mailTables.includes(t)));const notLate = declarations({ comms: { first: Object.fromEntries([...comms].map(([t, d]) => [t, { ...d, late: undefined }])) } }); expect(comms.get("email_thread")?.late, "Comms' kit names mail late").toBe(true); expect(comms.get("email")?.per, "Comms' kit groups mail by its conversation").toBe("thread_id");const before = pass("without", chatTables, withoutMail);const naive = pass("not-late", [...chatTables, ...mailTables], notLate);const unbounded = pass("late", [...chatTables, ...mailTables], comms);// As Comms builds before COMMS WITHOUT MAIL keep it: 90 days of mail (the window the phone sends), what is older left// on the object (`GET /v1/older`, `GET /v1/blind`). Their mail order is the Worker's still (OLD_COMMS_FIRST).const windows: SyncWindow[] = [{ table: "email", column: "sent_at", from: WINDOW_FROM }, { table: "email_thread", column: "last_at", from: WINDOW_FROM }];const windowed = sql.exec<{ e: number; t: number }>("SELECT (SELECT COUNT(*) FROM rows WHERE table_id = 'email' AND json_extract(data, '$.sent_at') >= ?) AS e, (SELECT COUNT(*) FROM rows WHERE table_id = 'email_thread' AND json_extract(data, '$.last_at') >= ?) AS t", WINDOW_FROM, WINDOW_FROM).one();const after = pass("windowed", [...chatTables, ...mailTables], comms, windows, inWindow);const mb = (n: number): string => `${(n / 1e6).toFixed(1)} MB`;const until = (u: Until | null): string => (u ? `${String(u.rows).padStart(8)} rows ${String(u.pages).padStart(4)} pages ${String(u.ms).padStart(6)} ms ${mb(u.bytes).padStart(9)}` : "-".padStart(46));const line = (name: string, r: Run): string => `${name.padEnd(15)} chats ${until(r.chats)} | mail ${until(r.mail)} | whole ${r.rows} rows ${r.pages} pages ${r.ms} ms ${mb(r.bytes)}`; console.log(`\nthe invented object: ${total} rows; ${messages} messages in ${CHATS} chats; ${EMAILS} emails in ${MAIL_THREADS} conversations of mail\n` +`until the ${RECENT} recent chats' newest ${NEWEST} (${chatsWanted.size} messages), and the newest ${MAIL_FIRST} mail conversations and their newest ${MAIL_ROWS} (${mailWanted.size} rows):\n` +`${line("without mail", before)}\n${line("mail, not late", naive)}\n${line("mail, late", unbounded)}\n${line("90 days, late", after)}\n` +`90 days hold ${windowed.e} emails in ${windowed.t} conversations of mail`, ); expect(after.chats.rows, "the recent chats' newest messages come after as many rows as without mail").toBe(before.chats.rows); expect(after.chats.pages).toBe(before.chats.pages); expect(naive.chats.rows, "without late, mail comes first and the chats wait").toBeGreaterThan(before.chats.rows); expect(after.mail, "the newest mail comes in the first pull").not.toBeNull(); expect(unbounded.rows).toBe(before.rows + EMAILS + MAIL_THREADS); expect(after.rows, "a window's worth of mail, nothing older").toBe(before.rows + windowed.e + windowed.t); }); }, 3_000_000);});