/** * A big table's list along an index on its order (Store.selectOrdered; coordinator, 23 Nov 2026: list_records on * 200,000 prompts took 1.8 to 2.7 s, sorting the whole table). The first list asks for the index and sorts as before, * the alarm makes it, and every list after reads only its page, in the same order. Invented notes only. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { ORDER_INDEX_ROWS } from "../src/mcp/tools/records/list.ts"; import { answer, NOTES_OPEN, personalObject } from "./personal.ts"; type Store = { buildOrderIndex(): boolean; orderIndexAsked(): boolean }; describe("a big table's list", () => { it("is read along its order's index once the alarm has made it, in the same order", async () => { const slug = "list-big"; const { owner } = await personalObject(slug, NOTES_OPEN); const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const n = ORDER_INDEX_ROWS + 500; await runInDurableObject(stub, (_i, s) => { s.storage.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 'note', printf('note-%06d', x), json_object('title', printf('Invented note %d', x)), NULL, x, x % 50 = 0, '2025-01-01T00:00:00Z', printf('2026-%02d-%02dT%02d:%02d:00Z', 1 + x % 11, 1 + x % 28, x % 24, x % 60) FROM c`, n, ); }); type Page = { records: { id: string }[]; total: number; next_page: number | null }; const list = (page = 0) => answer(slug, owner, "list_records", { table: "note", limit: 25, page }); const before = [await list(), await list(500)]; const asked = await runInDurableObject(stub, (instance) => (instance as unknown as { store: Store }).store.orderIndexAsked()); expect(asked, "the first list asks for the index").toBe(true); await runInDurableObject(stub, (instance, s) => { const store = (instance as unknown as { store: Store }).store; while (s.storage.transactionSync(() => store.buildOrderIndex())); expect(store.orderIndexAsked()).toBe(false); }); // Every statement the next lists run, and the rows each read. const seen: SqlStorageCursor>[] = []; const queries: string[] = []; await runInDurableObject(stub, (_i, s) => { const sql = s.storage.sql as unknown as { exec: (q: string, ...a: SqlStorageValue[]) => SqlStorageCursor> }; const exec = sql.exec.bind(sql); sql.exec = (q, ...a) => { const c = exec(q, ...a); seen.push(c); queries.push(q); return c; }; }); const after = [await list(), await list(500)]; expect(after, "the same pages, in the same order").toEqual(before); expect(after[0]!.total).toBe(n - Math.floor(n / 50)); const page = queries.findIndex((q) => q.includes("INDEXED BY rows_order_note_")); expect(page, "read along the order's index").toBeGreaterThanOrEqual(0); expect(seen[page]!.rowsRead, "a page reads about a page").toBeLessThan(1_000); }); });