/** * ERASING ROWS FOR GOOD (owner, 22 Nov 2026): `POST /v1/admin/erase`, the * owner's act, on a personal database, that the coordinator runs on the * owner's word. Three sets, each said by its body: * * { set: "tables", tables: ["news_story", …] } every row of tables no kept app lists * { set: "unlinked_photos", ignore?: ["media.key"] } photos and videos nothing else names * { set: "old_prompts", days?: 30 } session prompts older than `days` * * Without `confirm: "erase"` a call changes nothing that is a record: it says * what would go (and, for photos, what stays and why). With it, the rows go. * Either way one call does at most WORK pieces of work and answers `more: true` * while work is left: the caller asks again with the same body until `done` * (scripts/account-verbs.ts `erase` does). A job holds its place in meta * (ERASE_JOB) and its working sets in the erase_* tables, so a call that * stops anywhere goes on with the next; no statement binds more than a few * values (the earlier prune hit "too many SQL variables"). * * WHAT GOES, per row: the row itself, its links, blind tokens, change log, * staged seal twin, the classifier's and artwork pass's notes, and the files * in R2 its clear photo and file columns name (with a picture's renditions, * `.t256.jpg` and `.d1600.jpg`), unless another row that stays names the same * key in its clear data, or an open send holds it. A whole table also loses * its day counts and what the act log said of it. * * HOW PHONES ARE TOLD. A whole table goes from storage entirely, tombstones * too, and the table is written in meta ERASED_TABLES with the version and * moment it went: every sync page that opens a pass from before that version * says `dropped: { : }`, and the phone retracts every row it * holds of the table (cotton-client transport `pull`). The rows of a filtered * set (photos, prompts) become tombstones with no data, which every sync * carries as it carries any delete. * * WHAT IS REFUSED: a whole table that a kept app's kit lists (every * registry row not retired; the personal kit, which is every table, is the * database's own, not an app's), the shell kit's, an object's internal table, * and the system tables below. A table held as retired (src/retired.ts) is * none of these, whichever kit still lists it. The filtered sets reach kept * tables on purpose and only by their own rule. */ import * as neverAgain from "./never_again.ts"; import * as blind from "./blind.ts"; import registry from "../../registry.json"; import type { Definitions, TableDef } from "./definitions.ts"; import { refuse } from "./http.ts"; import { KITS } from "./kits.ts"; import { isGoneTable, KIT_RETIRED, readRetired, TABLE_DROP_1 } from "./retired.ts"; import { isSealedColumn, isSealedRow } from "./seal.ts"; import type { Store, StoredRow } from "./store.ts"; /** The meta key holding the job under way (`Job`, as JSON). */ export const ERASE_JOB = "erase_job"; /** The meta key holding each whole table erased: `{
: { version, at } }`, read by every sync. */ export const ERASED_TABLES = "erased_tables"; /** * The work one call does before it answers `more`, in pieces: a chunk of rows * costs 4, a window of a scan 8, any other step 1. Counted, not timed: a * Worker's clock stands still while it computes (it moves only at I/O), so a * time budget would never run out. Measured on the invented object of about a * million rows (test/erase-big.test.ts): 40 pieces is a few seconds of work, * far under a request's 30 seconds of CPU. */ const WORK = 40; const COST: Partial> = { rows: 4, scan: 8, media: 8 }; /** Rows a transaction takes at a time. */ const CHUNK = 400; /** Rows of the store one window of a scan reads. */ const SCAN_WINDOW = 20_000; /** R2 calls one request makes at most (the platform allows 1,000 subrequests). */ const R2_CALLS = 800; /** The renditions the object keeps beside a picture (crates/cotton-core media::keys THUMB_SUFFIX, DISPLAY_SUFFIX). */ const RENDITIONS = [".t256.jpg", ".d1600.jpg"]; export const ERASE_SCHEMA = ` CREATE TABLE IF NOT EXISTS erase_queue (table_id TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY (table_id, id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS erase_media (key TEXT PRIMARY KEY, bytes INTEGER) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS erase_names (name TEXT NOT NULL, table_id TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY (name, table_id, id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS erase_kept (table_id TEXT NOT NULL, id TEXT NOT NULL, why TEXT NOT NULL, PRIMARY KEY (table_id, id, why)) WITHOUT ROWID; `; /** * Tables no kit lists that the Worker, MCP, the Mac or a kept app needs (CLEANUP.md §2, marks S and K). The four * AI-account tables left this list on 24 Nov 2026 (OPEN TABLES, owner: retired; assets/design/shared/OPEN-TABLES.md * §4): nothing reads them, so `{ set: "tables" }` may erase them whole. The tables TABLE DROP 1 retired (src/retired.ts: * machine, the developer tables, feedback, decision, location, the old meetings, evidence, the old message tables) * left it on 27 Nov 2026 for the same reason. */ export const SYSTEM_TABLES: readonly string[] = [ "media", "photo", "video", "person", "person_key", "vault_key", "face_settings", "record_group", "group_member", "device", "settings", "memory", "project", "project_link", "document", "session", "session_task", "session_message", "prompt", "app_report", "mcp_token", "oauth_client", "oauth_code", "oauth_refresh", "outbox", "seal_key", "message_contact_handle", "message_reaction", "blocked_sender", "email_participant", "email_sender", "note_attachment", ]; /** The tables whose rows go with a photo or video they name, and never keep one. */ const WITH_PHOTO = ["photo", "video", "face", "sighting", "duplicate"] as const; type Ask = { set: "tables"; tables: string[] } | { set: "unlinked_photos"; ignore: string[] } | { set: "old_prompts"; days: number }; type Mode = "whole" | "rows"; type Phase = "names" | "scan" | "queue" | "rows" | "tail" | "media" | "drop" | "done"; interface Job { key: string; ask: Ask; confirm: boolean; phase: Phase; at: string; /** Where a scan of the store stands (a rowid) and where it ends. */ cursor: number; end: number; size_before: number; before: Record; going: Record; gone: Record; also: { links: number; change: number; blind: number; seal_twin: number; classify: number; artwork: number; acts: number }; media: { named: number; shared: number; dropped: number; bytes: number; missing: number; sealed: number }; kept: Record; unseen: Record; version: number | null; calls: number; } export interface EraseAnswer { set: Ask["set"]; ask: Ask; /** Whether this run erases: false says what a confirmed run would. */ erased: boolean; /** Ask again with the same body while true. */ more: boolean; done: boolean; phase: Phase; /** Each table's rows when the run began, live and tombstones. */ before: Record; /** Rows the run takes, by table. */ going: Record; /** Rows gone so far, by table (a confirmed run). */ gone: Record; /** Each table's rows now. */ after: Record; also: Job["also"]; /** Files in R2 the rows named: those another row names too stay; `dropped` went (`bytes`), `missing` were not in the bucket; `sealed` rows hold theirs in a seal the object cannot read, and those files stay. */ media: Job["media"]; /** Photos only: the rows that stay, by the table and column naming them. */ kept?: Record; /** Photos only: live rows of tables whose photo or file columns are sealed, which the object cannot read; a photo only they name is not seen as named. */ unseen?: Record; size: { before: number; after: number }; version: number | null; calls: number; } /** What the act needs of the object. */ export interface EraseHost { sql: SqlStorage; store: Store; defs: Definitions; databaseId: string | null; /** The bucket key a row's media key is kept at, or null when it is not this database's. */ bucketKey(key: string): string | null; /** Whether an open send holds the key (src/send/send.ts `holds`). */ held(key: string): boolean; /** One R2 head and delete: the bytes that went, null when the bucket held nothing there. */ drop(at: string): Promise; /** Bytes off the object's media count. */ counted(bytes: number): void; transaction(fn: () => T): T; now(): Date; } /** The tables a kept app's kit lists, and the shell's: never erased whole. A retired table is never kept (TABLE DROP 1: a parked app's kit may still list it). */ export function keptTables(): Map { const out = new Map(); const keep = (id: string, why: string): void => { if (!out.has(id) && !isGoneTable(id)) out.set(id, why); }; const apps = (registry as { apps: { slug: string; kit?: string | null; retired?: unknown }[] }).apps; for (const app of apps) { if (app.retired || !app.kit || app.kit === "personal") continue; for (const t of KITS[app.kit]?.tables ?? []) keep(String(t.id), `${app.slug}'s kit`); } for (const t of KITS["shell"]?.tables ?? []) keep(String(t.id), "the shell kit"); for (const t of SYSTEM_TABLES) keep(t, "a system table"); return out; } const NAME = /^[a-z][a-z0-9_]{0,63}$/; /** The body as an ask, or a refusal saying why. */ export function readAsk(body: Record, defs: Definitions): Ask { const set = body.set; // TABLE DROP 1: exactly the 68 approved tables, each retired (src/retired.ts), so no kept kit may hold one. if (set === "table_drop_1") return { set: "tables", tables: [...TABLE_DROP_1].sort() }; if (set === "tables") { const tables = body.tables; if (!Array.isArray(tables) || tables.length === 0 || tables.length > 64) refuse(400, "bad_erase", "tables is a list of 1 to 64 table ids"); const kept = keptTables(); const names = [...new Set(tables.map(String))]; for (const t of names) { if (!NAME.test(t)) refuse(400, "bad_erase", `${JSON.stringify(t)} is no table id`); const why = kept.get(t); if (why) refuse(409, "kept_table", `${t} is ${why === "a system table" ? "a system table" : `listed by ${why}`}: it is never erased whole`); if (defs.table(t)?.raw.internal === true) refuse(409, "kept_table", `${t} is the object's own table`); } return { set, tables: names.sort() }; } if (set === "unlinked_photos") { const ignore = body.ignore === undefined ? [] : body.ignore; if (!Array.isArray(ignore) || ignore.some((g) => typeof g !== "string" || !/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(g))) refuse(400, "bad_erase", "ignore is a list of
. the dry run named as keeping photos"); return { set, ignore: [...new Set(ignore as string[])].sort() }; } if (set === "old_prompts") { const days = body.days === undefined ? 30 : body.days; if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > 3650) refuse(400, "bad_erase", "days is a whole number from 1"); return { set, days }; } return refuse(400, "bad_erase", 'set is "tables", "unlinked_photos" or "old_prompts"'); } const blank = (): Job["also"] => ({ links: 0, change: 0, blind: 0, seal_twin: 0, classify: 0, artwork: 0, acts: 0 }); function held(sql: SqlStorage, table: string): boolean { return sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", table).toArray().length > 0; } function counts(sql: SqlStorage, table: string): { live: number; tombstones: number } { const out = { live: 0, tombstones: 0 }; for (const r of sql.exec<{ deleted: number; n: number }>("SELECT deleted, count(*) AS n FROM rows WHERE table_id = ? GROUP BY deleted", table)) { if (r.deleted) out.tombstones = Number(r.n); else out.live = Number(r.n); } return out; } function tablesOf(ask: Ask): string[] { if (ask.set === "tables") return ask.tables; if (ask.set === "unlinked_photos") return [...WITH_PHOTO]; return ["prompt"]; } const modeOf = (ask: Ask): Mode => (ask.set === "tables" ? "whole" : "rows"); /** * The photo and file columns of a table, by its served definition, or the one * the keep holds as retired (src/retired.ts). A row read for its files holds * them in the clear when it is not sealed yet, whatever its table's seal says; * a sealed row's are in its blob, which the object cannot read (counted as * `media.sealed`). */ function fileColumns(host: EraseHost, table: string): string[] { const t: TableDef | undefined = host.defs.table(table); if (t) return t.columns.filter((c) => c.type === "photo" || c.type === "file").map((c) => c.key); const held = readRetired(host.store.meta(KIT_RETIRED)).table[table] as { columns?: { key?: unknown; type?: unknown }[] } | undefined; return (held?.columns ?? []).filter((c) => (c.type === "photo" || c.type === "file") && typeof c.key === "string").map((c) => String(c.key)); } /** Every media key `value` holds: a key, a list of keys, or objects in a list that carry one under `key`. */ function keysIn(value: unknown, prefix: string, out: string[]): void { if (typeof value === "string") { if (value.startsWith(prefix)) out.push(value); } else if (Array.isArray(value)) for (const v of value) keysIn(v, prefix, out); else if (value && typeof value === "object") for (const v of Object.values(value)) keysIn(v, prefix, out); } function readJob(store: Store): Job | null { const text = store.meta(ERASE_JOB); return text ? (JSON.parse(text) as Job) : null; } function clearWork(sql: SqlStorage): void { for (const t of ["erase_queue", "erase_media", "erase_names", "erase_kept"]) sql.exec(`DELETE FROM ${t}`); } /** The erased whole tables a pass from `since` must tell its phone to drop: `{ table: moment }`, or null. */ export function droppedSince(store: Store, since: number): Record | null { const text = store.meta(ERASED_TABLES); if (!text) return null; const erased = JSON.parse(text) as Record; const out: Record = {}; for (const [table, e] of Object.entries(erased)) if (e.version > since) out[table] = e.at; return Object.keys(out).length ? out : null; } /** * One call of the act: begins the job `body` asks (or goes on with it), works * at most `work` pieces (WORK), and answers where it stands. A job under way for * another ask is refused until it is done; a dry run under way gives way to * any new ask. */ export async function runErase(host: EraseHost, body: Record, work = WORK): Promise { const { sql, store } = host; sql.exec(ERASE_SCHEMA); const ask = readAsk(body, host.defs); const confirm = body.confirm === "erase"; const key = JSON.stringify(ask); let job = readJob(store); if (job && (job.key !== key || job.confirm !== confirm)) { if (job.confirm && job.phase !== "done") refuse(409, "erase_running", `an erase of ${job.key} is under way: ask it again with that body until it is done`); job = null; } if (!job || job.phase === "done") { host.transaction(() => clearWork(sql)); job = { key, ask, confirm, phase: ask.set === "unlinked_photos" ? "names" : "queue", at: host.now().toISOString(), cursor: 0, end: 0, size_before: sql.databaseSize, before: Object.fromEntries(tablesOf(ask).map((t) => [t, counts(sql, t)])), going: {}, gone: {}, also: blank(), media: { named: 0, shared: 0, dropped: 0, bytes: 0, missing: 0, sealed: 0 }, kept: {}, unseen: {}, version: null, calls: 0, }; } job.calls += 1; let spent = 0; const working: Job = job; const save = (): void => store.setMeta(ERASE_JOB, JSON.stringify(working)); let r2 = 0; // At least one piece a call, so every call moves the job on. do { spent += COST[working.phase] ?? 1; if (working.phase === "drop") r2 += await dropStep(host, working, R2_CALLS - r2); else host.transaction(() => step(host, working)); host.transaction(save); } while (working.phase !== "done" && spent < work && r2 < R2_CALLS); if (job.phase === "done") host.transaction(() => clearWork(sql)); const answer: EraseAnswer = { set: ask.set, ask, erased: confirm, more: job.phase !== "done", done: job.phase === "done", phase: job.phase, before: job.before, going: job.going, gone: job.gone, after: Object.fromEntries(tablesOf(ask).map((t) => [t, counts(sql, t)])), also: job.also, media: job.media, ...(ask.set === "unlinked_photos" ? { kept: job.kept, unseen: job.unseen } : {}), size: { before: job.size_before, after: sql.databaseSize }, version: job.version, calls: job.calls, }; return answer; } /** One bounded piece of the job's phase, in the caller's transaction. */ function step(host: EraseHost, job: Job): void { switch (job.phase) { case "names": return photoNames(host, job); case "scan": return photoScan(host, job); case "queue": return queue(host, job); case "rows": return rowsStep(host, job); case "tail": return tailStep(host, job); case "media": return mediaScan(host, job); } } // ── photos: what names them ───────────────────────────────────────────── /** The names a photo or video is known by (its id, its key, a video's poster), and what keeps one before the scan. */ function photoNames(host: EraseHost, job: Job): void { const { sql } = host; sql.exec("INSERT OR IGNORE INTO erase_names (name, table_id, id) SELECT id, table_id, id FROM rows WHERE table_id IN ('photo', 'video') AND deleted = 0"); sql.exec("INSERT OR IGNORE INTO erase_names (name, table_id, id) SELECT json_extract(data, '$.key'), table_id, id FROM rows WHERE table_id IN ('photo', 'video') AND deleted = 0 AND json_type(data, '$.key') = 'text' AND json_extract(data, '$.key') <> ''"); sql.exec("INSERT OR IGNORE INTO erase_names (name, table_id, id) SELECT json_extract(data, '$.poster_key'), table_id, id FROM rows WHERE table_id = 'video' AND deleted = 0 AND json_type(data, '$.poster_key') = 'text' AND json_extract(data, '$.poster_key') <> ''"); const ignore = new Set(job.ask.set === "unlinked_photos" ? job.ask.ignore : []); const keep = (table: string, id: string, why: string): void => { if (!ignore.has(why)) sql.exec("INSERT OR IGNORE INTO erase_kept (table_id, id, why) VALUES (?, ?, ?)", table, id, why); }; // A link column of any table but the photo's own pointing at one. const withPhoto = WITH_PHOTO.map((t) => `'${t}'`).join(", "); for (const l of sql.exec<{ t: string; c: string; pt: string; pid: string }>(`SELECT l.table_id AS t, l.column AS c, n.table_id AS pt, n.id AS pid FROM links l JOIN erase_names n ON n.name = l.target WHERE l.table_id NOT IN (${withPhoto}) AND EXISTS (SELECT 1 FROM rows r WHERE r.table_id = l.table_id AND r.id = l.id AND r.deleted = 0)`).toArray()) keep(l.pt, l.pid, `${l.t}.${l.c}`); // A photo seen in a chat (the Mac's sighting names its thread) is a chat's picture. for (const s of sql.exec<{ photo: string | null; video: string | null }>("SELECT json_extract(data, '$.photo_id') AS photo, json_extract(data, '$.video_id') AS video FROM rows WHERE table_id = 'sighting' AND deleted = 0 AND json_type(data, '$.thread_id') = 'text' AND json_extract(data, '$.thread_id') <> ''").toArray()) { if (s.photo) keep("photo", s.photo, "sighting.thread_id"); if (s.video) keep("video", s.video, "sighting.thread_id"); } // What the object cannot read: live rows of tables whose photo or file columns are sealed. for (const t of host.defs.tables.values()) { if ((WITH_PHOTO as readonly string[]).includes(t.id) || !t.seal) continue; const hidden = t.columns.filter((c) => (c.type === "photo" || c.type === "file" || (c.type === "link" && (c.link_to === "photo" || c.link_to === "video"))) && isSealedColumn(t, c.key)); if (!hidden.length) continue; const n = counts(sql, t.id).live; if (n) for (const c of hidden) job.unseen[`${t.id}.${c.key}`] = n; } job.end = Number(sql.exec<{ m: number | null }>("SELECT max(rowid) AS m FROM rows").one().m ?? 0); job.cursor = 0; job.phase = "scan"; } /** One window of the store read for a clear value equal to a photo's name, in any table but the photo's own. */ function photoScan(host: EraseHost, job: Job): void { const { sql } = host; if (job.cursor >= job.end) { tallyKept(sql, job); job.phase = "queue"; return; } const to = job.cursor + SCAN_WINDOW; const ignore = new Set(job.ask.set === "unlinked_photos" ? job.ask.ignore : []); const withPhoto = WITH_PHOTO.map((t) => `'${t}'`).join(", "); const hits = sql .exec<{ t: string; path: string; pt: string; pid: string }>( `SELECT r.table_id AS t, j.fullkey AS path, n.table_id AS pt, n.id AS pid FROM rows r, json_tree(r.data) j JOIN erase_names n ON n.name = j.atom WHERE r.rowid > ? AND r.rowid <= ? AND r.deleted = 0 AND r.table_id NOT IN (${withPhoto}) AND j.type = 'text'`, job.cursor, to, ) .toArray(); for (const h of hits) { const column = /^\$\.("?)([^."[]+)\1/.exec(h.path)?.[2] ?? "?"; const why = `${h.t}.${column}`; if (!ignore.has(why)) sql.exec("INSERT OR IGNORE INTO erase_kept (table_id, id, why) VALUES (?, ?, ?)", h.pt, h.pid, why); } job.cursor = to; } function tallyKept(sql: SqlStorage, job: Job): void { job.kept = {}; for (const k of sql.exec<{ why: string; n: number }>("SELECT why, count(DISTINCT table_id || '/' || id) AS n FROM erase_kept GROUP BY why ORDER BY why")) job.kept[k.why] = Number(k.n); job.kept["(photos and videos kept)"] = Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM (SELECT DISTINCT table_id, id FROM erase_kept)").one().n); } // ── the queue ─────────────────────────────────────────────────────────── /** What goes, into erase_queue; a dry run ends here, with the counts. */ function queue(host: EraseHost, job: Job): void { const { sql } = host; const ask = job.ask; if (ask.set === "tables") { for (const t of ask.tables) sql.exec("INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT table_id, id FROM rows WHERE table_id = ?", t); } else if (ask.set === "old_prompts") { const cutoff = new Date(host.now().getTime() - ask.days * 86_400_000).toISOString(); const old = host.store.promptsBefore(); sql.exec(`INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT 'prompt', ${old.id} FROM ${old.from} WHERE ${old.where}`, cutoff); } else { sql.exec("INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT r.table_id, r.id FROM rows r WHERE r.table_id IN ('photo', 'video') AND r.deleted = 0 AND NOT EXISTS (SELECT 1 FROM erase_kept k WHERE k.table_id = r.table_id AND k.id = r.id)"); const going = "(SELECT id FROM erase_queue WHERE table_id IN ('photo', 'video'))"; sql.exec(`INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT 'face', id FROM rows WHERE table_id = 'face' AND deleted = 0 AND (json_extract(data, '$.photo_id') IN ${going} OR json_extract(data, '$.record_id') IN ${going})`); sql.exec(`INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT 'sighting', id FROM rows WHERE table_id = 'sighting' AND deleted = 0 AND (json_extract(data, '$.photo_id') IN ${going} OR json_extract(data, '$.video_id') IN ${going} OR json_extract(data, '$.record_id') IN ${going})`); sql.exec(`INSERT OR IGNORE INTO erase_queue (table_id, id) SELECT 'duplicate', id FROM rows WHERE table_id = 'duplicate' AND deleted = 0 AND (json_extract(data, '$.keep_id') IN ${going} OR json_extract(data, '$.copy_id') IN ${going})`); } job.going = {}; for (const r of sql.exec<{ t: string; n: number }>("SELECT table_id AS t, count(*) AS n FROM erase_queue GROUP BY table_id")) job.going[r.t] = Number(r.n); if (job.confirm) { job.phase = "rows"; return; } // A dry run says what the files would be too: the keys the rows name, and how many of those a row that stays names as well. dryMedia(host, job); job.phase = "done"; } function dryMedia(host: EraseHost, job: Job): void { const { sql } = host; const prefix = host.databaseId ? `${host.databaseId}/` : null; if (!prefix) return; const named = new Set(); for (const table of Object.keys(job.going)) { const cols = fileColumns(host, table); if (!cols.length) continue; for (const r of sql.exec<{ data: string }>("SELECT r.data FROM erase_queue q JOIN rows r ON r.table_id = q.table_id AND r.id = q.id WHERE q.table_id = ?", table)) { const data = JSON.parse(r.data) as Record; const keys: string[] = []; for (const c of cols) keysIn(data[c], prefix, keys); if (isSealedRow(data) && cols.some((c) => !(c in data))) job.media.sealed += 1; for (const k of keys) named.add(k); } } job.media.named = named.size; if (!named.size) return; // Whether a row that stays names one: rows outside the queue whose clear data holds this database's keys. const shared = new Set(); const find = new RegExp(`${escapeRe(prefix)}[^"\\\\]+`, "g"); for (const r of sql.exec<{ data: string }>("SELECT data FROM rows r WHERE deleted = 0 AND instr(data, ?) > 0 AND NOT EXISTS (SELECT 1 FROM erase_queue q WHERE q.table_id = r.table_id AND q.id = r.id)", `"${prefix}`)) { for (const m of r.data.matchAll(find)) if (named.has(m[0])) shared.add(m[0]); } job.media.shared = shared.size; } const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // ── the rows ──────────────────────────────────────────────────────────── const KEYED = [ ["seal_twin", "seal_twin"], ["classify_seen", "classify"], ["artwork_seen", "artwork"], ] as const; /** One chunk of the queue: each row and what is kept for it go (a whole table), or it becomes a tombstone with no data (a filtered set). */ function rowsStep(host: EraseHost, job: Job): void { const { sql, store } = host; const mode = modeOf(job.ask); const chunk = sql.exec<{ table_id: string; id: string }>("SELECT table_id, id FROM erase_queue ORDER BY table_id, id LIMIT ?", CHUNK).toArray(); if (!chunk.length) { job.phase = mode === "whole" ? "tail" : "media"; job.cursor = 0; return; } const prefix = host.databaseId ? `${host.databaseId}/` : null; const present = KEYED.filter(([t]) => held(sql, t)); // Each chunk of tombstones its own version: a pass that ends between two chunks still carries the next. const version = mode === "rows" ? store.bump() : 0; if (mode === "rows") job.version = version; for (const { table_id: table, id } of chunk) { const row = store.any(table, id); if (row && prefix) { const cols = fileColumns(host, table); const keys: string[] = []; for (const c of cols) keysIn(row.data[c], prefix, keys); if (cols.length && isSealedRow(row.data) && cols.some((c) => !(c in row.data))) job.media.sealed += 1; const size = typeof row.data.size_bytes === "number" ? row.data.size_bytes : null; for (const k of keys) sql.exec("INSERT OR IGNORE INTO erase_media (key, bytes) VALUES (?, ?)", k, k === row.data.key ? size : null); } const rid = sql.exec<{ rid: number }>("SELECT rid FROM blind_row WHERE table_id = ? AND id = ?", table, id).toArray()[0]?.rid; if (rid !== undefined) { job.also.blind += blind.dropTokens(sql, rid); sql.exec("DELETE FROM blind_row WHERE rid = ?", rid); } job.also.change += sql.exec("DELETE FROM change WHERE table_id = ? AND record_id = ? RETURNING id", table, id).toArray().length; for (const [t, as] of present) job.also[as] += sql.exec(`DELETE FROM ${t} WHERE table_id = ? AND id = ?`, table, id).rowsWritten; if (mode === "whole") { job.also.links += sql.exec("DELETE FROM links WHERE table_id = ? AND id = ?", table, id).rowsWritten; sql.exec("DELETE FROM rows WHERE table_id = ? AND id = ?", table, id); } else if (row && !row.deleted) { job.also.links += Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM links WHERE table_id = ? AND id = ?", table, id).one().n); // Erased for good, whatever a restore puts back (src/never_again.ts). neverAgain.note(sql, { kind: "erase_row", table, id, version: Number((row as StoredRow).version), at: new Date().toISOString() }); store.tombstone(row as StoredRow, version); } sql.exec("DELETE FROM erase_queue WHERE table_id = ? AND id = ?", table, id); job.gone[table] = (job.gone[table] ?? 0) + 1; } } /** A whole table's leftovers: change entries of rows gone before, its notes, its day counts, its acts; then the phones are told. */ function tailStep(host: EraseHost, job: Job): void { const { sql, store } = host; if (job.ask.set !== "tables") return void (job.phase = "media"); const tables = job.ask.tables; const t = tables[job.cursor]; if (t === undefined) { const at = host.now().toISOString(); const version = store.bump(); job.version = version; const erased = JSON.parse(store.meta(ERASED_TABLES) ?? "{}") as Record; for (const table of tables) erased[table] = { version, at }; store.setMeta(ERASED_TABLES, JSON.stringify(erased)); // Erased for good, whatever a restore puts back (src/never_again.ts). for (const table of tables) neverAgain.note(sql, { kind: "erase_table", table, version, at }); job.phase = "media"; job.cursor = 0; return; } // Counted by what it returns: rowsWritten counts the change log's size triggers too (src/store.ts SCHEMA). const n = sql.exec("DELETE FROM change WHERE id IN (SELECT id FROM change WHERE table_id = ? LIMIT 5000) RETURNING id", t).toArray().length; job.also.change += n; if (n === 5000) return; for (const [s, as] of [...KEYED, ["classify_meta", "classify"] as const, ["links", "links"] as const]) if (held(sql, s)) job.also[as] += sql.exec(`DELETE FROM ${s} WHERE table_id = ?`, t).rowsWritten; const blindRids = sql.exec<{ rid: number }>("SELECT rid FROM blind_row WHERE table_id = ?", t).toArray(); for (const { rid } of blindRids) job.also.blind += blind.dropTokens(sql, rid); sql.exec("DELETE FROM blind_row WHERE table_id = ?", t); sql.exec("DELETE FROM row_counts WHERE table_id = ?", t); job.also.acts += scrubActs(sql, t); job.cursor += 1; } const ERASED_ARGS = JSON.stringify({ erased: "rows of an erased table" }); /** The acts whose args name `table`: one on it goes whole, a batch naming it beside others loses its args. */ function scrubActs(sql: SqlStorage, table: string): number { const like = `%"table":"${table.replace(/_/g, "\\_")}"%`; let n = 0; for (const a of sql.exec<{ id: string; args: string }>("SELECT id, args FROM acts WHERE args LIKE ? ESCAPE '\\'", like).toArray()) { let own: unknown; try { own = (JSON.parse(a.args) as { table?: unknown }).table; } catch { own = undefined; } if (own === table) sql.exec("DELETE FROM acts WHERE id = ?", a.id); else sql.exec("UPDATE acts SET args = ? WHERE id = ?", ERASED_ARGS, a.id); n += 1; } return n; } // ── the files ─────────────────────────────────────────────────────────── /** One window of the store read for a key a row that stays names: that key stays in R2. */ function mediaScan(host: EraseHost, job: Job): void { const { sql } = host; const prefix = host.databaseId ? `${host.databaseId}/` : null; const waiting = Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM erase_media").one().n); if (job.cursor === 0) { job.media.named = waiting; job.end = Number(sql.exec<{ m: number | null }>("SELECT max(rowid) AS m FROM rows").one().m ?? 0); } if (!prefix || waiting === 0 || job.cursor >= job.end) { job.phase = "drop"; return; } const to = job.cursor + SCAN_WINDOW * 2; const find = new RegExp(`${escapeRe(prefix)}[^"\\\\]+`, "g"); for (const r of sql.exec<{ data: string }>("SELECT data FROM rows WHERE rowid > ? AND rowid <= ? AND deleted = 0 AND instr(data, ?) > 0", job.cursor, to, `"${prefix}`).toArray()) { for (const m of r.data.matchAll(find)) job.media.shared += sql.exec("DELETE FROM erase_media WHERE key = ?", m[0]).rowsWritten; } job.cursor = to; } /** Up to `calls` R2 calls of the files no row that stays names: each with its renditions. Answers the calls made. */ async function dropStep(host: EraseHost, job: Job, calls: number): Promise { const { sql } = host; let made = 0; const batch = sql.exec<{ key: string }>("SELECT key FROM erase_media ORDER BY key LIMIT ?", Math.max(1, Math.floor(calls / 3))).toArray(); if (!batch.length) { job.phase = "done"; return 0; } for (const { key } of batch) { if (!host.held(key)) { const at = host.bucketKey(key); if (at) { const dot = at.lastIndexOf("."); const picture = /\/(photos|videos|documents)\//.test(at) && dot > at.lastIndexOf("/"); for (const one of [at, ...(picture ? RENDITIONS.map((r) => at.slice(0, dot) + r) : [])]) { made += 1; const bytes = await host.drop(one); if (bytes === null) { if (one === at) job.media.missing += 1; } else { if (one === at) job.media.dropped += 1; job.media.bytes += bytes; host.counted(bytes); } } } } host.transaction(() => sql.exec("DELETE FROM erase_media WHERE key = ?", key)); } return made; } // ── the prompts kept to their window ──────────────────────────────────── /** The meta key holding when the prompts were last kept to their window (ISO). */ export const PROMPTS_KEPT = "prompts_kept_at"; /** How long a session's mirrored prompts are kept (owner, 22 Nov 2026). */ export const PROMPT_DAYS = 30; /** Prompts one alarm takes at most; more come round on the next. */ const PROMPTS_A_PASS = 2_000; /** * The alarm's daily pass (owner, 22 Nov 2026): a session's mirrored prompts * older than PROMPT_DAYS become tombstones with no data, their change log * going with them, at most `most` an alarm, once a day, in the caller's * transaction. Answers how many went and whether more are left (the alarm * then comes round in a second). */ export function keepPrompts(store: Store, sql: SqlStorage, now: Date, most = PROMPTS_A_PASS): { gone: number; more: boolean } { const last = store.meta(PROMPTS_KEPT); if (last && now.getTime() - Date.parse(last) < 86_400_000) return { gone: 0, more: false }; const cutoff = new Date(now.getTime() - PROMPT_DAYS * 86_400_000).toISOString(); const old = store.promptsBefore(); const ids = sql .exec<{ id: string }>(`SELECT ${old.id} AS id FROM ${old.from} WHERE ${old.where} LIMIT ?`, cutoff, most + 1) .toArray() .map((r) => r.id); const going = ids.slice(0, most); if (going.length) { const version = store.bump(); for (const id of going) { const row = store.any("prompt", id); if (!row) continue; store.tombstone(row, version); sql.exec("DELETE FROM change WHERE table_id = 'prompt' AND record_id = ?", id); } } const more = ids.length > most; if (!more) store.setMeta(PROMPTS_KEPT, now.toISOString()); return { gone: going.length, more }; } // ── TABLE DROP 1: the export the erase answers to ─────────────────────── /** Whether a confirmed TABLE DROP 1 erase is under way: its export was checked when it began. */ export function tableDropUnderWay(store: Store): boolean { const job = readJob(store); return !!job && job.confirm && job.phase !== "done" && job.key === JSON.stringify({ set: "tables", tables: [...TABLE_DROP_1].sort() }); } /** * Each of the 68 tables whose live rows now differ from what the export holds of it: `exported` is the export's * `counts` (GET /v1/admin/export: live rows by table, a table with none left out). Empty when they all agree; null * when no export was given. */ export function exportDiffers(sql: SqlStorage, exported: unknown): Record | null { if (exported === undefined || exported === null) return null; if (typeof exported !== "object" || Array.isArray(exported)) refuse(400, "bad_export", "export is the export's counts: {
: }"); const given = exported as Record; const out: Record = {}; for (const t of TABLE_DROP_1) { const n = given[t] ?? 0; if (typeof n !== "number" || !Number.isInteger(n) || n < 0) refuse(400, "bad_export", `export.${t} is a whole number of rows`); const now = counts(sql, t).live; if (now !== n) out[t] = { exported: n, now }; } return out; }