/** * RULE (owner, 27 Nov 2026: TABLE DROP 1, step 3): `POST /v1/admin/retired/erase` erases, for good, every row, * tombstone, change-log entry, link, act line and R2 file of the 68 approved tables (src/retired.ts TABLE_DROP_1) and * nothing else. Without `confirm: "erase"` it is a dry run that counts each table's rows and files. A confirmed run * begins only when `export` (the export's `counts`) agrees with every one of the 68 tables' live rows. It works a * bounded piece a call and says `more` until done; a run stopped anywhere goes on with the next call. Proven here on a * seeded throwaway account: every kept table byte for byte the same (a hash before and after), the 68 empty, the media * count and the row counts lower, and phones told. */import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";importtype { EraseAnswer } from"../src/erase.ts";importtype { SyncAnswer } from"../src/protocol.ts";import { GONE_TABLES, KIT_RETIRED, TABLE_DROP_1 } from"../src/retired.ts";import { ADMIN, DATABASE_ID, http, personalObject } from"./personal.ts";import THOUGHT from"./fixtures/thought.json";const ROUTE = "/v1/admin/retired/erase";const AT = "2026-10-01T06:00:00.000Z";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const KEY = (rest: string): string => `${DATABASE_ID}/${rest}`;const DROP = newSet(TABLE_DROP_1);const IN_DROP = `(${TABLE_DROP_1.map((t) => `'${t}'`).join(", ")})`;typeAnswer = EraseAnswer & { export: Record<string, { exported: number; now: number }> | null };typeRow = [table: string, id: string, data: Record<string, unknown>, deleted?: number];asyncfunction seed(slug: string, rows: Row[], links: [string, string, string, string][]): Promise<void> {await runInDurableObject(stub(slug), (_i, state) => {const sql = state.storage.sql;let v = Number(sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").toArray()[0]?.value ?? "0");for (const [table, id, data, deleted = 0] of rows) { v += 1; sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, ?, ?, ?)", table, id, JSON.stringify(data), v, deleted, AT, AT); }for (const [table, id, column, target] of links) sql.exec("INSERT INTO links (table_id, id, column, target) VALUES (?, ?, ?, ?)", table, id, column, target); sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", String(v)); });}/** A hash of everything the erase must leave alone: every row, link and change-log entry of every table outside the 68. */asyncfunction keptHash(slug: string): Promise<{ hash: string; rows: number }> {const text = await runInDurableObject(stub(slug), (_i, state) => {const sql = state.storage.sql;const rows = sql.exec<{ r: string }>(`SELECT table_id || '|' || id || '|' || version || '|' || deleted || '|' || data || '|' || created_at || '|' || updated_at AS r FROM rows WHERE table_id NOT IN ${IN_DROP} ORDER BY table_id, id`).toArray().map((x) => x.r);const links = sql.exec<{ r: string }>(`SELECT table_id || '|' || id || '|' || column || '|' || target AS r FROM links WHERE table_id NOT IN ${IN_DROP} ORDER BY 1`).toArray().map((x) => x.r);const change = sql.exec<{ r: string }>(`SELECT table_id || '|' || record_id || '|' || kind || '|' || version AS r FROM change WHERE table_id NOT IN ${IN_DROP} ORDER BY 1`).toArray().map((x) => x.r);return { text: [...rows, "--", ...links, "--", ...change].join("\n"), rows: rows.length }; });const digest = await crypto.subtle.digest("SHA-256", newTextEncoder().encode(text.text));return { hash: [...newUint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""), rows: text.rows };}asyncfunction held(slug: string): Promise<{ drop: number; media: number; counted: string[] }> {return runInDurableObject(stub(slug), (_i, state) => {const sql = state.storage.sql;return { drop: Number(sql.exec<{ n: number }>(`SELECT count(*) AS n FROM rows WHERE table_id IN ${IN_DROP}`).one().n), media: Number(sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'media_bytes'").toArray()[0]?.value ?? "0"), counted: sql.exec<{ t: string }>(`SELECT DISTINCT table_id AS t FROM row_counts WHERE table_id IN ${IN_DROP}`).toArray().map((r) => r.t), }; });}describe("TABLE DROP 1's erase", () => { it("names exactly the 68 approved tables, each retired, and none of the 13 retired before them", () => { expect(TABLE_DROP_1).toHaveLength(68); expect(newSet(TABLE_DROP_1).size).toBe(68);for (const t of TABLE_DROP_1) expect(GONE_TABLES, t).toContain(t);for (const t of ["screenplay", "recipe", "trip", "page_highlight"]) expect(DROP.has(t), t).toBe(false); }); it("dry-runs with counts per table, refuses without a matching export, then erases only the 68, resumably, and leaves every other table byte for byte", async () => {const slug = "table-drop-erase";const { credential } = await personalObject(slug, { open: ["note"] });// The keep held the retired definitions aside (src/retired.ts KIT_RETIRED): where the erase reads a thought's file column.await runInDurableObject(stub(slug), (_i, state) => { state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", KIT_RETIRED, JSON.stringify({ table: { thought: THOUGHT }, tool: {} })); state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('media_bytes', '1000')"); });const rows: Row[] = [];// One invented row in every one of the 68, more in two, some of them tombstones.for (const t of TABLE_DROP_1) rows.push([t, `${t}-1`, { title: `invented ${t}` }]);for (let i = 0; i < 5_000; i++) rows.push(["transaction", `tx-${String(i).padStart(5, "0")}`, { description: `invented ${i}`, amount_minor: i }, i % 9 === 0 ? 1 : 0]);for (let i = 0; i < 30; i++) rows.push(["news_story", `ns-${i}`, { title: `story ${i}` }, i % 3 === 0 ? 1 : 0]); rows.push(["thought", "th-file", { text: "invented", audio_url: KEY("thoughts/only.m4a") }]); rows.push(["thought", "th-shared", { text: "invented", audio_url: KEY("thoughts/shared.m4a") }]);// What stays: kept tables, a table retired before TABLE DROP 1, and a neighbour linking an erased row.for (let i = 0; i < 25; i++) rows.push(["note", `note-${i}`, { title: `kept note ${i}` }]); rows.push(["note", "note-shared", { title: "names a shared file", cover: KEY("thoughts/shared.m4a") }]); rows.push(["todo", "todo-1", { title: "kept todo", thought: "thought-1" }]); rows.push(["recipe", "recipe-1", { title: "retired before, not in the drop" }]);await seed(slug, rows, [["todo", "todo-1", "thought", "thought-1"], ["transaction", "tx-00001", "account", "money_account-1"]]);await runInDurableObject(stub(slug), (_i, state) => {const sql = state.storage.sql; sql.exec("INSERT INTO change (at, table_id, record_id, kind, version) VALUES (?, 'transaction', 'tx-00002', 'update', 1), (?, 'mood', 'mood-1', 'update', 1), (?, 'note', 'note-1', 'update', 1)", AT, AT, AT); sql.exec("INSERT INTO acts (id, at, act, args, outcome) VALUES ('a-gone', ?, 'create', ?, 'ok'), ('a-kept', ?, 'create', ?, 'ok')", AT, JSON.stringify({ table: "mood", data: {} }), AT, JSON.stringify({ table: "note", data: {} })); });for (const k of ["thoughts/only.m4a", "thoughts/shared.m4a"]) await env.MEDIA.put(`${slug}/${k}`, "invented sound bytes");const kept = await keptHash(slug);const phoneAt = await runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").one().value));const exported = (await http<{ counts: Record<string, number> }>(slug, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body.counts;// A dry run: each table's rows, the files, and nothing changed.const dry = await http<Answer>(slug, "POST", ROUTE, {}, ADMIN); expect(dry.status, JSON.stringify(dry.body).slice(0, 400)).toBe(200); expect(dry.body).toMatchObject({ erased: false, done: true, media: { named: 2, shared: 1 }, export: null }); expect(Object.keys(dry.body.going).sort()).toEqual([...TABLE_DROP_1].sort()); expect(dry.body.going.transaction).toBe(5_001); expect(dry.body.before.transaction).toEqual({ live: 5_001 - 556, tombstones: 556 }); expect(dry.body.going.recipe).toBeUndefined(); expect(await keptHash(slug)).toEqual(kept); expect((await held(slug)).drop).toBe(68 + 5_000 + 30 + 2);// A dry run with the export says where it differs: here nowhere. expect((await http<Answer>(slug, "POST", ROUTE, { export: exported }, ADMIN)).body.export).toEqual({});// Confirmed: refused with no export, and with one that does not match. expect(await http(slug, "POST", ROUTE, { confirm: "erase" }, ADMIN)).toMatchObject({ status: 400, body: { code: "export_needed" } });const stale = { ...exported, transaction: (exported.transaction ?? 0) - 1 };const refused = await http<{ code: string; message: string }>(slug, "POST", ROUTE, { confirm: "erase", export: stale }, ADMIN); expect(refused.status).toBe(409); expect(refused.body).toMatchObject({ code: "export_mismatch" }); expect(refused.body.message).toContain("transaction exported 4444, holds 4445"); expect((await held(slug)).drop, "nothing went").toBe(68 + 5_000 + 30 + 2);// Not the owner's token: the admin token only. expect(await http(slug, "POST", ROUTE, { confirm: "erase", export: exported }, { authorization: `Bearer ${credential}` })).toMatchObject({ status: 403 });// Confirmed with the export: a bounded piece a call, `more` until done.const runs: Answer[] = [];for (let i = 0; i < 50 && !runs.at(-1)?.done; i++) {const res = await http<Answer>(slug, "POST", ROUTE, { confirm: "erase", export: exported }, ADMIN); expect(res.status, JSON.stringify(res.body).slice(0, 400)).toBe(200); runs.push(res.body); } expect(runs.length, "more than one call: it works in bounded pieces and goes on").toBeGreaterThan(1); expect(runs[0]!.more).toBe(true);const last = runs.at(-1)!; expect(last).toMatchObject({ erased: true, done: true, media: { named: 2, shared: 1, dropped: 1 } }); expect(last.gone.transaction).toBe(5_001);for (const t of TABLE_DROP_1) expect(last.after[t], t).toEqual({ live: 0, tombstones: 0 });// Kept: byte for byte. Gone: every row, link, change entry, act line and file of the 68, and their counts. expect(await keptHash(slug), "every kept table byte for byte as it was").toEqual(kept);const after = await held(slug); expect(after.drop).toBe(0); expect(after.counted).toEqual([]); expect(after.media, "the media count drops by the file that went").toBe(1000 - "invented sound bytes".length); expect(await env.MEDIA.head(`${slug}/thoughts/only.m4a`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/thoughts/shared.m4a`), "a file a kept note names stays").not.toBeNull();await runInDurableObject(stub(slug), (_i, state) => {const sql = state.storage.sql;const n = (q: string) => Number(sql.exec<{ n: number }>(`SELECT count(*) AS n FROM ${q}`).one().n); expect(n(`links WHERE table_id IN ${IN_DROP}`)).toBe(0); expect(n(`change WHERE table_id IN ${IN_DROP}`)).toBe(0); expect(n("acts WHERE id = 'a-gone'")).toBe(0); expect(n("acts WHERE id = 'a-kept'")).toBe(1); expect(n("rows WHERE table_id = 'recipe'"), "a table retired before the drop stays").toBe(1); });const counts = (await http<{ counts: Record<string, number> }>(slug, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body.counts;for (const t of TABLE_DROP_1) expect(counts[t], t).toBeUndefined();// Phones are told: a pass from before the erase names the 68 tables that held rows as dropped.const behind = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${phoneAt}`, undefined, { authorization: `Bearer ${credential}` });for (const t of ["transaction", "news_story", "thought", "mood"]) expect(Object.keys(behind.body.dropped ?? {}), t).toContain(t);// Again: nothing left to go, and a new confirmed run checks the export anew (all zero now).const zero = Object.fromEntries(TABLE_DROP_1.map((t) => [t, 0]));const again = await http<Answer>(slug, "POST", ROUTE, { confirm: "erase", export: zero }, ADMIN); expect(again.status, JSON.stringify(again.body).slice(0, 300)).toBe(200); expect(again.body.going).toEqual({}); });});