/** * WHERE A DATABASE FILE'S BYTES GO (owner, 22 Nov 2026: his file stood at * 6.5 GB for 1.45 GB of records). An invented account built the way his is * (sealed mail, chats, mail participants and conversations, prompts, their * links, blind tokens and change log), part by part, the file's size read * after each; then each index and store table dropped in turn, so what each * part holds is read exactly (a Durable Object's SQLite gives freed pages * back, so a drop shrinks the file by the part's own bytes). Small by * default; `BIG_OBJECT=1` builds it at one fifth of his size (about 13 * minutes on the box), the run assets/design/shared/STORAGE.md quotes. */import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { BIG, personalShape, writeShape } from"./big_object.ts";import { lastMeasure, MEASURE_EVERY_MS, measureNow, measureStep } from"../src/storage_measure.ts";import { storageParts } from"../src/storage_parts.ts";import { SCHEMA } from"../src/store.ts";import { NOTES_OPEN, personalObject } from"./personal.ts";const SCALE = BIG ? 0.2 : 1 / 200;const out: string[] = [];describe("the file part by part", () => {it("measures each part, and storage_parts accounts for the whole file", async () => {const stub = env.BUSINESS.get(env.BUSINESS.idFromName("size-calibration"));let last = 0;const step = async (label: string, fn: (sql: SqlStorage) => void) => {const t0 = Date.now();await runInDurableObject(stub, (_i, s) => { fn(s.storage.sql); });const size = await runInDurableObject(stub, (_i, s) => s.storage.sql.databaseSize); out.push(`${label.padEnd(44)} +${((size - last) / 1e6).toFixed(1).padStart(8)} MB file ${(size / 1e6).toFixed(1)} MB (${Date.now() - t0} ms)`); last = size; };// The layout his file had: the blind index by row too (src/blind.ts drops it once a file moves one way).await step("schema", (sql) => { sql.exec(SCHEMA); sql.exec("CREATE INDEX IF NOT EXISTS blind_rid ON blind (rid)"); });// [table, rows at full size, average sealed data bytes, blind tokens a row, links a row]const shapes: [string, number, number, number, number][] = [ ["email", 110_715, 5_600, 360, 1], ["message", 142_694, 1_830, 25, 1], ["email_participant", 370_000, 450, 4, 1], ["email_thread", 80_000, 1_800, 22, 0], ["prompt", 108_765, 580, 0, 1], ["other", 100_000, 700, 3, 0], ];const uuid = "lower(hex(randomblob(4)))||'-'||lower(hex(randomblob(2)))||'-4'||substr(lower(hex(randomblob(2))),2)||'-a'||substr(lower(hex(randomblob(2))),2)||'-'||lower(hex(randomblob(6)))";for (const [table, full, bytes, , ] of shapes) {const n = Math.round(full * SCALE);for (let done = 0; done < n; done += 20_000) {const k = Math.min(20_000, n - done);await step(`rows ${table} ${done + k}/${n}`, (sql) => sql.exec(`WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM c WHERE i < ${k}) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT ?, ${uuid}, json_object('thread_id', ${uuid}, 'sent_at', '2025-03-04T05:06:07.000Z', '_sealed', 'v1.' || substr(hex(randomblob(${Math.ceil(bytes / 2)})), 1, ${bytes})), NULL, abs(random()) % 1000000, 0, '2025-03-04T05:06:07.000Z', '2025-03-04T05:06:07.000Z' FROM c`, table)); } }await step("links (one per linking row)", (sql) => {for (const [table, , , , links] of shapes) if (links) sql.exec("INSERT OR IGNORE INTO links (table_id, id, column, target) SELECT table_id, id, 'thread_id', json_extract(data, '$.thread_id') FROM rows WHERE table_id = ?", table); });await step("blind_row (every sealed row)", (sql) => { for (const [table, , , tokens] of shapes) if (tokens) sql.exec("INSERT INTO blind_row (table_id, id) SELECT table_id, id FROM rows WHERE table_id = ?", table); });for (const [table, , , tokens] of shapes) {if (!tokens) continue;const rids = await runInDurableObject(stub, (_i, s) => s.storage.sql.exec<{ a: number; b: number }>("SELECT MIN(rid) AS a, MAX(rid) AS b FROM blind_row WHERE table_id = ?", table).one());for (let a = Number(rids.a); a <= Number(rids.b); a += 2_000) {const b = Math.min(Number(rids.b), a + 1_999);await step(`blind ${table} rids ${a}..${b}`, (sql) => sql.exec(`WITH RECURSIVE t(j) AS (SELECT 1 UNION ALL SELECT j+1 FROM t WHERE j < ${tokens}) INSERT OR IGNORE INTO blind (tok, rid) SELECT random(), r.rid FROM blind_row r, t WHERE r.rid BETWEEN ? AND ?`, a, b)); } }const changes = Math.round(100_000 * SCALE);await step(`change log ${changes} (after = a row's data)`, (sql) => sql.exec(`INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) SELECT '2026-11-20T00:00:00.000Z', 'device:x', 'sync', table_id, id, 'create', NULL, data, version FROM rows ORDER BY random() LIMIT ${changes}`));await step("row_counts", (sql) => sql.exec("INSERT OR REPLACE INTO row_counts (table_id, day, deleted, n) SELECT table_id, substr(created_at,1,10), deleted, count(*) FROM rows GROUP BY 1,2,3"));const parts = await runInDurableObject(stub, (_i, s) => storageParts(s.storage.sql)); out.push("", `parts: file ${(parts.file / 1e6).toFixed(1)} MB carried ${(parts.carried / 1e6).toFixed(1)} MB overhead ${(parts.overhead / 1e6).toFixed(1)} MB`);for (const p of parts.parts.slice(0, 25)) out.push(` ${p.name.padEnd(48)} ${String(p.entries).padStart(10)} ${(p.bytes / 1e6).toFixed(1).padStart(8)} MB`); out.push("", "drops (exact bytes each part holds):");for (const index of ["blind_rid", "rows_made", "rows_cursor", "rows_owner", "links_target", "change_record", "change_at", "rows_message_minute"]) await step(`drop index ${index}`, (sql) => sql.exec(`DROP INDEX ${index}`));for (const table of ["change", "blind", "blind_row", "links"]) await step(`drop table ${table}`, (sql) => sql.exec(`DROP TABLE ${table}`)); console.log(out.join("\n")); expect(parts.carried + parts.overhead).toBe(parts.file);constof = (name: string) => parts.parts.find((p) => p.name === name)!;// Each sealed row's tokens are held twice, by token and by row: the two indexes carry the same entries. expect(of("blind").entries).toBe(of("blind_rid").entries); expect(of("blind").entries).toBeGreaterThan(of("rows").entries * 10);const end = await runInDurableObject(stub, (_i, s) => s.storage.sql.databaseSize); expect(end, "the drops gave their pages back").toBeLessThan(parts.file / 1.5);}, 3_600_000);});/** RULE (coordinator, 23 Nov 2026: his storage_summary took 13 to 25 s): a big object's figures are its alarm's, a step at a time, and they add up to what one pass works out. */describe("the storage measure, a step at a time", () => { it("adds its steps up to the one-pass figures, keeps its place between alarms, and begins again only when stale", async () => {const slug = "storage-measure-steps";await personalObject(slug, { open: NOTES_OPEN.open });const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));await runInDurableObject(stub, (_i, s) => { writeShape(s.storage.sql, personalShape(1 / 400));// Search tokens, a WITHOUT ROWID table read along its key. s.storage.sql.exec("WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000) INSERT OR IGNORE INTO blind (tok, rid) SELECT x % 977, x FROM c"); s.storage.sql.exec("WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 3000) INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) SELECT '2026-11-01T00:00:00Z', NULL, CASE WHEN x % 3 = 0 THEN 'fetch_progress' ELSE 'update_record' END, 'note', printf('n%05d', x), 'update', json_object('body', hex(randomblob(40))), NULL, 1 FROM c"); });const { whole, steps, stale, fresh } = await runInDurableObject(stub, (_i, s) => {const sql = s.storage.sql;const kept = newMap<string, string | null>();const host = { sql, meta: (k: string) => kept.get(k) ?? null, setMeta: (k: string, v: string | null) => void kept.set(k, v) };const at = newDate("2026-11-23T10:00:00Z");const whole = measureNow(sql, at);let steps = 0;// Ranges of 700 rows, one a call (no work budget still takes one range a call): the place is kept in meta between calls.while (measureStep(host, at, 0, 700)) steps += 1;const measure = lastMeasure(host);const fresh = measureStep(host, newDate(at.getTime() + 60_000), Infinity);const later = newDate(at.getTime() + MEASURE_EVERY_MS + 1);while (measureStep(host, later, Infinity));const stale = lastMeasure(host)!.at === later.toISOString();// An alarm's call does its work budget and no more, however fast it goes (a Worker's clock stands still through// synchronous work, so no time budget can stop it: LIVE CPU 4): with a budget of 20,000 units and 700-row ranges it// takes more calls than one range a call would, never all in one.const again = newMap<string, string | null>();const host2 = { sql, meta: (k: string) => again.get(k) ?? null, setMeta: (k: string, v: string | null) => void again.set(k, v) };let calls = 1;while (measureStep(host2, at, 20_000, 700)) calls += 1;return { whole, steps: { n: steps, measure, calls }, stale, fresh }; }); expect(steps.n, "it took many steps").toBeGreaterThan(10); expect(steps.calls, "a budgeted call does several ranges, and stops").toBeGreaterThan(1); expect(steps.calls).toBeLessThan(steps.n + 1);const m = steps.measure!; expect(m.parts.parts).toEqual(whole.parts.parts); expect(m.tables).toEqual(whole.tables); expect(m.changes_by).toEqual(whole.changes_by); expect(m.changes_by.find((c) => c.via === "fetch_progress")?.entries).toBe(1000); expect(m.parts.parts.find((p) => p.name === "blind")?.entries).toBe(5000); expect(stale, "a measure older than six hours is begun again").toBe(true); expect(fresh, "a fresh one is not").toBe(false); }, 300_000);});