Cotton code
80 lines · 5.0 KB · TypeScriptRaw
/** * AUDIT D (row-read rule): merging two people repoints every list that holds the one merged away (a note's people, an * event's people). It found them by reading every live row of each such table; on an account of hundreds of thousands * of rows that is one transaction reading them all, the pattern behind the 29 Oct CPU reset. Lists are now kept one * element a row in `list_links`, filled for older rows a page at a time on the alarm, and a merge seeks along it. * * Here: 200k notes, each with people, beside the three that name the person merged away. The fill is run to its end, * the alarm's other jobs are held off, then one merge is counted: it must read a handful of rows, not the table. * Synthetic rows only. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { http, personalObject } from "./personal.ts";const SLUG = "merge-cost";const ROWS = 200_000;const stub = () => env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));type Store = { listLinksStep(page?: number): boolean; listLinksReady(): boolean };type Counted = { cursors: SqlStorageCursor<Record<string, SqlStorageValue>>[]; said: string[] };type Exec = (...a: unknown[]) => SqlStorageCursor<Record<string, SqlStorageValue>>;describe("a merge's cost does not grow with the database (AUDIT D)", () => {  it("merge_people reads a handful of rows beside 200k notes that hold people", async () => {    const { credential } = await personalObject(SLUG, { open: ["person", "note"] });    const act = <T = Record<string, unknown>>(name: string, args: Record<string, unknown>) => http<T>(SLUG, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });    const keep = crypto.randomUUID();    const drop = crypto.randomUUID();    for (const [id, full_name] of [[keep, "Invented Keep"], [drop, "Invented Dup"]] as const) expect((await act("create", { table: "person", id, data: { full_name } })).status).toBe(200);    const now = new Date().toISOString();    await runInDurableObject(stub(), async (instance, state) => {      state.storage.sql.exec(        `WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?)         INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)         SELECT 'note', 'note-' || i, '{"kind":"note","title":"n","people":["someone-else-' || (i % 50) || '"]}', NULL, 1, 0, ?, ? FROM n`,        ROWS,        now,        now,      );      for (const i of [1, 2, 3]) {        state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('note', ?, ?, NULL, 1, 0, ?, ?)", `dup-${i}`, JSON.stringify({ kind: "note", title: `with dup ${i}`, people: [drop, "someone-else-1"] }), now, now);      }      // The alarm's fill, run to its end (each step one page).      const store = (instance as unknown as { store: Store }).store;      let steps = 0;      while (store.listLinksStep(5000) && steps < 1000) steps++;      expect(store.listLinksReady()).toBe(true);      // The alarm's other jobs (measuring storage, the calendar's pass) are not the merge's: held off while it is counted.      await state.storage.deleteAlarm();    });    await runInDurableObject(stub(), (_i, state) => {      const sql = state.storage.sql as unknown as { exec: Exec; __counted?: Counted; __exec?: Exec };      const exec = (sql.__exec ??= sql.exec.bind(sql));      const counted: Counted = { cursors: [], said: [] };      sql.__counted = counted;      sql.exec = (...a: unknown[]) => {        const cursor = exec(...a);        counted.cursors.push(cursor);        counted.said.push(String(a[0]).replace(/\s+/g, " ").slice(0, 200));        return cursor;      };    });    const merged = await act<{ moved: Record<string, number> }>("merge_people", { keep, drop });    const { rowsRead, heaviest } = await runInDurableObject(stub(), (_i, state) => {      const counted = (state.storage.sql as unknown as { __counted: Counted }).__counted;      return { rowsRead: counted.cursors.reduce((n, c) => n + c.rowsRead, 0), heaviest: counted.cursors.map((c, i) => ({ n: c.rowsRead, sql: counted.said[i] })).filter((x) => x.n > ROWS / 20) };    });    for (const h of heaviest) console.log(`MERGE COST heavy: ${h.n} rows: ${h.sql}`);    expect(merged.status, JSON.stringify(merged.body)).toBe(200);    expect(merged.body.moved["note.people"]).toBe(3);    expect(rowsRead, `one merge read ${rowsRead} rows`).toBeLessThan(ROWS / 20);    // What it moved is right: the three name keep, and the list index follows.    await runInDurableObject(stub(), (_i, state) => {      const sql = (state.storage.sql as unknown as { __exec: Exec }).__exec;      expect(sql("SELECT count(*) AS n FROM list_links WHERE table_id = 'note' AND column = 'people' AND target = ?", keep).one().n).toBe(3);      expect(sql("SELECT count(*) AS n FROM list_links WHERE table_id = 'note' AND column = 'people' AND target = ?", drop).one().n).toBe(0);    });  }, 600_000);});