Versions 124 to 318
new file, 499 lines
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs"; 4+import { tmpdir } from "node:os"; 5+import { join } from "node:path"; 6+import { test } from "node:test"; 7+import { answer } from "../../worker/project/http.ts"; 8+import { MemoryStore, Project } from "../../worker/project/project.ts"; 9+import { where } from "../../worker/project/where.ts"; 10+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 11+import { type EngineProject, SqliteLog } from "../src/engine-project.ts"; 12+import { SqliteProjectionStore } from "../src/projection-store.ts"; 13+import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts"; 14+import { memoryStorage } from "./helpers.ts"; 16+test("runtime defers a large later frame and adopts it on its own page", (t) => { 17+ const storage = memoryStorage(); 18+ t.after(() => storage.db.close()); 19+ const memory = new MemoryStore(); 20+ const project = new Project(memory); 21+ project.init({ "a.txt": "small\n" }, 0); 22+ project.record("alice", { "a.txt": `${"x".repeat(1_100_000)}\n` }, 1); 23+ project.publish("alice", "Large entry", 2); 24+ const log = new SqliteLog(storage); 25+ log.append(memory.entries); 26+ const large = memory.entries.findIndex((entry) => Buffer.byteLength(JSON.stringify(entry)) > 1_048_576); 27+ assert.ok(large > 0); 28+ const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 29+ t.mock.method(Project, "load", () => { 30+ throw Error("full-history replay forbidden"); 32+ const runtime = () => new DiskFirstRuntime(storage, "large-later", "large-later"); 33+ const first = runtime().preparePage(() => {}); 34+ assert.equal(first.phase, "writer"); 35+ assert.equal(first.next, large); 37+ while (!runtime().preparePage(() => {}).ready) assert.ok(++pages < 100); 40+ (calls) => calls.statusAt(log.seq()).version, 47+ (calls) => calls.shared().files["a.txt"]?.length, 52+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before); 55+test("historical runtime preserves named draft bases and intermediate states after landing", (t) => { 56+ const storage = memoryStorage(); 57+ t.after(() => storage.db.close()); 58+ const memory = new MemoryStore(); 59+ const project = new Project(memory); 60+ project.init({ "a.txt": "one\ntwo\n", "b.txt": "other\n" }, 0); 61+ project.switchTo("alice", "rewrite", 1); 62+ project.record("alice", { "a.txt": "ONE\ntwo\n" }, 2); 63+ project.publish("alice", "First draft version", 3); 64+ project.switchTo("bob", "rewrite", 4); 65+ project.record("bob", { "b.txt": "OTHER\n" }, 5); 66+ project.publish("bob", "Second draft version", 6); 67+ assert.equal(project.land("bob", "Land rewrite", 7).ok, true); 68+ const expected = memory.entries.map((_, i) => { 69+ const prefix = Project.load(memory.entries.slice(0, i + 1), new MemoryStore()); 70+ return { status: prefix.status(), where: where(prefix) }; 72+ new SqliteLog(storage).append(memory.entries); 73+ t.mock.method(Project, "load", () => { 74+ throw Error("full-history replay forbidden"); 76+ const runtime = () => new DiskFirstRuntime(storage, "named-history", "named-history"); 77+ while (!runtime().preparePage(() => {}).ready) {} 78+ for (let at = 1; at <= expected.length; at++) { 81+ (calls) => calls.statusAt(at), 84+ { at, ...expected[at - 1]!.status }, 89+ (calls) => calls.whereAt(at), 92+ { at, ...expected[at - 1]!.where }, 98+test("runtime resumes from disk and detaches reads, with exact authorized retries", (t) => { 99+ const directory = mkdtempSync(join(tmpdir(), "abso-runtime-")); 100+ const filename = join(directory, "state.sqlite"); 101+ let storage = memoryStorage(filename); 104+ unlinkSync(filename); 105+ rmdirSync(directory); 107+ const runtime = () => new DiskFirstRuntime(storage, "project-1", "disk-v1"); 108+ const validate = () => {}; 109+ t.mock.method(Project, "load", () => { 110+ throw Error("full-history load forbidden"); 112+ assert.equal(runtime().preparePage(validate).phase, "empty"); 114+ storage.db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'writer_state'").get()!.n, 116+ "an empty lookup must not install the legacy-write fence", 119+ runtime().initialize((calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }), validate) 123+ assert.throws(() => runtime().write(() => undefined, validate), /not complete/); 125+ while (!runtime().preparePage(validate).ready) { 126+ assert.ok(++pages < 100); 128+ storage = memoryStorage(filename); 130+ assert.ok(pages > 0); 131+ const initialLength = new SqliteLog(storage).seq(); 132+ const initialStatus = runtime().read((calls) => calls.statusAt(initialLength), validate); 133+ const initialWhere = runtime().read((calls) => calls.whereAt(initialLength), validate); 134+ // Reproduce the published runtime's ready state before historical indexing existed. 135+ new SqliteWriterState(storage, "disk-v1").remove("runtime", "history-ready"); 137+ "DELETE FROM writer_state WHERE namespace LIKE 'disk-v1:history%'; DROP TABLE writer_history_keys; DROP TABLE writer_history_heads;", 139+ assert.throws(() => runtime().read((calls) => calls.status(), validate), /not complete/); 140+ assert.throws(() => runtime().write(() => undefined, validate), /not complete/); 141+ while (!runtime().preparePage(validate).ready) {} 143+ runtime().read((calls) => calls.statusAt(initialLength), validate), 146+ const req = { id: "record-1", identity: { agent: "alice", operation: "record", files: { "a.txt": "changed\n" } } }; 147+ const operation = (calls: Parameters<Parameters<DiskFirstRuntime["write"]>[0]>[0]) => 148+ answer(calls, "record", "alice", { files: req.identity.files }); 149+ const first = runtime().write(operation, validate, req); 150+ assert.equal(first.status, 200); 151+ const length = new SqliteLog(storage).seq(); 152+ const draftStatus = runtime().read((calls) => calls.statusAt(length), validate); 153+ const draftWhere = runtime().read((calls) => calls.whereAt(length), validate); 155+ storage = memoryStorage(filename); 159+ throw Error("retry executed"); 166+ assert.equal(new SqliteLog(storage).seq(), length); 167+ assert.throws(() => runtime().write(operation, validate, { ...req, identity: { agent: "bob" } }), /reused/); 173+ throw Error("revoked"); 180+ runtime().write((calls) => answer(calls, "publish", "alice", { message: "Publish" }), validate).status, 183+ const shared = runtime().read((calls) => calls.shared(), validate); 184+ assert.equal(Object.getOwnPropertyDescriptor(shared, "files")?.get, undefined); 185+ assert.equal(shared.files["a.txt"], "changed\n"); 187+ storage = memoryStorage(filename); 188+ assert.equal(runtime().preparePage(validate).ready, true); 190+ runtime().read((calls) => calls.statusAt(initialLength), validate), 194+ runtime().read((calls) => calls.whereAt(initialLength), validate), 197+ const end = new SqliteLog(storage).seq(); 199+ runtime().read((calls) => calls.statusAt(length), validate), 203+ runtime().read((calls) => calls.whereAt(length), validate), 207+ runtime().read((calls) => calls.statusAt(end).version, validate), 211+ runtime().read((calls) => calls.whereAt(end).version, validate), 215+ runtime().read((calls) => calls.shared().files["a.txt"], validate), 220+test("runtime page and write authority failures leave no partial state", (t) => { 221+ const storage = memoryStorage(); 222+ t.after(() => storage.db.close()); 223+ const runtime = new DiskFirstRuntime(storage, "project", "disk-v1"); 225+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 228+ const rows = () => { 229+ const tables = storage.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all(); 230+ return tables.map((row) => [ 232+ storage.db.prepare(`SELECT * FROM "${String(row.name).replaceAll('"', '""')}" ORDER BY rowid`).all(), 235+ const before = rows(); 239+ runtime.preparePage(() => { 240+ if (++checks === 3) throw Error("authority changed"); 242+ /authority changed/, 244+ assert.deepEqual(rows(), before); 245+ while (!runtime.preparePage(() => {}).ready) {} 246+ const adopted = rows(); 251+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }), 253+ if (++checks === 3) throw Error("authority changed"); 255+ { id: "failed", identity: "record" }, 257+ /authority changed/, 259+ assert.deepEqual(rows(), adopted); 260+ const originalWrite = SqliteWriterState.prototype.write; 261+ const failure = t.mock.method( 262+ SqliteWriterState.prototype, 264+ function (this: SqliteWriterState, collection: string, key: string, value: unknown) { 265+ if (collection === "runtime:receipts") throw Error("receipt persistence failed"); 266+ return originalWrite.call(this, collection, key, value); 272+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }), 274+ { id: "receipt-failed", identity: "record" }, 276+ /receipt persistence failed/, 278+ assert.deepEqual(rows(), adopted, "receipt failure must roll back canonical state, history and its cursor"); 279+ failure.mock.restore(); 282+test("runtime recovers after a writer without historical support commits", (t) => { 283+ const storage = memoryStorage(); 284+ t.after(() => storage.db.close()); 285+ const namespace = "old-writer"; 286+ const runtime = () => new DiskFirstRuntime(storage, "recovery", namespace); 287+ runtime().initialize( 288+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 291+ while (!runtime().preparePage(() => {}).ready) {} 292+ const historical = runtime().read( 293+ (calls) => calls.statusAt(1), 296+ const projection = new SqliteProjectionStore( 298+ database: "recovery", 299+ namespace: `${namespace}:views`, 300+ registry: `${namespace}:roots`, 301+ defaultFile: "__abso_projection_default__", 304+ { indexedAtoms: true }, 306+ const oldWriter = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true }); 307+ for (const [op, body] of [ 308+ ["record", { files: { "a.txt": "two\n" } }], 309+ ["publish", { message: "Old writer" }], 312+ oldWriter().runCalls({ 313+ expected: oldWriter().source(), 314+ validateAuthority: () => {}, 315+ checkerReady: false, 316+ commitReceipt: () => {}, 317+ operation: (calls) => answer(calls, op, "alice", body), 322+ t.mock.method(Project, "load", () => { 323+ throw Error("full-history load forbidden"); 326+ for (let page = 0; page < 100 && !ready; page++) ready = runtime().preparePage(() => {}).ready; 327+ assert.equal(ready, true); 330+ (calls) => calls.statusAt(1), 337+ (calls) => calls.shared().files["a.txt"], 344+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "three\n" } }), 351+test("a large retry response must not roll back an otherwise successful write", (t) => { 352+ const storage = memoryStorage(); 353+ t.after(() => storage.db.close()); 354+ const runtime = () => new DiskFirstRuntime(storage, "large-receipt", "large-receipt"); 355+ runtime().initialize( 356+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 359+ while (!runtime().preparePage(() => {}).ready) {} 360+ const large = "x".repeat(65503) + "🚀" + '\u0000\n"\\é中\ud800'.repeat(1_000_000); 361+ const request = { id: "large-response", identity: { agent: "alice", operation: "large-fixture" } }; 362+ const result = runtime().write( 364+ const recorded = answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }); 365+ assert.equal(recorded.status, 200); 366+ return { status: 200, body: large }; 371+ assert.equal(result.body.length, large.length); 372+ const state = new SqliteWriterState(storage, "large-receipt"); 373+ const header = state.read("runtime:receipts", request.id) as { parts: number; characters: number; digest: string }; 374+ const expected = JSON.stringify({ result }); 375+ assert.equal(header.characters, expected.length); 376+ assert.equal(header.digest, createHash("sha256").update(expected).digest("hex")); 377+ for (let part = 0; part < header.parts; part++) 379+ state.read(`runtime:receipt:${request.id}`, String(part)), 380+ expected.slice(part * 65536, (part + 1) * 65536), 382+ const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 383+ const replay = runtime().write( 385+ throw Error("receipt replay must not execute twice"); 390+ assert.deepEqual(replay, result); 391+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before); 394+test("chunked receipts roll back failures and reject damaged replay", (t) => { 395+ const storage = memoryStorage(); 396+ t.after(() => storage.db.close()); 397+ const runtime = () => new DiskFirstRuntime(storage, "receipt-failure", "receipt-failure"); 398+ runtime().initialize( 399+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 402+ while (!runtime().preparePage(() => {}).ready) {} 403+ const rows = () => ({ 404+ log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), 405+ state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 406+ history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(), 407+ heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(), 409+ const before = rows(); 410+ const original = SqliteWriterState.prototype.write; 411+ const failure = t.mock.method( 412+ SqliteWriterState.prototype, 414+ function (this: SqliteWriterState, collection: string, key: string, value: unknown) { 415+ original.call(this, collection, key, value); 416+ if (collection === "runtime:receipt:chunk-failure" && key === "1") throw Error("injected receipt chunk failure"); 419+ const request = { id: "chunk-failure", identity: { operation: "fixture" } }; 420+ const operation = (calls: EngineProject) => { 421+ assert.equal(answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }).status, 200); 422+ return { body: "x".repeat(140000) }; 424+ assert.throws(() => runtime().write(operation, () => {}, request), /injected receipt chunk failure/); 425+ assert.deepEqual(rows(), before); 426+ failure.mock.restore(); 427+ const result = runtime().write(operation, () => {}, request); 428+ const committed = rows(); 432+ throw Error("must not execute"); 439+ assert.deepEqual(rows(), committed); 440+ const state = new SqliteWriterState(storage, "receipt-failure"); 441+ const chunk = state.read("runtime:receipt:chunk-failure", "1") as string; 442+ state.write("runtime:receipt:chunk-failure", "1", "y" + chunk.slice(1)); 447+ throw Error("must not execute"); 454+ state.remove("runtime:receipt:chunk-failure", "1"); 459+ throw Error("must not execute"); 464+ /incomplete receipt/, 466+ assert.deepEqual(rows().log, committed.log); 469+test("runtime format upgrade is authorized, atomic, and rejects unknown formats", (t) => { 470+ const storage = memoryStorage(); 471+ t.after(() => storage.db.close()); 472+ const runtime = () => new DiskFirstRuntime(storage, "format-test", "format-test"); 473+ runtime().initialize( 474+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }), 477+ while (!runtime().preparePage(() => {}).ready) {} 478+ const state = new SqliteWriterState(storage, "format-test"); 479+ assert.equal(state.read("runtime", "format"), 5); 480+ state.write("runtime", "format", 3); 481+ const before = storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(); 482+ let validations = 0; 485+ runtime().preparePage(() => { 486+ if (++validations === 2) throw Error("revoked during upgrade"); 491+ storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(), 494+ assert.equal(runtime().preparePage(() => {}).ready, true); 495+ assert.equal(state.read("runtime", "format"), 5); 496+ state.write("runtime", "format", 999); 497+ assert.throws(() => runtime().preparePage(() => {}), /unsupported disk-first runtime format/); 498+ assert.equal(state.read("runtime", "format"), 999);