Cotton code
115 lines · 8.2 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { planFirst } from "../src/first.ts";import { Store, type FirstAt, type FirstPlan, type StoredRow, type SyncScope, type SyncWindow } from "../src/store.ts";import { BIG, personalShape, watchStatements, writeShape } from "./big_object.ts";/** * WORDS' FIRST PULL ON AN OBJECT AS LARGE AS THE OWNER'S (21 Nov 2026). The * invented object of the personal one's shape (test/big_object.ts, about * 780,000 rows), with Words' tables at the owner's size: 1,000 notes of the * person's own and 5,000 an assistant wrote, 300 memory entries, 20,000 * project links of every kind (the object seals a link's kind, so Words takes * them whole), and 5,000 documents of which 300 are web pages (the kit's * `only` keeps those alone). Measured: how many rows and milliseconds of the * object's work come before the person's own newest 200 notes and every * memory entry are on the phone, and what the whole pass costs, with * project_link and without it. Printed (`--disableConsoleIntercept`); * `BIG_OBJECT=1` runs it at full size. */const SCALE = BIG ? 1 : 1 / 40;const n = (rows: number): number => Math.max(1, Math.round(rows * SCALE));describe("Words' first pull on a very large object", () => {  it("brings the person's newest notes and the memory first, and project_link whole costs a few pages", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("sync-words-big"));    await runInDurableObject(stub, (_instance, state) => {      const sql = state.storage.sql;      let upto = writeShape(sql, personalShape(SCALE));      const add = (table: string, count: number, data: (i: string) => string): void => {        sql.exec(          `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < ?)           INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)           SELECT ?, printf('%s-%08d', ?, x), ${data("x")}, NULL, ? + x, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`,          count,          table,          table,          upto,        );        upto += count;      };      const sealed = (bytes: number): string => `'sealed_enc', 's1:' || hex(randomblob(${bytes})), 'dek_enc', 'd1:x', 'seal_v', 1`;      const own = n(1_000);      const theirs = n(5_000);      // Notes: the assistant's and the person's, edited over two years; `updated_at` clear, the rest sealed.      add("note", own + theirs, (x) => `json_object('updated_at', strftime('%Y-%m-%dT%H:%M:%SZ', '2024-11-01', '+' || (${x} * 97 % 1051200) || ' minutes'), ${sealed(900)})`);      add("memory", n(300), (x) => `json_object('slug', 'invented-' || ${x}, 'title', 'An invented sentence the person said, number ' || ${x}, 'status', 'active', 'updated_at', '2026-11-01T09:00:00Z')`);      add("project_link", n(20_000), (x) => `json_object('project', 'project-' || (${x} % 12), ${sealed(120)})`);      add("document", n(5_000), (x) => `json_object('mime', CASE WHEN ${x} % 17 = 0 THEN 'text/html' ELSE 'application/pdf' END, 'byte_size', 20000, 'storage_path', 'db/documents/' || ${x}, ${sealed(200)})`);      add("project", 12, (x) => `json_object('slug', 'project-' || ${x}, 'name', 'Invented ' || ${x})`);      const total = Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows").one().n);      const store = new Store(sql, () => new Date("2026-11-21T10:00:00Z"));      while (store.carryCounts(10_000));      // The person's own newest 200 (the assistant's are told apart on the phone, sealed here: every note comes in the same order).      const newest = new Set(sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'note' ORDER BY json_extract(data, '$.updated_at') DESC, id DESC LIMIT 200").toArray().map((r) => r.id));      const memory = new Set(sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'memory'").toArray().map((r) => r.id));      const pages = Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id = 'document' AND json_extract(data, '$.mime') = 'text/html'").one().n);      type Run = { rowsUntil: number; msUntil: number; rows: number; pages: number; ms: number; read: number; documents: number; links: number };      const pull = (tables: string[], windows: SyncWindow[]): Run => {        const scope: SyncScope = { kind: "tables", whole: new Set(tables), own: new Set(), person: null, except: new Set() };        const counts = store.passTables({ since: 0, upto, scope, windows });        const specs = planFirst((t) => counts.get(t) ?? 0, "2026-11-21", 10_000).filter((s) => tables.includes(s.table));        store.firstIndexes(specs);        const small = store.smallFirst({ since: 0, upto, scope, windows, most: 10_000 });        const pass = `words-${tables.length}-${windows.length}`;        store.firstPass(pass, 1, 0);        let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass, small: small.filter((t) => !specs.some((s) => s.table === t)), specs, cuts: specs.map(() => null) }, at: null };        const run: Run = { rowsUntil: 0, msUntil: 0, rows: 0, pages: 0, ms: 0, read: 0, documents: 0, links: 0 };        const left = new Set([...newest, ...(tables.includes("memory") ? memory : [])]);        const begun = Date.now();        for (let more = true; more; ) {          const pageBegun = Date.now();          const watched = watchStatements(sql, () => store.firstPage({ since: 0, upto, limit: run.pages === 0 ? 200 : 5000, scope, windows, ...cursor }));          const got: { rows: StoredRow[]; more: boolean; plan: FirstPlan; at: FirstAt } = watched.result;          const took = Date.now() - pageBegun;          run.read += watched.statements.reduce((sum, st) => sum + st.rowsRead, 0);          if (took > 300) {            const worst = [...watched.statements].sort((x, y) => y.rowsRead - x.rowsRead)[0];            const plan = worst ? sql.exec<{ detail: string }>(`EXPLAIN QUERY PLAN ${worst.query}`, ...worst.args).toArray().map((r) => r.detail).join(" | ") : "";            console.log(`slow page ${run.pages} (${windows.length} windows): ${took} ms, ${watched.statements.length} statements, worst read ${worst?.rowsRead}: ${worst?.query.replace(/\s+/g, " ").slice(0, 260)} :: ${plan}`);          }          cursor = JSON.parse(JSON.stringify({ plan: got.plan, at: got.at })) as typeof cursor;          got.rows.forEach((r, i) => {            if (left.delete(r.id) && left.size === 0) Object.assign(run, { rowsUntil: run.rows + i + 1, msUntil: Date.now() - begun });            if (r.table === "document" && !r.deleted) run.documents++;            if (r.table === "project_link") run.links++;          });          run.rows += got.rows.length;          run.pages++;          more = got.more;        }        run.ms = Date.now() - begun;        return run;      };      const base = ["note", "project", "person", "record_group", "group_member", "media", "photo", "face_settings", "vault_key"];      const only: SyncWindow = { table: "document", column: "mime", from: "", is: ["text/html"] };      const before = pull(base, []);      const words = pull([...base, "memory", "project_link", "document"], [only]);      const unfiltered = pull([...base, "memory", "project_link", "document"], []);      const line = (name: string, r: Run): string =>        `${name.padEnd(28)} newest 200 notes (and the memory) after ${String(r.rowsUntil).padStart(7)} rows, ${String(r.msUntil).padStart(6)} ms | whole pass ${r.rows} rows, ${r.pages} pages, ${r.ms} ms, ${r.read} rows read (${r.documents} documents, ${r.links} links)`;      console.log(        `\nthe invented object: ${total} rows; ${own + theirs} notes, ${memory.size} memories, ${n(20_000)} project links, ${n(5_000)} documents (${pages} web pages)\n` +          `${line("Words before (no memory)", before)}\n${line("Words now", words)}\n${line("now, without `only`", unfiltered)}`,      );      expect(words.documents, "of the documents, the web pages alone").toBe(pages);      expect(unfiltered.documents).toBeGreaterThan(pages * 10);      expect(words.links, "every project link").toBe(n(20_000));      expect(words.rowsUntil, "the newest notes and the memory before the photos and the links").toBeLessThan(own + theirs + memory.size + 5_000);    });  }, 3_000_000);});