Cotton code
164 lines · 9.7 KB · TypeScriptRaw
/** * READ COST (coordinator, 28 Nov 2026): the row-read guard of test/read-cost.test.ts widened to every door a phone or an * assistant uses often. An object holds about 200k rows (sealed rows of the locked tables, open notes, binned notes and * todos), both locks sealed as on the owner's account; each door is called once warm and the rows SQLite reads for it * are counted. Each must stay under a bound that does not grow with the table. Synthetic rows only. */import { env, runInDurableObject } from "cloudflare:test";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { ADMIN, http, personalObject, tool } from "./personal.ts";const SLUG = "read-cost-doors";const SEALED = 100_000;const OPEN = 60_000;const BINNED = 40_000;/** A door may read this many rows at most: a page, a few lookups, the object's own small tables; never a table's walk. */const BOUND = 5_000;const stub = () => env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));type Cursor = SqlStorageCursor<Record<string, SqlStorageValue>>;type Counted = { calls: number; cursors: Cursor[]; said: string[] };type Patched = { exec: (...a: unknown[]) => Cursor; __counted?: Counted; __exec?: (...a: unknown[]) => Cursor };/** Count the rows SQLite reads while `run` goes, statement by statement; the heaviest are said. */async function costOf(what: string, run: () => Promise<unknown>): Promise<{ rowsRead: number; calls: number; answer: unknown }> {  await runInDurableObject(stub(), (_i, state) => {    const sql = state.storage.sql as unknown as Patched;    const exec = (sql.__exec ??= sql.exec.bind(sql));    const counted: Counted = { calls: 0, cursors: [], said: [] };    sql.__counted = counted;    sql.exec = (...a: unknown[]) => {      const cursor = exec(...a);      counted.calls++;      counted.cursors.push(cursor);      counted.said.push(String(a[0]).replace(/\s+/g, " ").slice(0, 240));      return cursor;    };  });  const answer = await run();  const { rowsRead, calls, heaviest } = await runInDurableObject(stub(), (_i, state) => {    const sql = state.storage.sql as unknown as Patched;    const counted = sql.__counted!;    if (sql.__exec) sql.exec = sql.__exec;    return {      rowsRead: counted.cursors.reduce((n, c) => n + c.rowsRead, 0),      calls: counted.calls,      heaviest: counted.cursors.map((c, i) => ({ n: c.rowsRead, sql: counted.said[i]! })).filter((x) => x.n > 1_000).sort((a, b) => b.n - a.n).slice(0, 4),    };  });  for (const h of heaviest) console.log(`READ COST heavy: ${what}: ${h.n} rows: ${h.sql}`);  console.log(`READ COST: ${what} read ${rowsRead} rows in ${calls} statements`);  return { rowsRead, calls, answer };}describe("every often-used door reads a bounded number of rows beside 200k (READ COST)", { timeout: 600_000 }, () => {  let owner = "";  let device: Record<string, string> = {};  let cursor = 0;  beforeAll(async () => {    const made = await personalObject(SLUG, { open: ["note", "todo"] });    owner = made.owner;    device = { authorization: `Bearer ${made.credential}` };    const now = new Date().toISOString();    await runInDurableObject(stub(), (instance, state) => {      const store = (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store;      for (const key of ["memory_lock", "open_tables_lock"]) store.setMeta(key, JSON.stringify({ on_at: now, by: "birth", sealing_at: now }));      const fill = (table: string, n: number, data: string, prefix = table) =>        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 ?, ? || '-' || i, ${data}, NULL, 1, 0, ?, ? FROM n`,          n, table, prefix, now, now,        );      const seal = `'{"sealed_enc":"s1:AAAA","dek_enc":"d1:AAAA","seal_v":1}'`;      fill("session", SEALED / 2, seal);      fill("prompt", SEALED / 4, seal);      fill("memory", SEALED / 4, seal);      fill("note", OPEN, `json_object('title', 'note ' || i, 'body', 'words')`);      fill("note", BINNED / 2, `json_object('title', 'binned ' || i, 'trashed_at', '${now}')`, "binned-note");      fill("todo", BINNED / 2, `json_object('title', 'done ' || i, 'trashed_at', '${now}')`, "binned-todo");      state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('note', 'note-x', ?, NULL, 2, 0, ?, ?)", JSON.stringify({ title: "the one", body: "words" }), now, now);    });    // Warm: the object's once-per-instance work is not any door's.    expect((await tool(SLUG, owner, "get_record_by_table", { table: "note", id: "note-x" })).isError).toBe(false);    const version = await http<{ version?: number; cursor?: string }>(SLUG, "GET", "/v1/sync?since=0&tables=alarm", undefined, device);    cursor = Number(version.body.version ?? 0);    // The lookup indexes the doors ask for are made by the alarm, never in a request (Store.lookupIndex): each door is    // called once, then the alarm runs until nothing is asked, and the door's second call is what it costs.  }, 600_000);  const doors: [string, () => Promise<unknown>][] = [    ["GET /v1/sync (a small table, since the cursor)", () => http(SLUG, "GET", `/v1/sync?since=${cursor}&tables=alarm`, undefined, device)],    ["GET /v1/me", () => http(SLUG, "GET", "/v1/me", undefined, device)],    ["GET /v1/fetch/pending", () => http(SLUG, "GET", "/v1/fetch/pending", undefined, device)],    ["POST /v1/act (one row)", () => http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "note", id: "note-x", data: { body: "changed" } } }, device)],    ["mcp brief", () => tool(SLUG, owner, "brief", { machine: "invented-mac" })],    ["mcp recall", () => tool(SLUG, owner, "recall", { q: "anything", limit: 5 })],    ["mcp remember", () => tool(SLUG, owner, "remember", { title: "an invented fact" })],    ["mcp log_session", () => tool(SLUG, owner, "log_session", { tool: "claude-code", externalId: "invented-ext-1", machine: "invented-mac", lastActiveAt: new Date().toISOString() })],    ["mcp list_devices", () => tool(SLUG, owner, "list_devices", {})],        ["mcp update_record", () => tool(SLUG, owner, "update_record", { table: "note", id: "note-x", patch: { body: "again" } })],    ["mcp create_record", () => tool(SLUG, owner, "create_record", { table: "note", data: { title: "a fresh note" } })],    ["mcp list_bin", () => tool(SLUG, owner, "list_bin", { limit: 5 })],    ["mcp summarize_records (a small table)", () => tool(SLUG, owner, "summarize_records", { table: "alarm", measures: [{ op: "count" }] })],    ["the alarm's regular pass", () => runInDurableObject(stub(), async (instance) => (instance as unknown as { alarm(): Promise<void> }).alarm())],    [      "the first request after a reset",      () =>        runInDurableObject(stub(), async (instance, state) => {          // A fresh instance over the same storage, as the platform makes after a reset: its constructor and first request.          const Fresh = (instance as object).constructor as new (s: DurableObjectState, e: unknown) => { fetch(r: Request): Promise<Response> };          const fresh = new Fresh(state, env);          const res = await fresh.fetch(new Request(`https://example.test/b/${SLUG}/v1/me`, { headers: { ...device, "x-cotton-slug": SLUG } }));          return res.status;        }),    ],  ];  // Doors that read a table, or the file, by nature: measured and said, not bounded. How each is kept from blocking the  // object is in assets/design/shared/READ-COST.md.  const scans: [string, () => Promise<unknown>][] = [    ["mcp summarize_records (20k todos)", () => tool(SLUG, owner, "summarize_records", { table: "todo", measures: [{ op: "count" }] })],    ["mcp storage_summary (a file under 64 MB, measured when asked)", () => tool(SLUG, owner, "storage_summary", {})],    ["mcp search_records", () => tool(SLUG, owner, "search_records", { q: "binned 1999" })],    [      "POST /v1/admin/erase old_prompts (dry run, 25k prompts, none old enough)",      async () => {        const res = await http(SLUG, "POST", "/v1/admin/erase", { set: "old_prompts", days: 1 }, ADMIN);        expect(res.status, JSON.stringify(res.body)).toBe(200);        return res;      },    ],  ];  const said: [string, number, string][] = [];  /** The alarm until no index is asked for, as the object's own alarms come round. */  const settle = () =>    runInDurableObject(stub(), (_i, state) => {      for (let i = 0; i < 10 && state.storage.sql.exec("SELECT 1 FROM meta WHERE key = 'order_indexes_wanted' AND value IS NOT NULL").toArray().length; i++) {        (_i as unknown as { store: { buildOrderIndex(): boolean } }).store.buildOrderIndex();      }    });  // A door once and again: what it costs warm stays under BOUND whatever the table holds.  afterAll(() => console.log(["READ COST table:", ...said.map(([w, n, k]) => `| ${w} | ${n} | ${k} |`)].join("\n")));  for (const [what, run] of doors) {    it(what, async () => {      // The first call may build its lookup index (once a file, CREATE INDEX IF NOT EXISTS); the second is the door's cost.      const first = await costOf(`${what} (first)`, run);      await settle();      const { rowsRead, calls } = await costOf(what, run);      said.push([what, rowsRead, `bounded; first call ${first.rowsRead}`]);      expect(calls, "the patched exec saw the door's statements").toBeGreaterThan(0);      expect(rowsRead, `${what} read ${rowsRead} rows in ${calls} statements`).toBeLessThan(BOUND);    });  }  for (const [what, run] of scans) {    it(`${what} (scans by nature, measured)`, async () => {      const { rowsRead, calls } = await costOf(what, run);      said.push([what, rowsRead, "scan"]);      expect(calls).toBeGreaterThan(0);    });  }});