Cotton code
144 lines · 7.3 KB · TypeScriptRaw
/** * THE UNDO-HISTORY TRIM, KILLED HALFWAY (coordinator for the owner, 23 Nov 2026): what a deploy or an eviction does * to a trim under way. A local `wrangler dev` holds an invented account with old-style history (planted as on the * dev Worker, scripts/undo-shrink-proof.ts), the switch is set, and the Worker is killed outright (SIGKILL, no * goodbye) three times while the trim runs, each time started again on the same files. Then the object's file is * opened directly: the log left must be the newest entries with no gap, its counted size must be its real size, * and every record must stand as before. * *   cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-undo-shrink-killed.ts [--entries 30000] [--kills 3] * * Invented data only, on this machine only; the temp folder goes however it ends. */import { spawnSync, type ChildProcess } from "node:child_process";import { randomBytes } from "node:crypto";import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { signIn, type Session } from "../dev-seed/client.ts";import { check, startWrangler } from "./dev-worker.ts";const arg = (name: string, fallback: string) => (process.argv.includes(`--${name}`) ? process.argv[process.argv.indexOf(`--${name}`) + 1]! : fallback);const ENTRIES = Number(arg("entries", "30000"));const KILLS = Number(arg("kills", "3"));const BUDGET = 100_000_000;const say = (line: string) => console.log(`[killed] ${new Date().toISOString().slice(11, 19)} ${line}`);// The same keys every start, so the account's sign-in and tokens hold across the kills.const KEYS = { VAULT_KEY: randomBytes(32).toString("base64url"), SERVICE_TOKEN_KEY: randomBytes(32).toString("base64url"), WINDOW_KEY: randomBytes(32).toString("base64url") };const tmp = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "undo-killed-"));let child: ChildProcess | null = null;const kill = () => {  if (child?.pid) {    try {      process.kill(-child.pid, "SIGKILL");    } catch {      /* gone */    }  }  child = null;};process.on("exit", () => {  kill();  rmSync(tmp, { recursive: true, force: true });});let base = "";async function call<T>(method: string, path: string, body?: unknown): Promise<T> {  const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${s.token}` }, body: body === undefined ? undefined : JSON.stringify(body) });  const text = await res.text();  if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${text.slice(0, 300)}`);  return JSON.parse(text) as T;}const summary = async () => {  const r = await call<{ result: { content: { text: string }[] } }>("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "storage_summary", arguments: { parts: false } } });  return JSON.parse(r.result.content[0]!.text) as { change_log: { rows: number; chars?: { counted: number; ready: boolean } } };};const exportRows = async () => {  const out = new Map<string, string>();  let after: string | null = null;  for (;;) {    const page: { rows: { table: string; id: string; version: number; data: unknown }[]; next: string | null } = await call("GET", `/v1/admin/export?limit=5000${after ? `&after=${encodeURIComponent(after)}` : ""}`);    for (const r of page.rows) if (r.table !== "mcp_token") out.set(`${r.table}/${r.id}`, `${r.version} ${JSON.stringify(r.data)}`);    if (!page.next) return out;    after = page.next;  }};const up = async () => {  const w = await startWrangler(tmp, (c) => (child = c), KEYS);  base = w.base;};await up();const s: Session = await signIn(base, "+15550109201", "123456");const ids: string[] = [];for (let i = 0; i < 400; i += 200) {  const rows = Array.from({ length: 200 }, (_x, k) => ({ table: "decision", id: crypto.randomUUID(), data: { title: `Invented decision ${i + k}` } }));  await call("POST", "/v1/admin/import", { rows });  ids.push(...rows.map((r) => r.id));}for (let from = 0; from < ENTRIES; from += 1000) await call("POST", "/v1/admin/dev/plant-history", { table: "decision", records: ids, entries: Math.min(1000, ENTRIES - from), chars: 29_300, days: 90, from, of: ENTRIES });const before = await exportRows();const start = await summary();say(`planted: ${start.change_log.rows} entries, ${before.size} live rows`);await call("PUT", "/v1/admin/business", { change_days: 30, change_bytes: BUDGET });const t0 = Date.now();let kills = 0;let last = start.change_log.rows;for (;;) {  await new Promise((done) => setTimeout(done, 700));  let now;  try {    now = await summary();  } catch (error) {    say(`read refused: ${error instanceof Error ? error.message.slice(0, 120) : String(error)}`);    continue;  }  const counted = now.change_log.chars;  // Killed in the counting once, then twice while the entries go.  const counting = counted !== undefined && !counted.ready;  const due = kills === 0 ? counting || now.change_log.rows < start.change_log.rows : now.change_log.rows < start.change_log.rows - 4_000 * kills && now.change_log.rows > ENTRIES / 4;  if (kills < KILLS && due) {    // Each kill is a different moment of the trim: counting first, then while entries go.    kill();    kills++;    say(`KILLED ${kills}: at ${now.change_log.rows} entries, counted ${counted ? `${(counted.counted / 1e6).toFixed(0)} MB${counted.ready ? "" : " (counting)"}` : "not yet"}`);    await up();    continue;  }  if (counted?.ready && counted.counted <= BUDGET && now.change_log.rows === last) break;  last = now.change_log.rows;  if (Date.now() - t0 > 900_000) throw new Error("the trim did not end in 15 minutes");}const after = await exportRows();const end = await summary();say(`trimmed: ${start.change_log.rows} -> ${end.change_log.rows} entries in ${((Date.now() - t0) / 1000).toFixed(0)} s across ${kills} kills`);kill();// The object's own file, read directly once the Worker is down: the biggest .sqlite under the persisted state.const files: string[] = [];const walk = (dir: string) => {  for (const f of readdirSync(dir)) {    const p = join(dir, f);    if (statSync(p).isDirectory()) walk(p);    else if (p.endsWith(".sqlite")) files.push(p);  }};walk(join(tmp, "state"));const file = files.sort((a, b) => statSync(b).size - statSync(a).size)[0]!;const q = (sql: string) => spawnSync("sqlite3", ["-readonly", file, sql], { encoding: "utf8" }).stdout.trim();const [n, first, lastId, real] = q("SELECT COUNT(*), MIN(id), MAX(id), SUM(coalesce(length(before),0)+coalesce(length(after),0)) FROM change").split("|").map(Number);const counted = Number(q("SELECT bytes FROM change_size"));const newest = Number(q("SELECT MAX(id) FROM change WHERE kind = 'update' AND via = 'update'"));say(`FILE: ${n} entries, ids ${first}..${lastId}, real ${(real! / 1e6).toFixed(1)} MB, counted ${(counted / 1e6).toFixed(1)} MB`);let same = 0;for (const [k, v] of before) if (after.get(k) === v) same++;check(lastId! - first! + 1 === n, "what is left is the newest, with no gap");check(counted === real, "the counted size is the real size");check(real! <= BUDGET, "the log fits its budget");check(newest === lastId || lastId! >= newest, "the newest entry stands");check(same === before.size && after.size === before.size, `every record as before (${same} of ${before.size})`);say(`PASSED: ${kills} kills, nothing half-deleted, ${same} of ${before.size} records identical`);process.exit(0);