154 lines · 9.7 KB · TypeScriptRaw
/** * THE ERASE ON AN OBJECT AS LARGE AS THE OWNER'S (22 Nov 2026). The invented * object of the personal one's shape (test/big_object.ts at 1.25: about a * million rows), with every retired set at the owner's sizes (a few rows to * 7,000 a table) and 20,000 session prompts. Erased through the route, a * bounded call at a time, while Comms (message, thread) syncs before and * after: Comms' rows are the same, the retired tables are empty, the file is * smaller, a phone behind is told which tables to drop. The photos' dry run * is timed over the whole store. Printed (`--disableConsoleIntercept`); * `BIG_OBJECT=1` runs it at full size. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { EraseAnswer } from "../src/erase.ts";import type { SyncAnswer } from "../src/protocol.ts";import { BIG, personalShape, writeShape } from "./big_object.ts";import { KIT_RETIRED } from "../src/retired.ts";import { ADMIN, DATABASE_ID, http, personalObject } from "./personal.ts";import THOUGHT from "./fixtures/thought.json"; // the retired definition as it shipped (TABLE DROP 1)const SCALE = BIG ? 1.25 : 1 / 40;const n = (rows: number): number => Math.max(1, Math.round(rows * (BIG ? 1 : 1 / 40)));/** The retired sets and their invented sizes (the owner's tables hold from a few rows to 7,000). */const SETS: Record<string, Record<string, number>> = { allinone: { news_edition: 300, news_seen: 3_000, news_settings: 1, news_story: 7_000, news_topic: 40, thought: 500, thought_attachment: 200, mood: 900, goal: 30, alarm: 20, post: 50, repository: 10, repo_bundle: 10, repo_clone: 10, repo_comment: 2_000, repo_commit: 7_000, repo_job: 500, repo_label: 40, repo_merge_queue: 5, repo_rule: 5, repo_runner: 3, repo_var: 10, run: 3_000, pull: 600, issue: 400, release: 50, document_page: 100, },};// The podcasts, pages, trips and recipes sets are refused while their apps stand in apps/registry.json (their kits are a kept app's): measured once those rows leave it.describe("the erase on a very large object", () => { it("empties the retired tables in bounded calls while Comms syncs the same, and the file shrinks", async () => { const slug = "erase-big"; const { credential } = await personalObject(slug); const auth = ADMIN; const phone = { authorization: `Bearer ${credential}` }; const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const built = await runInDurableObject(stub, (_i, state) => { const sql = state.storage.sql; let upto = writeShape(sql, personalShape(SCALE)) + 1_000; const add = (table: string, count: number, data: string): void => { 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 ?, printf('%s-%08d', ?, x), ${data}, NULL, ? + x, x % 23 = 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, count, table, table, upto, ); upto += count; }; for (const set of Object.values(SETS)) for (const [table, rows] of Object.entries(set)) { const data = table === "thought" ? `json_object('text', 'an invented thought ' || x, 'audio_url', CASE WHEN x % 5 = 0 THEN '${DATABASE_ID}/thoughts/' || x || '.m4a' END)` : `json_object('title', 'an invented ${table} ' || x, 'body', hex(randomblob(300)))`; add(table, n(rows), data); } add("prompt", n(20_000), `json_object('ts', strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-' || (x % 75) || ' days'), 'text', hex(randomblob(400)))`); // A link and a change of a retired row, and a neighbour that keeps one of its files. sql.exec("INSERT INTO links (table_id, id, column, target) SELECT table_id, id, 'repository', 'repository-00000001' FROM rows WHERE table_id = 'repo_commit'"); sql.exec("INSERT INTO change (at, table_id, record_id, kind, version) SELECT '2025-06-01T00:00:00Z', table_id, id, 'update', version FROM rows WHERE table_id IN ('news_story', 'run')"); sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('note', 'keeps-a-file', ?, NULL, ?, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z')", JSON.stringify({ cover: `${DATABASE_ID}/thoughts/5.m4a` }), upto + 1); sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", String(upto + 2)); // An object that held these tables keeps their definitions aside as the keep retired them (TABLE DROP 1, src/retired.ts): // where the erase reads a thought's file column from. sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", KIT_RETIRED, JSON.stringify({ table: { thought: THOUGHT }, tool: {} })); return { total: Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows").one().n), size: sql.databaseSize, version: upto + 2 }; }); for (let x = 5; x <= n(500); x += 5) await env.MEDIA.put(`${slug}/thoughts/${x}.m4a`, "invented sound"); const comms = async (): Promise<string[]> => { const out: string[] = []; let path = "/v1/sync?since=0&limit=10000&tables=message,thread"; for (;;) { const page = await http<SyncAnswer>(slug, "GET", path, undefined, phone); expect(page.status).toBe(200); for (const r of page.body.rows) out.push(`${r.table}/${r.id}/${r.version}/${r.deleted ? 1 : 0}`); if (!page.body.next) return out.sort(); path = `/v1/sync?cursor=${page.body.next}`; } }; const t0 = Date.now(); const commsBefore = await comms(); const commsMs = Date.now() - t0; const lines: string[] = [`the invented object: ${built.total} rows, ${(built.size / 1e6).toFixed(0)} MB; Comms' pass ${commsBefore.length} rows in ${commsMs} ms`]; const run = async (body: Record<string, unknown>): Promise<{ last: EraseAnswer; calls: number; ms: number; worst: number }> => { const begun = Date.now(); let worst = 0; for (let calls = 1; calls < 2_000; calls++) { const at = Date.now(); const res = await http<EraseAnswer>(slug, "POST", "/v1/admin/erase", body, auth); worst = Math.max(worst, Date.now() - at); expect(res.status, JSON.stringify(res.body)).toBe(200); if (res.body.done) return { last: res.body, calls, ms: Date.now() - begun, worst }; } throw new Error("never done"); }; const shrunk = { before: Infinity, after: 0 }; for (const [name, set] of Object.entries(SETS)) { const tables = Object.keys(set); const dry = await run({ set: "tables", tables }); const done = await run({ set: "tables", tables, confirm: "erase" }); const rows = Object.values(done.last.gone).reduce((a, b) => a + b, 0); expect(rows).toBe(Object.values(dry.last.going).reduce((a, b) => a + b, 0)); for (const t of tables) expect(done.last.after[t], t).toEqual({ live: 0, tombstones: 0 }); shrunk.before = Math.min(shrunk.before, done.last.size.before); shrunk.after = done.last.size.after; lines.push( `set ${name}: dry run ${dry.ms} ms; erased ${rows} rows in ${done.calls} calls, ${done.ms} ms (slowest call ${done.worst} ms); also ${JSON.stringify(done.last.also)}; media ${JSON.stringify(done.last.media)}; file ${(done.last.size.before / 1e6).toFixed(1)} → ${(done.last.size.after / 1e6).toFixed(1)} MB`, ); } expect(await env.MEDIA.head(`${slug}/thoughts/5.m4a`), "a file a note names stays").not.toBeNull(); expect(await env.MEDIA.head(`${slug}/thoughts/10.m4a`)).toBeNull(); const photos = await run({ set: "unlinked_photos" }); lines.push(`photos' dry run: ${photos.calls} calls, ${photos.ms} ms (slowest ${photos.worst} ms); going ${JSON.stringify(photos.last.going)}; kept ${JSON.stringify(photos.last.kept)}; unseen ${JSON.stringify(photos.last.unseen)}`); const prompts = await run({ set: "old_prompts", confirm: "erase" }); lines.push(`prompts: ${JSON.stringify(prompts.last.gone)} in ${prompts.calls} calls, ${prompts.ms} ms; left ${JSON.stringify(prompts.last.after.prompt)}`); const commsAfter = await comms(); expect(commsAfter, "Comms syncs the same rows, at the same versions").toEqual(commsBefore); const behind = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${built.version}&tables=message,thread`, undefined, phone); expect(Object.keys(behind.body.dropped ?? {}).sort()).toEqual(Object.values(SETS).flatMap((s) => Object.keys(s)).sort()); const after = await runInDurableObject(stub, (_i, state) => { const sql = state.storage.sql; const size = sql.databaseSize; const pragma = (p: string): string => { try { return JSON.stringify(sql.exec(`PRAGMA ${p}`).toArray()); } catch (e) { return `refused (${e instanceof Error ? e.message : String(e)})`; } }; let vacuum = `auto_vacuum ${pragma("auto_vacuum")}, freelist ${pragma("freelist_count")}`; try { sql.exec("VACUUM"); vacuum += `; ${(sql.databaseSize / 1e6).toFixed(1)} MB after VACUUM`; } catch (e) { vacuum += `; VACUUM refused: ${e instanceof Error ? e.message : String(e)}`; } return { size, vacuum, total: Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows").one().n) }; }); lines.push(`after: ${after.total} rows, ${(after.size / 1e6).toFixed(1)} MB (was ${(built.size / 1e6).toFixed(1)} MB); ${after.vacuum}`); console.log(`\n${lines.join("\n")}`); // The file is smaller once the retired rows are gone; what the photos' dry run and the prompts' tombstones then write is measured beside it. expect(shrunk.after, "the file shrinks with the retired rows").toBeLessThan(shrunk.before); }, 3_000_000);});