- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/test/disk-first-runtime.test.ts?version=165&format=json
488 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 162, 2 versions changed it
You're reading version 165. The newest is 318, and 1 version since then changed this file.
1import assert from "node:assert/strict";
2import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
3import { tmpdir } from "node:os";
4import { join } from "node:path";
5import { test } from "node:test";
6import { answer } from "../../worker/project/http.ts";
7import { MemoryStore, Project } from "../../worker/project/project.ts";
8import { where } from "../../worker/project/where.ts";
9import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
10import { type EngineProject, SqliteLog } from "../src/engine-project.ts";
11import { SqliteProjectionStore } from "../src/projection-store.ts";
12import { SqliteWriterHost, SqliteWriterState } from "../src/writer-host.ts";
13import { memoryStorage } from "./helpers.ts";
15test("runtime defers a large later frame and adopts it on its own page", (t) => {
16 const storage = memoryStorage();
17 t.after(() => storage.db.close());
18 const memory = new MemoryStore();
19 const project = new Project(memory);
20 project.init({ "a.txt": "small\n" }, 0);
21 project.record("alice", { "a.txt": `${"x".repeat(1_100_000)}\n` }, 1);
22 project.publish("alice", "Large entry", 2);
23 const log = new SqliteLog(storage);
24 log.append(memory.entries);
25 const large = memory.entries.findIndex((entry) => Buffer.byteLength(JSON.stringify(entry)) > 1_048_576);
26 assert.ok(large > 0);
27 const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
28 t.mock.method(Project, "load", () => {
29 throw Error("full-history replay forbidden");
30 });
31 const runtime = () => new DiskFirstRuntime(storage, "large-later", "large-later");
32 const first = runtime().preparePage(() => {});
33 assert.equal(first.phase, "writer");
34 assert.equal(first.next, large);
35 let pages = 0;
36 while (!runtime().preparePage(() => {}).ready) assert.ok(++pages < 100);
37 assert.equal(
38 runtime().read(
39 (calls) => calls.statusAt(log.seq()).version,
40 () => {},
41 ),
42 1,
43 );
44 assert.equal(
45 runtime().read(
46 (calls) => calls.shared().files["a.txt"]?.length,
47 () => {},
48 ),
49 1_100_001,
50 );
51 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before);
52});
54test("historical runtime preserves named draft bases and intermediate states after landing", (t) => {
55 const storage = memoryStorage();
56 t.after(() => storage.db.close());
57 const memory = new MemoryStore();
58 const project = new Project(memory);
59 project.init({ "a.txt": "one\ntwo\n", "b.txt": "other\n" }, 0);
60 project.switchTo("alice", "rewrite", 1);
61 project.record("alice", { "a.txt": "ONE\ntwo\n" }, 2);
62 project.publish("alice", "First draft version", 3);
63 project.switchTo("bob", "rewrite", 4);
64 project.record("bob", { "b.txt": "OTHER\n" }, 5);
65 project.publish("bob", "Second draft version", 6);
66 assert.equal(project.land("bob", "Land rewrite", 7).ok, true);
67 const expected = memory.entries.map((_, i) => {
68 const prefix = Project.load(memory.entries.slice(0, i + 1), new MemoryStore());
69 return { status: prefix.status(), where: where(prefix) };
70 });
71 new SqliteLog(storage).append(memory.entries);
72 t.mock.method(Project, "load", () => {
73 throw Error("full-history replay forbidden");
74 });
75 const runtime = () => new DiskFirstRuntime(storage, "named-history", "named-history");
76 while (!runtime().preparePage(() => {}).ready) {}
77 for (let at = 1; at <= expected.length; at++) {
78 assert.deepEqual(
79 runtime().read(
80 (calls) => calls.statusAt(at),
81 () => {},
82 ),
83 { at, ...expected[at - 1]!.status },
84 `status at ${at}`,
85 );
86 assert.deepEqual(
87 runtime().read(
88 (calls) => calls.whereAt(at),
89 () => {},
90 ),
91 { at, ...expected[at - 1]!.where },
92 `where at ${at}`,
93 );
94 }
95});
97test("runtime resumes from disk and detaches reads, with exact authorized retries", (t) => {
98 const directory = mkdtempSync(join(tmpdir(), "abso-runtime-"));
99 const filename = join(directory, "state.sqlite");
100 let storage = memoryStorage(filename);
101 t.after(() => {
102 storage.db.close();
103 unlinkSync(filename);
104 rmdirSync(directory);
105 });
106 const runtime = () => new DiskFirstRuntime(storage, "project-1", "disk-v1");
107 const validate = () => {};
108 t.mock.method(Project, "load", () => {
109 throw Error("full-history load forbidden");
110 });
111 assert.equal(runtime().preparePage(validate).phase, "empty");
112 assert.equal(
113 storage.db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'writer_state'").get()!.n,
114 0,
115 "an empty lookup must not install the legacy-write fence",
116 );
117 assert.equal(
118 runtime().initialize((calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }), validate)
119 .status,
120 200,
121 );
122 assert.throws(() => runtime().write(() => undefined, validate), /not complete/);
123 let pages = 0;
124 while (!runtime().preparePage(validate).ready) {
125 assert.ok(++pages < 100);
126 storage.db.close();
127 storage = memoryStorage(filename);
128 }
129 assert.ok(pages > 0);
130 const initialLength = new SqliteLog(storage).seq();
131 const initialStatus = runtime().read((calls) => calls.statusAt(initialLength), validate);
132 const initialWhere = runtime().read((calls) => calls.whereAt(initialLength), validate);
133 // Reproduce the published runtime's ready state before historical indexing existed.
134 new SqliteWriterState(storage, "disk-v1").remove("runtime", "history-ready");
135 storage.db.exec(
136 "DELETE FROM writer_state WHERE namespace LIKE 'disk-v1:history%'; DROP TABLE writer_history_keys; DROP TABLE writer_history_heads;",
137 );
138 assert.throws(() => runtime().read((calls) => calls.status(), validate), /not complete/);
139 assert.throws(() => runtime().write(() => undefined, validate), /not complete/);
140 while (!runtime().preparePage(validate).ready) {}
141 assert.deepEqual(
142 runtime().read((calls) => calls.statusAt(initialLength), validate),
143 initialStatus,
144 );
145 const req = { id: "record-1", identity: { agent: "alice", operation: "record", files: { "a.txt": "changed\n" } } };
146 const operation = (calls: Parameters<Parameters<DiskFirstRuntime["write"]>[0]>[0]) =>
147 answer(calls, "record", "alice", { files: req.identity.files });
148 const first = runtime().write(operation, validate, req);
149 assert.equal(first.status, 200);
150 const length = new SqliteLog(storage).seq();
151 const draftStatus = runtime().read((calls) => calls.statusAt(length), validate);
152 const draftWhere = runtime().read((calls) => calls.whereAt(length), validate);
153 storage.db.close();
154 storage = memoryStorage(filename);
155 assert.deepEqual(
156 runtime().write(
157 () => {
158 throw Error("retry executed");
159 },
160 validate,
161 req,
162 ),
163 first,
164 );
165 assert.equal(new SqliteLog(storage).seq(), length);
166 assert.throws(() => runtime().write(operation, validate, { ...req, identity: { agent: "bob" } }), /reused/);
167 assert.throws(
168 () =>
169 runtime().write(
170 operation,
171 () => {
172 throw Error("revoked");
173 },
174 req,
175 ),
176 /revoked/,
177 );
178 assert.equal(
179 runtime().write((calls) => answer(calls, "publish", "alice", { message: "Publish" }), validate).status,
180 200,
181 );
182 const shared = runtime().read((calls) => calls.shared(), validate);
183 assert.equal(Object.getOwnPropertyDescriptor(shared, "files")?.get, undefined);
184 assert.equal(shared.files["a.txt"], "changed\n");
185 storage.db.close();
186 storage = memoryStorage(filename);
187 assert.equal(runtime().preparePage(validate).ready, true);
188 assert.deepEqual(
189 runtime().read((calls) => calls.statusAt(initialLength), validate),
190 initialStatus,
191 );
192 assert.deepEqual(
193 runtime().read((calls) => calls.whereAt(initialLength), validate),
194 initialWhere,
195 );
196 const end = new SqliteLog(storage).seq();
197 assert.deepEqual(
198 runtime().read((calls) => calls.statusAt(length), validate),
199 draftStatus,
200 );
201 assert.deepEqual(
202 runtime().read((calls) => calls.whereAt(length), validate),
203 draftWhere,
204 );
205 assert.equal(
206 runtime().read((calls) => calls.statusAt(end).version, validate),
207 1,
208 );
209 assert.equal(
210 runtime().read((calls) => calls.whereAt(end).version, validate),
211 1,
212 );
213 assert.equal(
214 runtime().read((calls) => calls.shared().files["a.txt"], validate),
215 "changed\n",
216 );
217});
219test("runtime page and write authority failures leave no partial state", (t) => {
220 const storage = memoryStorage();
221 t.after(() => storage.db.close());
222 const runtime = new DiskFirstRuntime(storage, "project", "disk-v1");
223 runtime.initialize(
224 (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
225 () => {},
226 );
227 const rows = () => {
228 const tables = storage.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all();
229 return tables.map((row) => [
230 row.name,
231 storage.db.prepare(`SELECT * FROM "${String(row.name).replaceAll('"', '""')}" ORDER BY rowid`).all(),
232 ]);
233 };
234 const before = rows();
235 let checks = 0;
236 assert.throws(
237 () =>
238 runtime.preparePage(() => {
239 if (++checks === 3) throw Error("authority changed");
240 }),
241 /authority changed/,
242 );
243 assert.deepEqual(rows(), before);
244 while (!runtime.preparePage(() => {}).ready) {}
245 const adopted = rows();
246 checks = 0;
247 assert.throws(
248 () =>
249 runtime.write(
250 (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }),
251 () => {
252 if (++checks === 3) throw Error("authority changed");
253 },
254 { id: "failed", identity: "record" },
255 ),
256 /authority changed/,
257 );
258 assert.deepEqual(rows(), adopted);
259 const originalWrite = SqliteWriterState.prototype.write;
260 const failure = t.mock.method(
261 SqliteWriterState.prototype,
262 "write",
263 function (this: SqliteWriterState, collection: string, key: string, value: unknown) {
264 if (collection === "runtime:receipts") throw Error("receipt persistence failed");
265 return originalWrite.call(this, collection, key, value);
266 },
267 );
268 assert.throws(
269 () =>
270 runtime.write(
271 (calls) => answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }),
272 () => {},
273 { id: "receipt-failed", identity: "record" },
274 ),
275 /receipt persistence failed/,
276 );
277 assert.deepEqual(rows(), adopted, "receipt failure must roll back canonical state, history and its cursor");
278 failure.mock.restore();
279});
281test("runtime recovers after a writer without historical support commits", (t) => {
282 const storage = memoryStorage();
283 t.after(() => storage.db.close());
284 const namespace = "old-writer";
285 const runtime = () => new DiskFirstRuntime(storage, "recovery", namespace);
286 runtime().initialize(
287 (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
288 () => {},
289 );
290 while (!runtime().preparePage(() => {}).ready) {}
291 const historical = runtime().read(
292 (calls) => calls.statusAt(1),
293 () => {},
294 );
295 const projection = new SqliteProjectionStore(
296 {
297 database: "recovery",
298 namespace: `${namespace}:views`,
299 registry: `${namespace}:roots`,
300 defaultFile: "__abso_projection_default__",
301 },
302 1,
303 { indexedAtoms: true },
304 );
305 const oldWriter = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true });
306 for (const [op, body] of [
307 ["record", { files: { "a.txt": "two\n" } }],
308 ["publish", { message: "Old writer" }],
309 ] as const) {
310 assert.equal(
311 oldWriter().runCalls({
312 expected: oldWriter().source(),
313 validateAuthority: () => {},
314 checkerReady: false,
315 commitReceipt: () => {},
316 operation: (calls) => answer(calls, op, "alice", body),
317 }).status,
318 200,
319 );
320 }
321 t.mock.method(Project, "load", () => {
322 throw Error("full-history load forbidden");
323 });
324 let ready = false;
325 for (let page = 0; page < 100 && !ready; page++) ready = runtime().preparePage(() => {}).ready;
326 assert.equal(ready, true);
327 assert.deepEqual(
328 runtime().read(
329 (calls) => calls.statusAt(1),
330 () => {},
331 ),
332 historical,
333 );
334 assert.equal(
335 runtime().read(
336 (calls) => calls.shared().files["a.txt"],
337 () => {},
338 ),
339 "two\n",
340 );
341 assert.equal(
342 runtime().write(
343 (calls) => answer(calls, "record", "alice", { files: { "a.txt": "three\n" } }),
344 () => {},
345 ).status,
346 200,
347 );
348});
350test("a large retry response must not roll back an otherwise successful write", (t) => {
351 const storage = memoryStorage();
352 t.after(() => storage.db.close());
353 const runtime = () => new DiskFirstRuntime(storage, "large-receipt", "large-receipt");
354 runtime().initialize(
355 (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
356 () => {},
357 );
358 while (!runtime().preparePage(() => {}).ready) {}
359 const large = "x".repeat(8_100_000);
360 const request = { id: "large-response", identity: { agent: "alice", operation: "large-fixture" } };
361 const result = runtime().write(
362 (calls) => {
363 const recorded = answer(calls, "record", "alice", { files: { "a.txt": "two\n" } });
364 assert.equal(recorded.status, 200);
365 return { status: 200, body: large };
366 },
367 () => {},
368 request,
369 );
370 assert.equal(result.body.length, large.length);
371 const before = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
372 const replay = runtime().write(
373 () => {
374 throw Error("receipt replay must not execute twice");
375 },
376 () => {},
377 request,
378 ) as typeof result;
379 assert.deepEqual(replay, result);
380 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), before);
381});
383test("chunked receipts roll back failures and reject damaged replay", (t) => {
384 const storage = memoryStorage();
385 t.after(() => storage.db.close());
386 const runtime = () => new DiskFirstRuntime(storage, "receipt-failure", "receipt-failure");
387 runtime().initialize(
388 (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
389 () => {},
390 );
391 while (!runtime().preparePage(() => {}).ready) {}
392 const rows = () => ({
393 log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(),
394 state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
395 history: storage.db.prepare("SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision").all(),
396 heads: storage.db.prepare("SELECT * FROM writer_history_heads ORDER BY namespace").all(),
397 });
398 const before = rows();
399 const original = SqliteWriterState.prototype.write;
400 const failure = t.mock.method(
401 SqliteWriterState.prototype,
402 "write",
403 function (this: SqliteWriterState, collection: string, key: string, value: unknown) {
404 original.call(this, collection, key, value);
405 if (collection === "runtime:receipt:chunk-failure" && key === "1") throw Error("injected receipt chunk failure");
406 },
407 );
408 const request = { id: "chunk-failure", identity: { operation: "fixture" } };
409 const operation = (calls: EngineProject) => {
410 assert.equal(answer(calls, "record", "alice", { files: { "a.txt": "two\n" } }).status, 200);
411 return { body: "x".repeat(140000) };
412 };
413 assert.throws(() => runtime().write(operation, () => {}, request), /injected receipt chunk failure/);
414 assert.deepEqual(rows(), before);
415 failure.mock.restore();
416 const result = runtime().write(operation, () => {}, request);
417 const committed = rows();
418 assert.deepEqual(
419 runtime().write(
420 () => {
421 throw Error("must not execute");
422 },
423 () => {},
424 request,
425 ),
426 result,
427 );
428 assert.deepEqual(rows(), committed);
429 const state = new SqliteWriterState(storage, "receipt-failure");
430 const chunk = state.read("runtime:receipt:chunk-failure", "1") as string;
431 state.write("runtime:receipt:chunk-failure", "1", "y" + chunk.slice(1));
432 assert.throws(
433 () =>
434 runtime().write(
435 () => {
436 throw Error("must not execute");
437 },
438 () => {},
439 request,
440 ),
441 /digest mismatch/,
442 );
443 state.remove("runtime:receipt:chunk-failure", "1");
444 assert.throws(
445 () =>
446 runtime().write(
447 () => {
448 throw Error("must not execute");
449 },
450 () => {},
451 request,
452 ),
453 /incomplete receipt/,
454 );
455 assert.deepEqual(rows().log, committed.log);
456});
458test("runtime format upgrade is authorized, atomic, and rejects unknown formats", (t) => {
459 const storage = memoryStorage();
460 t.after(() => storage.db.close());
461 const runtime = () => new DiskFirstRuntime(storage, "format-test", "format-test");
462 runtime().initialize(
463 (calls) => answer(calls, "init", undefined, { files: { "a.txt": "one\n" } }),
464 () => {},
465 );
466 while (!runtime().preparePage(() => {}).ready) {}
467 const state = new SqliteWriterState(storage, "format-test");
468 assert.equal(state.read("runtime", "format"), 5);
469 state.write("runtime", "format", 3);
470 const before = storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all();
471 let validations = 0;
472 assert.throws(
473 () =>
474 runtime().preparePage(() => {
475 if (++validations === 2) throw Error("revoked during upgrade");
476 }),
477 /revoked/,
478 );
479 assert.deepEqual(
480 storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
481 before,
482 );
483 assert.equal(runtime().preparePage(() => {}).ready, true);
484 assert.equal(state.read("runtime", "format"), 5);
485 state.write("runtime", "format", 999);
486 assert.throws(() => runtime().preparePage(() => {}), /unsupported disk-first runtime format/);
487 assert.equal(state.read("runtime", "format"), 999);
488});