Cotton code
98 lines · 9.0 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import * as migration from "../src/seal_migration.ts";import { Store, type SyncScope, type SyncWindow } from "../src/store.ts";import { BIG, personalShape, sortsOfRows, watchStatements, writeShape } from "./big_object.ts";/** * WHAT EACH STATEMENT COSTS ON A VERY LARGE OBJECT (audit, 21 Nov 2026). * Every statement a sync pass, a write, a kit change, the alarm's trim or a * sealing status runs, on the invented object of the personal one's shape * (test/big_object.ts), with the rows it reads and the time it takes. The * table is printed (`--disableConsoleIntercept`); the bounds asserted are * the ones the object depends on. `BIG_OBJECT=1` runs it at full size. */const SCALE = BIG ? 1 : 1 / 40;const NOW = new Date("2026-11-21T10:00:00Z");const CHANGES_STEP = BIG ? 10_000 : 2_000;type Cost = { path: string; ms: number; statements: number; mostRead: number; read: number; worst: string; sorts: string[] };function cost<T>(sql: SqlStorage, path: string, run: () => T, costs: Cost[]): T {  const t = Date.now();  const { result, statements } = watchStatements(sql, run);  const worst = statements.reduce((w, s) => (s.rowsRead > w.rowsRead ? s : w), { query: "", rowsRead: 0 });  costs.push({ path, ms: Date.now() - t, statements: statements.length, mostRead: worst.rowsRead, read: statements.reduce((n, s) => n + s.rowsRead, 0), worst: worst.query.replace(/\s+/g, " ").slice(0, 110), sorts: sortsOfRows(sql, statements) });  return result;}describe("the cost of each statement on a very large object", () => {  it("measures a pass, a write, a kit change, the trim and a sealing status", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("big-object-audit"));    const costs: Cost[] = [];    await runInDurableObject(stub, (_instance, state) => {      const sql = state.storage.sql;      const shape = personalShape(SCALE);      const upto = writeShape(sql, shape);      const total = shape.reduce((n, t) => n + t.rows, 0);      const columns = new Map(shape.filter((t) => t.dated).map((t) => [t.table, t.dated!]));      const store = new Store(sql, () => NOW);      store.setDateColumns(columns);      const owner: SyncScope = { kind: "all", except: new Set() };      const notes: SyncScope = { kind: "tables", whole: new Set(["small_00"]), own: new Set(), person: null, except: new Set() };      const windows: SyncWindow[] = [{ table: "message", column: "sent_at", from: "2026-08-23" }];      // While row_counts is being counted again: the pass counts in SQL.      cost(sql, "pass from nothing, counts in SQL (recount under way)", () => [store.syncCounts({ since: 0, upto, scope: owner, windows }), store.passTables({ since: 0, upto, scope: owner, windows })], costs);      while (store.carryCounts(10_000));      cost(sql, "pass from nothing, counts (row_counts)", () => [store.syncCounts({ since: 0, upto, scope: owner, windows }), store.smallFirst({ since: 0, upto, scope: owner, windows, most: 1000 })], costs);      const small = store.smallFirst({ since: 0, upto, scope: owner, windows, most: 1000 });      cost(sql, "pass from nothing, first page (500 rows)", () => store.changedPage({ since: 0, upto, limit: 500, scope: owner, windows, small, floor: null, after: null }), costs);      cost(sql, "pass from nothing, a page of the big tables (5000)", () => store.changedPage({ since: 0, upto, limit: 5000, scope: owner, windows, small: [], floor: null, after: null }), costs);      cost(sql, "pass from nothing, a windowed page (message before its window)", () => store.changedPage({ since: 0, upto, limit: 5000, scope: { kind: "tables", whole: new Set(["message"]), own: new Set(), person: null, except: new Set() }, windows, small: [], floor: null, after: null }), costs);      cost(sql, "Notes (tables=small_00) from nothing: counts + first page", () => [store.syncCounts({ since: 0, upto, scope: notes, windows: [] }), store.changedPage({ since: 0, upto, limit: 500, scope: notes, windows: [], small: store.smallFirst({ since: 0, upto, scope: notes, windows: [], most: 1000 }), floor: null, after: null })], costs);      cost(sql, "Notes (tables=small_00), a member's scope: counts in SQL", () => store.syncCounts({ since: 0, upto, scope: { ...notes, person: "member-invented" }, windows: [] }), costs);      cost(sql, "a caught-up pass (since = upto - 100)", () => [store.syncCounts({ since: upto - 100, upto, scope: owner, windows }), store.passTables({ since: upto - 100, upto, scope: owner, windows }), store.changedPage({ since: upto - 100, upto, limit: 5000, scope: owner, windows, small: [], floor: null, after: null })], costs);      const chat: SyncScope = { kind: "tables", whole: new Set(["message", "thread", "message_contact_handle"]), own: new Set(), person: null, except: new Set() };      const chatSmall = store.smallFirst({ since: 0, upto, scope: chat, windows, most: 1000 });      cost(sql, "Chat (tables=message,…) from nothing: counts + first page", () => [store.syncCounts({ since: 0, upto, scope: chat, windows }), store.changedPage({ since: 0, upto, limit: 500, scope: chat, windows, small: chatSmall, floor: null, after: null })], costs);      cost(sql, "Chat (tables=message,…), a page of message (5000)", () => store.changedPage({ since: 0, upto, limit: 5000, scope: chat, windows, small: [], floor: null, after: null }), costs);      cost(sql, "Chat (tables=message,…), a caught-up pass", () => [store.syncCounts({ since: upto - 100, upto, scope: chat, windows }), store.passTables({ since: upto - 100, upto, scope: chat, windows }), store.changedPage({ since: upto - 100, upto, limit: 5000, scope: chat, windows, small: [], floor: null, after: null })], costs);      cost(sql, "held ids, one page of message", () => store.heldPage(["message"], null, 5000), costs);      const row = store.any("message", "message-00000001")!;      cost(sql, "a write: update, tombstone, insert", () => {        store.update(row, { ...row.data, sent_at: "2026-11-21T09:00:00Z" }, null, upto + 1);        store.tombstone(store.any("message", "message-00000002")!, upto + 2);        store.insert("message", "message-new", { sent_at: "2026-11-21T09:00:00Z" }, null, upto + 3);      }, costs);      cost(sql, "the export's counts", () => store.counts(), costs);      // A kit change: message.thread_id becomes a link column.      store.setLinkColumns(new Map([["message", ["thread_id"]]]));      cost(sql, "a kit change: message gains a link column (relink)", () => store.relink(new Map()), costs);      // The change log of a big import, then the alarm's trim to its window.      sql.exec(        `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < ?)         INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) SELECT '2026-01-01T00:00:00Z', NULL, 'import', 'message', printf('message-%08d', x), 'create', NULL, json_object('sealed_enc', 's1:' || hex(randomblob(300))), x FROM c`,        Math.round(150_000 * SCALE * 4),      );      const trim = cost(sql, "the alarm's trim of the change log", () => store.trimChanges("2026-08-23T00:00:00Z", Math.round(100_000 * SCALE), null, CHANGES_STEP), costs);      expect(trim.trimmed, "a trim takes at most a step").toBeLessThanOrEqual(CHANGES_STEP);      expect(trim.more, "and says more are left").toBe(true);      let trims = 1;      while (store.trimChanges("2026-08-23T00:00:00Z", Math.round(100_000 * SCALE), null, CHANGES_STEP).more) trims++;      expect(Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n), "the log ends in its window").toBe(0);      expect(trims).toBeGreaterThan(1);      const sealed = { id: "message", columns: [{ key: "sent_at" }, { key: "thread_id" }, { key: "body" }], raw: {}, seal: { clear: ["sent_at", "thread_id"], blind: [], blind_exact: [] } };      cost(sql, "a sealing status (seal standing of message)", () => migration.standing(sql, sealed, [], (_a, args) => args), costs);      console.log(`\nthe invented object: ${total} rows\n${costs.map((c) => `${c.path.padEnd(66)} ${String(c.ms).padStart(6)} ms ${String(c.statements).padStart(5)} stmts  most ${String(c.mostRead).padStart(8)} rows  all ${String(c.read).padStart(8)}  ${c.worst}`).join("\n")}`);    });    const of = (path: string): Cost => costs.find((c) => c.path.startsWith(path))!;    expect(of("pass from nothing, counts (row_counts)").read, "a pass's counts read no row").toBeLessThan(5000);    // No statement of a pass sorts or groups rows in a temporary B-tree, whose memory grows with the rows (the 21 Nov outage's shape).    for (const c of costs.filter((c) => /pass|Notes|Chat|held/.test(c.path))) expect(c.sorts, c.path).toEqual([]);    // A caught-up pass of an app keeping to its kit reads the rows changed since, never its tables whole.    expect(of("Chat (tables=message,…), a caught-up pass").mostRead, "a caught-up Chat pass").toBeLessThan(1000);    expect(of("Notes (tables=small_00) from nothing").read, "Notes from nothing walks no other table").toBeLessThan(1000);  }, 3_000_000);});