Cotton code
205 lines · 10.8 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import { answer, MEMORY_OPEN, personalObject, put, TODOS_OPEN, PEOPLE_OPEN } from "./personal.ts";/** What one SQL statement over the rows table handed the isolate: the statement, the table it names first and how many rows. */type Read = { sql: string; table: unknown; rows: number };const READS = Symbol.for("paging-test-reads");type Held = { [READS]?: Read[] };/** * Counts every stored row a statement over the rows table hands to JS, on the object * the slug names: the object's SQLite is the only place a table may be whole. */async function watch(slug: string): Promise<void> {  const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));  await runInDurableObject(stub, (_instance, state) => {    const sql = state.storage.sql as SqlStorage & Held;    if (sql[READS]) return;    const reads: Read[] = [];    sql[READS] = reads;    const exec = sql.exec.bind(sql);    sql.exec = ((query: string, ...bindings: SqlStorageValue[]) => {      const cursor = exec(query, ...bindings);      if (!/\b(FROM|JOIN) rows\b/.test(query)) return cursor;      const toArray = cursor.toArray.bind(cursor);      cursor.toArray = () => {        const all = toArray();        // A count or a MAX hands back a number, not a row.        if (all.some((r) => "data" in r)) reads.push({ sql: query, table: bindings[0], rows: all.length });        return all;      };      return cursor;    }) as typeof sql.exec;  });}/** The reads of `table` since the last call; every read is emptied. */async function reads(slug: string, table: string): Promise<Read[]> {  const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));  return runInDurableObject(stub, (_instance, state) => {    const held = (state.storage.sql as SqlStorage & Held)[READS]!;    return held.splice(0, held.length).filter((r) => r.table === table);  });}const most = (rs: Read[]): number => Math.max(0, ...rs.map((r) => r.rows));const sum = (rs: Read[]): number => rs.reduce((a, r) => a + r.rows, 0);const N = 1200;const pad = (i: number, w = 4): string => String(i).padStart(w, "0");const minute = (i: number): string => new Date(Date.UTC(2026, 0, 1) + i * 60_000).toISOString();async function putAll(slug: string, rows: Record<string, unknown>[]): Promise<void> {  for (let i = 0; i < rows.length; i += 1000) await put(slug, rows.slice(i, i + 1000));}type Rec = { id: string; data: Record<string, unknown> };type Page = { records: Rec[]; next_page: number | null; total: number };/** * RULE (owner, 25 Oct 2026): the record tools page in SQL — the message table, or any other, never loads into the Worker's memory. * Messages are sealed (e3bca3c99) and read in a window, so the clear path is paged here over todos, dated by when they are due, under two projects. */describe("the record tools page in SQL", () => {  const SLUG = "paging-personal";  let owner = "";  // Every 100th todo has no due_at; every 50th says "needle"; the projects alternate.  const todos = Array.from({ length: N }, (_, i) => ({    verb: "put",    table: "todo",    id: `td-${pad(i)}`,    updated_at: "2026-02-01T00:00:00.000Z",    data: { project: i % 2 ? "pj-b" : "pj-a", title: i % 50 === 7 ? `the needle ${i}` : `hello ${i}`, status: "open", ...(i % 100 === 3 ? {} : { due_at: minute((i * 7919) % N) }) },  }));  /** list_records' order on a dated table: dated first, newest first, then id. */  const expected = (keep: (m: (typeof todos)[number]) => boolean): string[] =>    todos      .filter(keep)      .sort((a, b) => {        const x = (a.data as { due_at?: string }).due_at;        const y = (b.data as { due_at?: string }).due_at;        if ((x === undefined) !== (y === undefined)) return x === undefined ? 1 : -1;        if (x !== y) return x! < y! ? 1 : -1;        return a.id < b.id ? -1 : 1;      })      .map((m) => m.id);  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    await putAll(SLUG, [      { verb: "put", table: "project", id: "pj-a", data: { slug: "asha", name: "Asha" } },      { verb: "put", table: "project", id: "pj-b", data: { slug: "bela", name: "Bela" } },      ...todos,    ]);    await watch(SLUG);    await reads(SLUG, "");  });  it("pages the whole todo table by offset in the date order, each page reading one page's rows", async () => {    const seen: string[] = [];    let page: number | null = 0;    let peak = 0;    while (page !== null) {      const got: Page = await answer<Page>(SLUG, owner, "list_records", { table: "todo", limit: 100, page });      expect(got.total).toBe(N);      seen.push(...got.records.map((r) => r.id));      page = got.next_page;      const r = await reads(SLUG, "todo");      peak = Math.max(peak, sum(r));    }    expect(seen).toEqual(expected(() => true));    expect(peak, "a page of 100 reads its 101 rows, not the table").toBeLessThanOrEqual(101);  });  it("narrows by where, query and count_only in SQL", async () => {    const b = await answer<Page>(SLUG, owner, "list_records", { table: "todo", where: { project: "pj-b" }, query: "NEEDLE", limit: 500 });    expect(b.records.map((r) => r.id)).toEqual(expected((m) => m.data.project === "pj-b" && m.data.title.includes("needle")));    expect(b.total).toBe(b.records.length);    expect(most(await reads(SLUG, "todo"))).toBeLessThanOrEqual(b.records.length + 1);    const a = await answer<Page>(SLUG, owner, "list_records", { table: "todo", where: { project: "pj-a" }, limit: 1 });    expect(a.total).toBe(N / 2);    expect(sum(await reads(SLUG, "todo")), "the total is counted in SQL").toBe(2);    expect(await answer(SLUG, owner, "list_records", { table: "todo", count_only: true })).toEqual({ table: "todo", total: N });    expect(sum(await reads(SLUG, "todo")), "a count reads no row").toBe(0);    const undated = await answer<Page>(SLUG, owner, "list_records", { table: "todo", where: { due_at: { present: false } } });    expect(undated.total).toBe(N / 100);    expect(sum(await reads(SLUG, "todo"))).toBe(N / 100);  });  it("answers last_changed without reading a row", async () => {    const r = await answer<{ table: string; last_changed: string | null }>(SLUG, owner, "list_records", { table: "todo", last_changed: true });    expect(typeof r.last_changed).toBe("string");    expect(sum(await reads(SLUG, "todo"))).toBe(0);  });});describe("recall, list_sessions and list_todos stream or page their tables", () => {  const SLUG = "paging-tools";  let owner = "";  const at = (i: number): string => new Date(Date.UTC(2026, 1, 1) + i * 1000).toISOString();  beforeAll(async () => {    // Memory open: this is the paging of an open table (sealed, recall opens every entry in the window: window.test.ts).    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    const memories = Array.from({ length: 700 }, (_, i) => ({      verb: "put",      table: "memory",      id: `00000000-0000-4000-8000-${pad(i, 12)}`,      data: { slug: `entry-${pad(i)}`, title: i === 611 ? "The kettle rule is the only kettle rule." : i % 3 ? `Entry ${i} about kettle tea` : `Entry ${i} about coffee`, body: "", status: i % 10 === 9 ? "archived" : "active", visibility: "private", origin_kind: "user" },      created_at: at(i),      updated_at: at(i),    }));    const sessions = Array.from({ length: 700 }, (_, i) => ({ verb: "put", table: "session", id: `ses-${pad(i)}`, data: { tool: "claude-code", machine: i % 2 ? "mac-d" : "mac-a", last_active_at: at((i * 389) % 700) } }));    const prompts = Array.from({ length: 700 }, (_, i) => ({ verb: "put", table: "prompt", id: `pr-${pad(i)}`, data: { session: `ses-${pad(i)}`, seq: 0, ts: at(i), role: "user", text: i === 444 ? "Find the walrus in the hangar" : `Prompt ${i} about the build` } }));    const todos = Array.from({ length: 600 }, (_, i) => ({ verb: "put", table: "todo", id: `td-${pad(i)}`, data: { title: `Todo ${i}`, status: "open", ...(i % 2 ? { due_at: at((i * 211) % 600) } : {}) }, created_at: at(i), updated_at: at(i) }));    await putAll(SLUG, [...memories, ...sessions, ...prompts, ...todos]);    await watch(SLUG);    await reads(SLUG, "");  });  it("recall without a project reads its limit; with q it streams the corpus a page at a time", async () => {    const newest = await answer<{ memories: { slug: string }[] }>(SLUG, owner, "recall", { limit: 5 });    expect(newest.memories.map((m) => m.slug)).toEqual(["entry-0698", "entry-0697", "entry-0696", "entry-0695", "entry-0694"]);    expect(most(await reads(SLUG, "memory"))).toBeLessThanOrEqual(5);    const found = await answer<{ memories: { slug: string }[] }>(SLUG, owner, "recall", { q: "kettle rule" });    expect(found.memories.map((m) => m.slug)).toEqual(["entry-0611"]);    expect(most(await reads(SLUG, "memory")), "the corpus comes in pages of 500").toBeLessThanOrEqual(500);  });  it("list_sessions pages by cursor through every session, newest first, a page's rows at a time", async () => {    const seen: string[] = [];    let cursor: string | undefined;    do {      const got: { sessions: { id: string }[]; nextCursor?: string } = await answer(SLUG, owner, "list_sessions", { limit: 50, machine: "mac-d", ...(cursor ? { cursor } : {}) });      seen.push(...got.sessions.map((s) => s.id));      cursor = got.nextCursor;      expect(most(await reads(SLUG, "session"))).toBeLessThanOrEqual(50);    } while (cursor);    const macD = Array.from({ length: 700 }, (_, i) => i)      .filter((i) => i % 2)      .sort((a, b) => ((b * 389) % 700) - ((a * 389) % 700))      .map((i) => `ses-${pad(i)}`);    expect(seen).toEqual(macD);    const said = await answer<{ sessions: { id: string; hits: { snippet: string }[] }[] }>(SLUG, owner, "list_sessions", { q: "walrus hangar" });    expect(said.sessions.map((s) => s.id)).toEqual(["ses-0444"]);    expect(said.sessions[0]!.hits[0]!.snippet).toContain("walrus");    expect(most(await reads(SLUG, "prompt")), "prompts stream in pages of 500").toBeLessThanOrEqual(500);  });  it("list_todos pages by cursor, the dated soonest first then the undated newest first", async () => {    const seen: string[] = [];    let cursor: string | undefined;    do {      const got: { todos: { title: string }[]; nextCursor?: string } = await answer(SLUG, owner, "list_todos", { limit: 40, ...(cursor ? { cursor } : {}) });      seen.push(...got.todos.map((t) => t.title));      cursor = got.nextCursor;      expect(most(await reads(SLUG, "todo"))).toBeLessThanOrEqual(41);    } while (cursor);    const dated = Array.from({ length: 600 }, (_, i) => i).filter((i) => i % 2).sort((a, b) => ((a * 211) % 600) - ((b * 211) % 600));    const undated = Array.from({ length: 600 }, (_, i) => i).filter((i) => !(i % 2)).reverse();    expect(seen).toEqual([...dated, ...undated].map((i) => `Todo ${i}`));  });});