/** * THE UNDO-HISTORY PROOF'S PLANTING ROUTE, AND THE TRIM ON WHAT IT PLANTS (coordinator for the owner, 23 Nov 2026). * `POST /v1/admin/dev/plant-history` (dev and test Workers only) adds old-style change-log entries, a sealed body * before and after, spread back over some days, on records that exist, so the dev Worker can hold an invented * account with the owner's undo history. It writes no record. Then, small: the per-account switch is off until set * (an alarm trims nothing); once set to 30 days, the planted entries older than that go, every record and its version * stand as they were, and a recent change is still undone. Invented records only. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { ADMIN, answer, http, NOTES_OPEN, personalObject } from "./personal.ts"; /** The object's own alarm, as the class defines it: run even while `quiet` has silenced the runtime's. */ const ownAlarm = (instance: unknown): Promise => (Object.getPrototypeOf(instance) as { alarm(this: unknown): Promise }).alarm.call(instance); const alarm = (slug: string) => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (instance, s) => { await s.storage.deleteAlarm(); await ownAlarm(instance); await s.storage.deleteAlarm(); }); /** * No alarm runs on the object but the ones the test runs (a flake in the full suite under load, 26 Nov 2026): the * writes before schedule a real alarm, and one already running when the test deletes the alarm re-arms itself at its * end, a second on while it is trimming, so real alarms went on trimming the log between the test's own reads. The * runtime's alarm becomes a no-op on this instance, the alarm is deleted, and any alarm still running (the object * marks it, `alarm_running`) is waited out. */ async function quiet(slug: string): Promise { const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); await runInDurableObject(stub, async (instance, s) => { (instance as { alarm: () => Promise }).alarm = async () => {}; await s.storage.deleteAlarm(); }); for (let i = 0; i < 1200; i++) { const running = await runInDurableObject(stub, (_i, s) => s.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'alarm_running'").toArray()[0]?.value ?? null); if (running === null) break; await new Promise((done) => setTimeout(done, 50)); } await runInDurableObject(stub, (_i, s) => s.storage.deleteAlarm()); } const log = (slug: string) => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, s) => s.storage.sql.exec<{ n: number; old: number }>(`SELECT COUNT(*) AS n, SUM(at < ?) AS old FROM change`, new Date(Date.now() - 30 * 86_400_000).toISOString()).one()); const rows = (slug: string) => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, s) => s.storage.sql.exec<{ id: string; version: number; data: string }>("SELECT id, version, data FROM rows WHERE table_id = 'note' ORDER BY id").toArray().map((r) => `${r.id} ${r.version} ${r.data}`), ); describe("the undo-history proof's planting route", () => { it("plants old entries only, the switch is off until set, and the trim keeps every record and recent undo", async () => { const slug = "plant-history"; const { owner } = await personalObject(slug, { open: NOTES_OPEN.open }); const ids: string[] = []; for (let i = 0; i < 4; i++) ids.push((await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "note", data: { body: `Invented note ${i}` } })).record.id); const before = await rows(slug); const start = await log(slug); const plant = (from: number, entries: number) => http(slug, "POST", "/v1/admin/dev/plant-history", { table: "note", records: ids, entries, chars: 2_000, days: 90, from, of: 300 }, ADMIN); for (let from = 0; from < 300; from += 100) expect((await plant(from, 100)).status).toBe(200); expect((await http(slug, "POST", "/v1/admin/dev/plant-history", { table: "note", records: ids, entries: 2_001, chars: 2_000, days: 90 }, ADMIN)).status).toBe(400); const planted = await log(slug); expect(planted.n).toBe(start.n + 300); // Two thirds of 90 days lie past 30: those are what the switch will take. expect(planted.old).toBeGreaterThanOrEqual(195); expect(await rows(slug), "planting writes no record").toEqual(before); // A recent change of the person's own, made after the history. const changed = await answer<{ change_id: number }>(slug, owner, "update_record", { table: "note", id: ids[0], patch: { body: "Invented note 0, changed today" } }); // Off until set: an alarm trims nothing. await alarm(slug); expect((await log(slug)).n).toBe(planted.n + 1); await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, s) => s.storage.setAlarm(Date.now() + 3_600_000)); expect((await http(slug, "PUT", "/v1/admin/business", { change_days: 30, change_bytes: 200_000 }, ADMIN)).status).toBe(200); // The switch wakes the alarm: the trim starts by itself now, not at the hourly pass that stood. let woke = false; for (let i = 0; i < 50 && !woke; i++) { await new Promise((done) => setTimeout(done, 200)); woke = (await log(slug)).n < planted.n + 1; } expect(woke, "the trim began on its own within 10 s of the switch").toBe(true); for (let i = 0; i < 20; i++) await alarm(slug); const after = await log(slug); expect(after.old, "nothing older than 30 days is left").toBe(0); expect(after.n).toBeLessThan(planted.n); const now = await rows(slug); expect(now.filter((r) => !r.startsWith(`${ids[0]} `)), "every other record and its version as it was").toEqual(before.filter((r) => !r.startsWith(`${ids[0]} `))); // The recent change is still undone. await answer(slug, owner, "undo", { change_id: changed.change_id }); const words = (list: string[]) => list.map((r) => r.replace(/^(\S+) \d+ /, "$1 ")); expect(words(await rows(slug)), "undone: the note reads as it did, and every record as before").toEqual(words(before)); }); it("a trim stopped halfway through a step leaves the log whole, and the next alarm carries on", async () => { const slug = "plant-history-stopped"; const { owner } = await personalObject(slug, { open: NOTES_OPEN.open }); await quiet(slug); const ids: string[] = []; for (let i = 0; i < 3; i++) ids.push((await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "note", data: { body: `Invented note ${i}` } })).record.id); // 2,000 entries of 40,000 characters (80 MB): more than two steps of 32 MB to take. for (let from = 0; from < 2_000; from += 500) expect((await http(slug, "POST", "/v1/admin/dev/plant-history", { table: "note", records: ids, entries: 500, chars: 40_000, days: 90, from, of: 2_000 }, ADMIN)).status).toBe(200); const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const records = await rows(slug); // The log as it stands: how many, the first and last id, the counted size and the size it really is. const whole = () => runInDurableObject(stub, (_i, s) => { const sql = s.storage.sql; const log = sql.exec<{ n: number; first: number; last: number; real: number }>("SELECT COUNT(*) AS n, MIN(id) AS first, MAX(id) AS last, SUM(coalesce(length(before), 0) + coalesce(length(after), 0)) AS real FROM change").one(); const counted = sql.exec<{ bytes: number; below: number }>("SELECT bytes, below FROM change_size").toArray()[0] ?? null; return { ...log, counted }; }); // The switch set in the object itself, so that no alarm runs but the ones this test runs; a step trims at most // 32 MB, so the trim takes several alarms. await runInDurableObject(stub, async (_i, s) => { await s.storage.deleteAlarm(); s.storage.sql.exec("INSERT INTO meta (key, value) VALUES ('change_days', '30'), ('change_bytes', '10000000') ON CONFLICT (key) DO UPDATE SET value = excluded.value"); }); // The first alarm counts the log's size; then the trim's first step is stopped. await runInDurableObject(stub, (instance) => (instance as unknown as { store: { countChanges(): boolean } }).store.countChanges()); const counted = await whole(); expect(counted.counted?.bytes, "the counted size is the size").toBe(counted.real); // The next step is stopped after its delete and before it ends, as an eviction or a deploy would stop it. const stopped = await runInDurableObject(stub, async (instance, s) => { // The object's own store, whose statements the trim runs. const sql = (instance as unknown as { store: { sql: { exec: (q: string, ...a: unknown[]) => unknown } } }).store.sql; const exec = sql.exec.bind(sql); let deleted = false; sql.exec = (q: string, ...a: unknown[]) => { const out = exec(q, ...a); if (q.startsWith("DELETE FROM change WHERE id <=")) deleted = true; if (deleted) throw new Error("stopped halfway"); return out; }; try { await ownAlarm(instance); return "ran"; } catch (error) { return error instanceof Error ? error.message : String(error); } finally { sql.exec = exec; await s.storage.deleteAlarm(); } }); expect(stopped).toBe("stopped halfway"); expect(await whole(), "nothing deleted: the stopped step is undone whole").toEqual(counted); // The next alarms carry on to the end, from where the log stands. for (let i = 0; i < 40; i++) await alarm(slug); const end = await whole(); expect(end.n).toBeLessThan(counted.n); expect(end.counted?.bytes, "the counted size is still the size").toBe(end.real); expect(end.real).toBeLessThanOrEqual(10_000_000); expect(end.last - end.first + 1, "what is left is the newest, with no gap").toBe(end.n); expect(end.last).toBe(counted.last); expect(await rows(slug), "every record as it was").toEqual(records); }); });