/** * HEAVY READS AT HIS SIZE (coordinator for the owner, 23 Nov 2026): on his live object (4.2 GB, about a million rows) * storage_summary took 13 to 25 s and twice answered 500, and search_records and list_sessions answered 502 through * the MCP proxy. An invented object of the personal shape (test/big_object.ts: about 800,000 sealed rows) with the open * tables an assistant's own work fills beside it (sessions, their prompts, messages and tasks, memory), and each of * those reads timed, with the rows every statement it ran read. Small by default; `BIG_OBJECT=1` builds it at his * size (about 1.1 million rows, 1.4 GB of local disk while it runs). Invented records only. */import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { BIG, personalShape, writeShape } from"./big_object.ts";import { answer, personalObject } from"./personal.ts";const SCALE = BIG ? 1 : 1 / 200;const n = (rows: number): number => Math.max(1, Math.round(rows * SCALE));/** The open tables an assistant's work fills, by rows and the words each row's text column holds. */const OPEN = [ { table: "session", rows: n(4_000), text: "summary", body: 600 }, { table: "prompt", rows: n(200_000), text: "text", body: 1_500 }, { table: "session_message", rows: n(80_000), text: "body", body: 900 }, { table: "session_task", rows: n(30_000), text: "text", body: 120 }, { table: "memory", rows: n(6_000), text: "body", body: 400 },];const out: string[] = [];/** Invented words: a few real-looking ones so a search finds some, the rest letters. */function writeOpen(sql: SqlStorage, from: number): number {let version = from;for (const t of OPEN) {for (let start = 1; start <= t.rows; start += 10_000) {const end = Math.min(t.rows, start + 9_999); sql.exec(`WITH RECURSIVE c(x) AS (SELECT ? UNION ALL SELECT x + 1 FROM c WHERE x < ?) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT ?, printf('%s-%08d', ?, x), json_object('session', printf('session-%08d', 1 + x % ?), 'seq', x, 'state', CASE WHEN x % 3 = 0 THEN 'done' ELSE 'open' END, 'last_active_at', printf('2026-%02d-%02dT%02d:00:00Z', 1 + x % 11, 1 + x % 28, x % 24), 'kind', 'thread', 'tool', 'claude-code', ?, CASE WHEN x % 997 = 0 THEN 'an invented lighthouse keeper ' ELSE '' END || lower(hex(randomblob(?)))), NULL, ? + x, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, start, end, t.table, t.table, OPEN[0]!.rows, t.text, Math.ceil(t.body / 2), version, ); } version += t.rows; }return version;}describe("heavy reads at his size", () => { it("times storage_summary, search_records and list_sessions on a million rows", async () => {const slug = "heavy-reads-big";const { owner } = await personalObject(slug);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));const shape = personalShape(SCALE);await runInDurableObject(stub, (_i, s) => {const last = writeShape(s.storage.sql, shape); writeOpen(s.storage.sql, last); s.storage.sql.exec("UPDATE meta SET value = CAST(? AS TEXT) WHERE key = 'version'", last + OPEN.reduce((a, t) => a + t.rows, 0)); });const size = await runInDurableObject(stub, (_i, s) => ({ file: s.storage.sql.databaseSize, rows: Number(s.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows").one().n) })); out.push(`built: ${size.rows} rows, file ${(size.file / 1e6).toFixed(0)} MB`);// row_counts counted, as on a live object long since (the alarm's recount): a whole table's total is read from it.const counted = await runInDurableObject(stub, (instance, s) => {const store = (instance as unknown as { store: { carryCounts(steps: number, tx: (step: () => void) => void): boolean; countsProgress(): { ready: boolean } } }).store;while (store.carryCounts(50, (step) => s.storage.transactionSync(step)));return store.countsProgress().ready; }); out.push(`row_counts ready: ${counted}`);// Before the alarm has measured anything: storage_summary answers at once, without the tables' bytes or the parts.let t0 = Date.now();const first = await answer<{ measured: unknown; parts: unknown }>(slug, owner, "storage_summary", {}); out.push(`storage_summary before any measure: ${Date.now() - t0} ms (measured ${JSON.stringify(first.measured)}, parts ${first.parts === null ? "null" : "held"})`);// The alarm's measure, a step at a time: how many steps, the longest (a request waits behind one), and the whole.let steps = 0;let longest = 0; t0 = Date.now();for (;;) {const { took, more } = await runInDurableObject(stub, (instance, s) => {const a = Date.now();const store = (instance as unknown as { store: { measureStorage(now: Date): boolean } }).store;const more = s.storage.transactionSync(() => store.measureStorage(newDate()));return { took: Date.now() - a, more }; }); steps += 1; longest = Math.max(longest, took);if (!more) break; } out.push(`measure: ${steps} steps in ${((Date.now() - t0) / 1000).toFixed(1)} s, the longest ${longest} ms`);const reads: [string, Record<string, unknown>][] = [ ["storage_summary", {}], ["storage_summary", { parts: false }], ["search_records", { q: "lighthouse keeper" }], ["search_records", { q: "lighthouse keeper", table: "prompt" }], ["list_sessions", {}], ["list_sessions", { q: "lighthouse" }], ["list_records", { table: "prompt", limit: 20 }],// Again, the order's index made: what every later page costs. ["list_records", { table: "prompt", limit: 20 }], ["list_records", { table: "prompt", limit: 20, page: 100 }], ["list_records", { table: "prompt", limit: 20, page: 200 }], ["list_records", { table: "session_message", limit: 50 }], ];// Every statement the object runs while a read runs, with the rows it read.typeSeen = { query: string; cursor: SqlStorageCursor<Record<string, SqlStorageValue>> };const seen: Seen[] = [];await runInDurableObject(stub, (_i, s) => {const sql = s.storage.sql as unknown as { exec: (q: string, ...a: SqlStorageValue[]) => SqlStorageCursor<Record<string, SqlStorageValue>>; __exec?: unknown };if (sql.__exec) return;const exec = sql.exec.bind(sql); sql.__exec = exec; sql.exec = (q, ...a) => {const cursor = exec(q, ...a); seen.push({ query: q, cursor });return cursor; }; });for (const [tool, args] of reads) { seen.length = 0;const t0 = Date.now();let failed: string | null = null;try {await answer(slug, owner, tool, args); } catch (error) { failed = String(error).slice(0, 200); }const ms = Date.now() - t0; out.push(`${tool} ${JSON.stringify(args)}: ${ms} ms${failed ? ` FAILED ${failed}` : ""}`);const heavy = newMap<string, { n: number; rows: number }>();for (const st of seen) {const key = st.query.replace(/\s+/g, " ").slice(0, 150);const h = heavy.get(key) ?? { n: 0, rows: 0 }; h.n += 1; h.rows += st.cursor.rowsRead; heavy.set(key, h); }for (const [q, h] of [...heavy].filter(([, h]) => h.rows > 2_000).sort((a, b) => b[1].rows - a[1].rows).slice(0, 4)) out.push(` ${h.rows} rows read in ${h.n}x: ${q}`); // An order index the read asked for, made as the alarm makes it (Store.buildOrderIndex).const built = await runInDurableObject(stub, (instance, s) => {const store = (instance as unknown as { store: { buildOrderIndex(): boolean; orderIndexAsked(): boolean } }).store;if (!store.orderIndexAsked()) returnnull;const a = Date.now();while (s.storage.transactionSync(() => store.buildOrderIndex()));returnDate.now() - a; });if (built !== null) out.push(` the alarm made the order index it asked for: ${built} ms`); }// The run's figures, said where a passing test can say them: as the reason a run stops (HEAVY=1 says them small too).if (BIG || (env as unknown as { HEAVY?: string }).HEAVY === "1") thrownewError(`RESULT\n${out.join("\n")}`); expect(size.rows).toBeGreaterThan(0); }, BIG ? 3_600_000 : 300_000);});