Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 76 to 318

Compare

+499 −0 in 1 place
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");
31+ });
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);
36+ let pages = 0;
37+ while (!runtime().preparePage(() => {}).ready) assert.ok(++pages < 100);
38+ assert.equal(
39+ runtime().read(
40+ (calls) => calls.statusAt(log.seq()).version,
41+ () => {},
42+ ),
43+ 1,
44+ );
45+ assert.equal(
46+ runtime().read(
47+ (calls) => calls.shared().files["a.txt"]?.length,
48+ () => {},
49+ ),
50+ 1_100_001,
51+ );
52+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before);
53+});
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) };
71+ });
72+ new SqliteLog(storage).append(memory.entries);
73+ t.mock.method(Project, "load", () => {
74+ throw Error("full-history replay forbidden");
75+ });
76+ const runtime = () => new DiskFirstRuntime(storage, "named-history", "named-history");
77+ while (!runtime().preparePage(() => {}).ready) {}
78+ for (let at = 1; at <= expected.length; at++) {
79+ assert.deepEqual(
80+ runtime().read(
81+ (calls) => calls.statusAt(at),
82+ () => {},
83+ ),
84+ { at, ...expected[at - 1]!.status },
85+ `status at ${at}`,
86+ );
87+ assert.deepEqual(
88+ runtime().read(
89+ (calls) => calls.whereAt(at),
90+ () => {},
91+ ),
92+ { at, ...expected[at - 1]!.where },
93+ `where at ${at}`,
94+ );
95+ }
96+});
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);
102+ t.after(() => {
103+ storage.db.close();
104+ unlinkSync(filename);
105+ rmdirSync(directory);
106+ });
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");
111+ });
112+ assert.equal(runtime().preparePage(validate).phase, "empty");
113+ assert.equal(
114+ storage.db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'writer_state'").get()!.n,
115+ 0,
116+ "an empty lookup must not install the legacy-write fence",
117+ );
118+ assert.equal(
119+ runtime().initialize((calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }), validate)
120+ .status,
121+ 200,
122+ );
123+ assert.throws(() => runtime().write(() => undefined, validate), /not complete/);
124+ let pages = 0;
125+ while (!runtime().preparePage(validate).ready) {
126+ assert.ok(++pages < 100);
127+ storage.db.close();
128+ storage = memoryStorage(filename);
129+ }
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");
136+ storage.db.exec(
137+ "DELETE FROM writer_state WHERE namespace LIKE 'disk-v1:history%'; DROP TABLE writer_history_keys; DROP TABLE writer_history_heads;",
138+ );
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) {}
142+ assert.deepEqual(
143+ runtime().read((calls) => calls.statusAt(initialLength), validate),
144+ initialStatus,
145+ );
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);
154+ storage.db.close();
155+ storage = memoryStorage(filename);
156+ assert.deepEqual(
157+ runtime().write(
158+ () => {
159+ throw Error("retry executed");
160+ },
161+ validate,
162+ req,
163+ ),
164+ first,
165+ );
166+ assert.equal(new SqliteLog(storage).seq(), length);
167+ assert.throws(() => runtime().write(operation, validate, { ...req, identity: { agent: "bob" } }), /reused/);
168+ assert.throws(
169+ () =>
170+ runtime().write(
171+ operation,
172+ () => {
173+ throw Error("revoked");
174+ },
175+ req,
176+ ),
177+ /revoked/,
178+ );
179+ assert.equal(
180+ runtime().write((calls) => answer(calls, "publish", "alice", { message: "Publish" }), validate).status,
181+ 200,
182+ );
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");
186+ storage.db.close();
187+ storage = memoryStorage(filename);
188+ assert.equal(runtime().preparePage(validate).ready, true);
189+ assert.deepEqual(
190+ runtime().read((calls) => calls.statusAt(initialLength), validate),
191+ initialStatus,
192+ );
193+ assert.deepEqual(
194+ runtime().read((calls) => calls.whereAt(initialLength), validate),
195+ initialWhere,
196+ );
197+ const end = new SqliteLog(storage).seq();
198+ assert.deepEqual(
199+ runtime().read((calls) => calls.statusAt(length), validate),
200+ draftStatus,
201+ );
202+ assert.deepEqual(
203+ runtime().read((calls) => calls.whereAt(length), validate),
204+ draftWhere,
205+ );
206+ assert.equal(
207+ runtime().read((calls) => calls.statusAt(end).version, validate),
208+ 1,
209+ );
210+ assert.equal(
211+ runtime().read((calls) => calls.whereAt(end).version, validate),
212+ 1,
213+ );
214+ assert.equal(
215+ runtime().read((calls) => calls.shared().files["a.txt"], validate),
216+ "changed\n",
217+ );
218+});
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");
224+ runtime.initialize(
225+ (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
226+ () => {},
227+ );
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) => [
231+ row.name,
232+ storage.db.prepare(`SELECT * FROM "${String(row.name).replaceAll('"', '""')}" ORDER BY rowid`).all(),
233+ ]);
234+ };
235+ const before = rows();
236+ let checks = 0;
237+ assert.throws(
238+ () =>
239+ runtime.preparePage(() => {
240+ if (++checks === 3) throw Error("authority changed");
241+ }),
242+ /authority changed/,
243+ );
244+ assert.deepEqual(rows(), before);
245+ while (!runtime.preparePage(() => {}).ready) {}
246+ const adopted = rows();
247+ checks = 0;
248+ assert.throws(
249+ () =>
250+ runtime.write(
251+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }),
252+ () => {
253+ if (++checks === 3) throw Error("authority changed");
254+ },
255+ { id: "failed", identity: "record" },
256+ ),
257+ /authority changed/,
258+ );
259+ assert.deepEqual(rows(), adopted);
260+ const originalWrite = SqliteWriterState.prototype.write;
261+ const failure = t.mock.method(
262+ SqliteWriterState.prototype,
263+ "write",
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);
267+ },
268+ );
269+ assert.throws(
270+ () =>
271+ runtime.write(
272+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }),
273+ () => {},
274+ { id: "receipt-failed", identity: "record" },
275+ ),
276+ /receipt persistence failed/,
277+ );
278+ assert.deepEqual(rows(), adopted, "receipt failure must roll back canonical state, history and its cursor");
279+ failure.mock.restore();
280+});
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" } }),
289+ () => {},
290+ );
291+ while (!runtime().preparePage(() => {}).ready) {}
292+ const historical = runtime().read(
293+ (calls) => calls.statusAt(1),
294+ () => {},
295+ );
296+ const projection = new SqliteProjectionStore(
297+ {
298+ database: "recovery",
299+ namespace: `${namespace}:views`,
300+ registry: `${namespace}:roots`,
301+ defaultFile: "__abso_projection_default__",
302+ },
303+ 1,
304+ { indexedAtoms: true },
305+ );
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" }],
310+ ] as const) {
311+ assert.equal(
312+ oldWriter().runCalls({
313+ expected: oldWriter().source(),
314+ validateAuthority: () => {},
315+ checkerReady: false,
316+ commitReceipt: () => {},
317+ operation: (calls) => answer(calls, op, "alice", body),
318+ }).status,
319+ 200,
320+ );
321+ }
322+ t.mock.method(Project, "load", () => {
323+ throw Error("full-history load forbidden");
324+ });
325+ let ready = false;
326+ for (let page = 0; page < 100 && !ready; page++) ready = runtime().preparePage(() => {}).ready;
327+ assert.equal(ready, true);
328+ assert.deepEqual(
329+ runtime().read(
330+ (calls) => calls.statusAt(1),
331+ () => {},
332+ ),
333+ historical,
334+ );
335+ assert.equal(
336+ runtime().read(
337+ (calls) => calls.shared().files["a.txt"],
338+ () => {},
339+ ),
340+ "two\n",
341+ );
342+ assert.equal(
343+ runtime().write(
344+ (calls) => answer(calls, "record", "alice", { files: { "a.txt": "three\n" } }),
345+ () => {},
346+ ).status,
347+ 200,
348+ );
349+});
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" } }),
357+ () => {},
358+ );
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(
363+ (calls) => {
364+ const recorded = answer(calls, "record", "alice", { files: { "a.txt": "two\n" } });
365+ assert.equal(recorded.status, 200);
366+ return { status: 200, body: large };
367+ },
368+ () => {},
369+ request,
370+ );
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++)
378+ assert.equal(
379+ state.read(`runtime:receipt:${request.id}`, String(part)),
380+ expected.slice(part * 65536, (part + 1) * 65536),
381+ );
382+ const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
383+ const replay = runtime().write(
384+ () => {
385+ throw Error("receipt replay must not execute twice");
386+ },
387+ () => {},
388+ request,
389+ ) as typeof result;
390+ assert.deepEqual(replay, result);
391+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before);
392+});
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" } }),
400+ () => {},
401+ );
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(),
408+ });
409+ const before = rows();
410+ const original = SqliteWriterState.prototype.write;
411+ const failure = t.mock.method(
412+ SqliteWriterState.prototype,
413+ "write",
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");
417+ },
418+ );
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) };
423+ };
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();
429+ assert.deepEqual(
430+ runtime().write(
431+ () => {
432+ throw Error("must not execute");
433+ },
434+ () => {},
435+ request,
436+ ),
437+ result,
438+ );
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));
443+ assert.throws(
444+ () =>
445+ runtime().write(
446+ () => {
447+ throw Error("must not execute");
448+ },
449+ () => {},
450+ request,
451+ ),
452+ /digest mismatch/,
453+ );
454+ state.remove("runtime:receipt:chunk-failure", "1");
455+ assert.throws(
456+ () =>
457+ runtime().write(
458+ () => {
459+ throw Error("must not execute");
460+ },
461+ () => {},
462+ request,
463+ ),
464+ /incomplete receipt/,
465+ );
466+ assert.deepEqual(rows().log, committed.log);
467+});
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" } }),
475+ () => {},
476+ );
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;
483+ assert.throws(
484+ () =>
485+ runtime().preparePage(() => {
486+ if (++validations === 2) throw Error("revoked during upgrade");
487+ }),
488+ /revoked/,
489+ );
490+ assert.deepEqual(
491+ storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
492+ before,
493+ );
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);
499+});
MCP
compare on this site's /mcp
CLI
abso diff 76 318 server/test/disk-first-runtime.test.ts --json
JSON
/christopher/abso-core/compare/76..318?file=server%2Ftest%2Fdisk-first-runtime.test.ts&format=json