Cotton code
166 lines · 9.8 KB · TypeScriptRaw
/** * MAIL SYNC BOUNDED (coordinator, 24 Nov 2026; SENDERS.md "all of his mail on the phone"): the phone takes the text of * all his mail, 111,422 sealed rows on his 3.7 GB object, with no window. A pass from nothing carries it behind the * chats (Comms' kit, `late`). Every page of that pass is held to the object's page bounds, by what it carries and by * what it reads, not only by its rows: some of his mails are long (a body of up to 65,536 characters), and a page of * 5,000 of those would be hundreds of MB built in one invocation. * * `BIG_OBJECT=1` runs it at full size; otherwise at a fortieth. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import commsKit from "../../../crates/cotton-core/kits/messages/kit.json";import { PAGE_BYTES, PAGE_READS } from "../src/store.ts";import { BIG, personalShape, writeShape } from "./big_object.ts";import { http, personalObject } from "./personal.ts";/** The tables Comms' kit syncs, as the phone names them in `tables=`. */const COMMS = (commsKit as { tables: string[] }).tables.map((t) => t.split("/")[1]!);const SCALE = BIG ? 1 : 1 / 40;const CHATS = BIG ? 3000 : 120;const EMAILS = Math.round(111_422 * SCALE);const MAIL_THREADS = Math.round(80_000 * SCALE);const STEP = Math.round(57 / SCALE);const END = "2026-11-21T09:00:00Z";/** One mail in this many is long: a sealed block of 60 KB, as a 30,000-character body seals to. */const LONG_EVERY = 100;const LONG_BYTES = 30_000;describe("all of his mail, from nothing, on a very large object", () => {  it("comes in pages each held to the page bounds, by bytes and by rows read, and every row arrives once", { timeout: 3_600_000 }, async () => {    const slug = "sync-mail-all-big";    const { credential } = await personalObject(slug);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    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(CASE WHEN x % ${LONG_EVERY} = 0 THEN ${LONG_BYTES} ELSE 1500 END)), '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;      sql.exec("UPDATE meta SET value = CAST(? AS TEXT) WHERE key = 'version'", upto);      // Drop any order index the shape's writes left (his object holds none: it is past ORDER_INDEX_MAX_BYTES).      for (const r of sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'rows_first_%'").toArray()) sql.exec(`DROP INDEX ${r.name}`);    });    // Its row counts counted, as on his object long since.    await runInDurableObject(stub, (instance) => {      const store = (instance as unknown as { store: { carryCounts(steps: number): boolean } }).store;      while (store.carryCounts(10_000));    });    // Every statement the object runs, with the rows it read (read inside the object, where the cursors live).    type Seen = { q: string; c: { rowsRead: number } }[];    const g = globalThis as unknown as { mailSeen: Seen };    g.mailSeen = [];    await runInDurableObject(stub, (_i, state) => {      const sql = state.storage.sql as unknown as { exec: (q: string, ...a: unknown[]) => { rowsRead: number } };      const real = sql.exec.bind(sql);      sql.exec = (q: string, ...a: unknown[]) => {        const c = real(q, ...a);        g.mailSeen.push({ q, c });        return c;      };    });    const phone = { authorization: `Bearer ${credential}` };    const seen = new Set<string>();    let pages = 0;    let twice = 0;    let longest = 0;    const worst = { bytes: 0, rows: 0, reads: 0, readsQ: "", ms: 0 };    let path = `/v1/sync?since=0&tables=${COMMS.join(",")}&limit=5000`;    for (;;) {      // The alarm's own work (the storage measure, the engines) is its own invocation with its own CPU: cleared before      // each page, so what is counted is the page's.      await runInDurableObject(stub, async (_i, state) => {        await state.storage.deleteAlarm();        g.mailSeen.length = 0;      });      const t0 = Date.now();      const page = await http<{ rows: { table: string; id: string; data?: unknown }[]; next?: string }>(slug, "GET", path, undefined, phone);      expect(page.status, JSON.stringify(page.body).slice(0, 300)).toBe(200);      const read = await runInDurableObject(stub, () => g.mailSeen.map((x) => ({ q: x.q, r: x.c.rowsRead })));      worst.ms = Math.max(worst.ms, Date.now() - t0);      pages++;      const reads = read.reduce((a, b) => a + b.r, 0);      let bytes = 0;      for (const r of page.body.rows) {        const k = `${r.table}/${r.id}`;        if (seen.has(k)) twice++;        seen.add(k);        const b = JSON.stringify(r.data ?? null).length;        bytes += b;        longest = Math.max(longest, b);      }      if (bytes > worst.bytes) Object.assign(worst, { bytes, rows: page.body.rows.length });      if (reads > worst.reads) {        const byQ = new Map<string, number>();        for (const x of read) byQ.set(x.q.replace(/\s+/g, " ").slice(0, 110), (byQ.get(x.q.replace(/\s+/g, " ").slice(0, 110)) ?? 0) + x.r);        Object.assign(worst, { reads, readsQ: `page ${pages}: ` + [...byQ.entries()].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([q, r]) => `${r} ${q}`).join(" | ") });      }      if (!page.body.next) break;      path = `/v1/sync?cursor=${encodeURIComponent(page.body.next)}`;      expect(pages, "the pass ends").toBeLessThan(5_000);    }    const want = await runInDurableObject(stub, (_i, state) => Number(state.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id IN (SELECT value FROM json_each(?))", JSON.stringify(COMMS)).one().n));    const size = await runInDurableObject(stub, (_i, state) => state.storage.sql.databaseSize);    const line = `all mail from nothing on ${(size / 1e6).toFixed(0)} MB (${EMAILS} emails, one in ${LONG_EVERY} long): ${seen.size} rows in ${pages} pages; largest page ${(worst.bytes / 1e6).toFixed(2)} MB (${worst.rows} rows), most rows one page read ${worst.reads} (${worst.readsQ}); slowest page ${worst.ms} ms`;    console.log(line);    if ((env as unknown as { SAY?: string }).SAY === "1") throw new Error(`SAY ${line}`);    expect(seen.size, "every row of the pass's tables, once").toBe(want);    expect(twice).toBe(0);    // A page carries PAGE_BYTES at most, past it by one row at most (a page holds at least one row).    expect(worst.bytes).toBeLessThanOrEqual(PAGE_BYTES + longest + 2);    // What a page reads goes with PAGE_READS, never with the file: where its walk stops (PAGE_READS entries), then    // the walk to there (each entry passed costs about three rows read), and its own rows and their lookups.    expect(worst.reads, line).toBeLessThanOrEqual(4 * PAGE_READS + 6 * 5_000);  });});