- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/test/projection-integration.test.ts?format=json
791 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 143, 1 version changed it
1import assert from "node:assert/strict";
2import { createHash } from "node:crypto";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { performance } from "node:perf_hooks";
7import { test } from "node:test";
8import { ExperimentalMarkerProjection } from "../../../src/engine/experimental/projection-marker.ts";
9import { ProjectionOverlayStorage } from "../../../src/engine/experimental/projection-overlay-storage.ts";
10import { ProjectionReadScope } from "../../../src/engine/experimental/projection-read-scope.ts";
11import { ProjectionReader } from "../../../src/engine/experimental/projection-reader.ts";
12import type { ProjectionHandle, ProjectionIdentity } from "../../../src/engine/experimental/projection-root.ts";
13import { ProjectionSnapshots } from "../../../src/engine/experimental/projection-snapshots.ts";
14import type { Graph } from "../../../src/engine/graph.ts";
15import { CachedStateStorage, storedArray } from "../../../src/engine/state-source.ts";
16import { SqlState } from "../../../src/engine/test/storage-helper.ts";
17import { MemoryStore, Project } from "../project.ts";
18import type { Entry, ProjectOptions, ProjectStore } from "../project-types.ts";
19import { projectedReader } from "../projection-provider.ts";
20import { Membership } from "../spaces.ts";
21import { ViewCache } from "../views.ts";
22import { WriterAgents } from "../writer-agents.ts";
24// Private test host only. Canonical frames and projection receipts share one SQLite transaction.
25class ProjectionHost {
26 readonly storage: SqlState;
27 readonly entries: Entry[];
28 verifyReadParity = true;
29 readViewProvider?: ProjectOptions["readViewProvider"];
30 enableReaderProvider(): void {
31 this.readViewProvider = (graph) => {
32 const scope = this.newReadScope(graph);
33 return { keyed: (key) => this.readerForKey(key, graph, scope.guard(graph)) };
34 };
35 }
36 #scopeFrames: { token: object; scopes: ProjectionReadScope[]; overlays: ProjectionOverlayStorage[] }[] = [];
37 #nextOverlay = 0;
38 newReadScope(graph: Graph): ProjectionReadScope {
39 const frame = this.#scopeFrames.at(-1);
40 assert.ok(frame, "reader provider requires an active transaction");
41 const scope = new ProjectionReadScope(graph, () => this.#scopeFrames.at(-1)?.token);
42 frame.scopes.push(scope);
43 return scope;
44 }
45 #transaction<T>(operation: () => T): T {
46 const parent = this.#scopeFrames.at(-1);
47 if (parent) {
48 for (const scope of parent.scopes) scope.close();
49 parent.scopes.length = 0;
50 }
51 const frame = { token: {}, scopes: [] as ProjectionReadScope[], overlays: [] as ProjectionOverlayStorage[] };
52 this.#scopeFrames.push(frame);
53 try {
54 return this.storage.transaction(() => {
55 try {
56 return operation();
57 } finally {
58 for (const overlay of frame.overlays) overlay.close();
59 }
60 });
61 } finally {
62 for (const scope of frame.scopes) scope.close();
63 assert.equal(this.#scopeFrames.pop(), frame);
64 }
65 }
67 constructor(filename = ":memory:") {
68 this.storage = new SqlState(filename);
69 this.entries = storedArray<Entry>(this.storage, "integration:canonical");
70 }
71 readonly store: ProjectStore = {
72 append: (batch) => {
73 for (const entry of batch) {
74 const digest = this.storage.read("integration:source", "digest") ?? "";
75 this.entries.push(entry);
76 this.storage.write(
77 "integration:source",
78 "digest",
79 createHash("sha256")
80 .update(JSON.stringify([digest, entry]))
81 .digest("hex"),
82 );
83 this.storage.write(
84 "integration:prefixes",
85 String(this.entries.length),
86 this.storage.read("integration:source", "digest"),
87 );
88 }
89 },
90 };
91 run<T>(
92 id: string,
93 expectedLength: number,
94 operation: (project: Project) => T,
95 fail = false,
96 request: { body: string; target: string; authority: string } = {
97 body: id,
98 target: "shared",
99 authority: "test-writer",
100 },
101 ): T {
102 // The real host must supply a normalized request body, never a callback's source text.
103 const requestDigest = createHash("sha256")
104 .update(JSON.stringify([request.body, request.target, request.authority]))
105 .digest("hex");
106 return this.#transaction(() => {
107 const receipt = this.storage.read("integration:receipts", id) as { result: T; requestDigest: string } | undefined;
108 if (receipt) {
109 if (receipt.requestDigest !== requestDigest) throw Error("operation ID request conflict");
110 return receipt.result;
111 }
112 assert.equal(this.entries.length, expectedLength, "stale canonical head");
113 const project = this.entries.length
114 ? Project.openWriter(this.store, this.storage, this.entries.length, { readViewProvider: this.readViewProvider })
115 : new Project(this.store, { writerStorage: this.storage });
116 const adapter = new ExperimentalMarkerProjection(
117 this.storage,
118 project.graph,
119 "a.txt",
120 JSON.stringify(["database-a", "projection-a"]),
121 );
122 const context = {
123 database: "database-a",
124 namespace: JSON.stringify(["database-a", "projection-a"]),
125 registry: "registry-a",
126 defaultFile: "a.txt",
127 };
128 const snapshots = new ProjectionSnapshots(this.storage, adapter, context);
129 const previous = this.storage.read("integration:head", "projection") as ProjectionHandle | undefined;
130 if (this.entries.length && !previous) throw Error("missing committed projection head");
131 const expected: ProjectionIdentity = {
132 ...context,
133 sourceGeneration: 1,
134 sourceLength: this.entries.length,
135 sourceDigest: this.storage.read("integration:prefixes", String(this.entries.length)) as string,
136 membership: this.entries.length ? String(project.version) : "-1",
137 };
138 let state = previous ? snapshots.load(previous, expected) : adapter.empty();
139 const before = previous ? project.version : -1;
140 const result = operation(project);
141 const save = (version: number): ProjectionHandle => {
142 const next = (this.storage.read("integration:head", "next-root") as number | undefined) ?? 0;
143 const handle = snapshots.save(
144 next,
145 {
146 ...context,
147 sourceGeneration: 1,
148 sourceLength: this.entries.length,
149 sourceDigest: this.storage.read("integration:source", "digest") as string,
150 membership: String(version),
151 },
152 state,
153 );
154 this.storage.write("integration:head", "next-root", next + 1);
155 return handle;
156 };
157 let versionHandle: ProjectionHandle | undefined;
158 const membership = new Membership(this.storage);
159 for (let version = before + 1; version <= project.version; version++) {
160 const delta = membership.shared.versions[version]!;
161 for (const atom of [...(delta.dropped ?? [])].map((id) => project.graph.atom(id)).sort((a, b) => b.seq - a.seq))
162 state = adapter.removeAtom(state, atom);
163 for (const atom of delta.atoms.map((id) => project.graph.atom(id)).sort((a, b) => a.seq - b.seq))
164 state = adapter.apply(state, atom);
165 versionHandle = save(version);
166 this.storage.write("integration:versions", String(version), versionHandle);
167 }
168 const handle =
169 previous && this.entries.length === expectedLength ? previous : (versionHandle ?? save(project.version));
170 this.storage.write("integration:head", "projection", handle);
171 this.storage.write("integration:head", "version", project.version);
172 if (!this.storage.read("integration:versions", String(project.version)))
173 this.storage.write("integration:versions", String(project.version), handle);
174 this.storage.write("integration:receipts", id, { result, requestDigest });
175 for (const path of this.verifyReadParity ? ["a.txt", "b.txt"] : []) {
176 const reader = new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph));
177 assert.deepEqual(reader.lines(path), project.sharedView().lines(path));
178 assert.deepEqual(reader.knownPaths(), project.sharedView().knownPaths());
179 assert.deepEqual(reader.sequence(path), project.sharedView().sequence(path));
180 assert.equal(reader.text(path), project.sharedView().text(path));
181 assert.equal(reader.hasFile(path), project.sharedView().hasFile(path));
182 assert.deepEqual(
183 adapter.lines(state, path),
184 project
185 .sharedView()
186 .lines(path)
187 .map((line) => line.id),
188 );
189 assert.deepEqual(adapter.attrs(state, path), project.sharedView().attrs(path));
190 }
191 if (fail) throw Error("injected outer rollback");
192 return result;
193 });
194 }
195 draftLines(name: string, path: string): string[] {
196 return this.withDraftReader(name, (reader) => reader.lines(path).map((line) => line.id));
197 }
198 readerForKey(key: string, graph: Graph, assertLive?: () => void): ProjectionReader {
199 const frame = this.#scopeFrames.at(-1);
200 assert.ok(frame, "projection reads require a transaction");
201 const guard = assertLive ?? this.newReadScope(graph).guard(graph);
202 const versions = new Membership(this.storage).shared.versions;
203 return projectedReader(
204 {
205 graph,
206 context: {
207 database: "database-a",
208 namespace: JSON.stringify(["database-a", "projection-a"]),
209 registry: "registry-a",
210 defaultFile: "a.txt",
211 },
212 sourceGeneration: 1,
213 sourceLength: () => this.entries.length,
214 prefixDigest: (length) => this.storage.read("integration:prefixes", String(length)) as string | undefined,
215 version: () => versions.length - 1,
216 committed: () => ({
217 version: this.storage.read("integration:head", "version") as number,
218 handle: this.storage.read("integration:head", "projection") as ProjectionHandle,
219 }),
220 at: (version) => this.storage.read("integration:versions", String(version)) as ProjectionHandle | undefined,
221 delta: (version) => versions[version],
222 guard: () => guard,
223 allocate: () => {
224 const overlay = new ProjectionOverlayStorage(this.storage, `reader-${this.#nextOverlay++}`);
225 frame.overlays.push(overlay);
226 return new CachedStateStorage(overlay, frame.overlays.length <= 32 ? 8192 : 0, 32);
227 },
228 },
229 key,
230 );
231 }
233 withDraftReader<T>(name: string, read: (reader: ProjectionReader) => T): T {
234 const rollback = Symbol("completed draft read");
235 let result!: T;
236 try {
237 this.#transaction(() => {
238 const project = Project.openWriter(this.store, this.storage, this.entries.length, {
239 readViewProvider: this.readViewProvider,
240 });
241 const actor = new WriterAgents(this.storage).get(name);
242 assert.ok(actor);
243 assert.equal(actor.space, "", "named draft projection is not implemented in this test host");
244 const handle = this.storage.read("integration:versions", String(actor.base)) as ProjectionHandle;
245 assert.ok(handle, "missing exact base projection");
246 const context = {
247 database: "database-a",
248 namespace: JSON.stringify(["database-a", "projection-a"]),
249 registry: "registry-a",
250 defaultFile: "a.txt",
251 };
252 const adapter = new ExperimentalMarkerProjection(this.storage, project.graph, "a.txt", context.namespace);
253 const snapshots = new ProjectionSnapshots(this.storage, adapter, context);
254 const expected: ProjectionIdentity = {
255 ...context,
256 sourceGeneration: 1,
257 sourceLength: handle.identity.sourceLength,
258 sourceDigest: this.storage.read("integration:prefixes", String(handle.identity.sourceLength)) as string,
259 membership: String(actor.base),
260 };
261 let state = snapshots.load(handle, expected);
262 for (const id of actor.mine) state = adapter.apply(state, project.graph.atom(id));
263 result = read(new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph)));
264 throw rollback;
265 });
266 } catch (error) {
267 if (error !== rollback) throw error;
268 }
269 return result;
270 }
271}
273test("measure private routed fixed-working-set cost", { skip: process.env.ABSO_PROJECTION_COST !== "1" }, () => {
274 for (const revisions of [8, 32, 128]) {
275 const host = new ProjectionHost();
276 try {
277 host.run("init", 0, (p) => p.init({ "a.txt": "head\nrevision 0\ntail\n" }, 0));
278 for (let i = 1; i <= revisions; i++)
279 host.run(`seed-${i}`, host.entries.length, (p) => {
280 p.record("writer", { "a.txt": `head\nrevision ${i}\ntail\n` }, i * 2);
281 p.publish("writer", "Seed", i * 2 + 1);
282 });
283 host.enableReaderProvider();
284 host.verifyReadParity = false;
285 const byCollection = new Map<string, number>();
286 const callers = new Map<string, number>();
287 const read = host.storage.read.bind(host.storage);
288 host.storage.read = (collection, key) => {
289 if (process.env.ABSO_PROJECTION_TRACE === "1" && collection === "line-base") {
290 const stack = new Error().stack!.split("\n").slice(2, 11).join("\n");
291 callers.set(stack, (callers.get(stack) ?? 0) + 1);
292 }
293 const group = collection.startsWith("projection:temporary:") ? "projection:temporary" : collection;
294 byCollection.set(group, (byCollection.get(group) ?? 0) + 1);
295 return read(collection, key);
296 };
297 const reads = host.storage.reads,
298 writes = host.storage.writes,
299 scans = host.storage.scans;
300 const start = performance.now();
301 host.run("measured", host.entries.length, (p) => {
302 p.record("writer", { "a.txt": "head\nmeasured\ntail\n" }, 1000);
303 assert.equal(p.publish("writer", "Measured", 1001).ok, true);
304 });
305 console.log(
306 JSON.stringify({
307 revisions,
308 liveLines: 3,
309 milliseconds: performance.now() - start,
310 reads: host.storage.reads - reads,
311 writes: host.storage.writes - writes,
312 scans: host.storage.scans - scans,
313 collections: [...byCollection].sort((a, b) => b[1] - a[1]).slice(0, 12),
314 callers: [...callers].sort((a, b) => b[1] - a[1]).slice(0, 3),
315 }),
316 );
317 assert.equal(
318 host.storage.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'").get()!
319 .n,
320 0,
321 );
322 } finally {
323 host.storage.db.close();
324 }
325 }
326});
328for (const fail of [false, true]) {
329 test(`nested host transaction permanently expires parent readers after ${fail ? "rollback" : "commit"}`, () => {
330 const host = new ProjectionHost();
331 try {
332 host.run("init", 0, (p) => p.init({ "a.txt": "one\ntwo\n" }, 0));
333 host.run("outer", host.entries.length, (p) => {
334 const reader = host.readerForKey("v @0", p.graph, host.newReadScope(p.graph).guard(p.graph));
335 const iterator = reader.visibleLines("a.txt");
336 iterator.next();
337 const inner = () =>
338 host.run(
339 "inner",
340 host.entries.length,
341 () => {
342 assert.throws(() => reader.text("a.txt"), /expired/);
343 },
344 fail,
345 );
346 if (fail) assert.throws(inner, /outer rollback/);
347 else inner();
348 assert.throws(() => reader.text("a.txt"), /expired/);
349 assert.throws(() => iterator.next(), /expired/);
350 assert.equal(
351 host.readerForKey("v @0", p.graph, host.newReadScope(p.graph).guard(p.graph)).text("a.txt"),
352 "one\ntwo\n",
353 );
354 });
355 } finally {
356 host.storage.db.close();
357 }
358 });
359}
361test("private projection host joins actual Project commits and rolls back with canonical state", () => {
362 const host = new ProjectionHost();
363 const oracle = new Project(new MemoryStore());
364 let id = 0;
365 const run = <T>(operation: (project: Project) => T) =>
366 assert.deepEqual(host.run(String(id++), host.entries.length, operation), operation(oracle));
367 try {
368 run((p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0));
369 run((p) => p.record("left", { "a.txt": "ONE\n" }, 1));
370 run((p) => p.record("right", { "b.txt": "TWO\n" }, 2));
371 run((p) => p.publish("left", "Left", 3));
372 run((p) => p.publish("right", "Right", 4));
373 const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all());
374 const before = rows(),
375 length = host.entries.length;
376 assert.throws(
377 () => host.run("failure", length, (p) => p.record("left", { "a.txt": "again\n" }, 5), true),
378 /outer rollback/,
379 );
380 assert.equal(rows(), before);
381 assert.throws(() => host.run("stale", length - 1, () => null), /stale canonical head/);
382 assert.equal(rows(), before);
383 host.run("retry", length, (p) => p.record("left", { "a.txt": "again\n" }, 5));
384 const committed = rows();
385 host.run("retry", length, () => {
386 throw Error("retry executed twice");
387 });
388 assert.equal(rows(), committed);
389 } finally {
390 host.storage.db.close();
391 }
392});
394test("runtime provider refuses a valid root stored under the wrong version", () => {
395 const host = new ProjectionHost();
396 try {
397 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
398 host.run("edit", host.entries.length, (p) => {
399 p.record("writer", { "a.txt": "two\n" }, 1);
400 p.publish("writer", "Edit", 2);
401 });
402 const original = host.storage.read("integration:versions", "1");
403 host.storage.write("integration:versions", "1", host.storage.read("integration:versions", "0"));
404 const writes = host.storage.writes;
405 assert.throws(
406 () => host.run("wrong-version", host.entries.length, (p) => host.readerForKey("v @1", p.graph)),
407 /mismatch/,
408 );
409 assert.equal(host.storage.writes, writes);
410 host.storage.write("integration:versions", "1", original);
411 for (const key of ["v @2", "v named@1", "v @01", "v @1+a0"])
412 assert.throws(
413 () => host.run(key, host.entries.length, (p) => host.readerForKey(key, p.graph)),
414 /authority|unsupported/,
415 );
416 } finally {
417 host.storage.db.close();
418 }
419});
421test("private projection host refuses a forged source or membership handle before executing", () => {
422 const host = new ProjectionHost();
423 try {
424 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
425 const original = host.storage.read("integration:head", "projection") as ProjectionHandle;
426 for (const change of [
427 { sourceDigest: "f".repeat(64) },
428 { sourceLength: original.identity.sourceLength + 1 },
429 { membership: "900" },
430 { database: "other-database" },
431 { sourceGeneration: 2 },
432 ]) {
433 host.storage.write("integration:head", "projection", {
434 ...original,
435 identity: { ...original.identity, ...change },
436 });
437 let invoked = false;
438 const writes = host.storage.writes;
439 assert.throws(
440 () =>
441 host.run("forged", host.entries.length, () => {
442 invoked = true;
443 }),
444 /mismatch/,
445 );
446 assert.equal(invoked, false);
447 assert.equal(host.storage.writes, writes);
448 }
449 host.storage.write("integration:head", "projection", original);
450 host.run("valid", host.entries.length, (p) => p.record("writer", { "a.txt": "two\n" }, 1));
451 assert.equal(
452 host.storage.read("integration:prefixes", String(original.identity.sourceLength)),
453 original.identity.sourceDigest,
454 "later graph extension preserves the old canonical prefix identity",
455 );
456 } finally {
457 host.storage.db.close();
458 }
459});
461test("private projection host routes cross-file moves, later edits and dropping versions", (t) => {
462 const host = new ProjectionHost();
463 const oracle = new Project(new MemoryStore());
464 let id = 0;
465 const run = <T>(operation: (project: Project) => T) => {
466 const read = host.storage.read.bind(host.storage);
467 const guard =
468 host.readViewProvider &&
469 t.mock.method(host.storage, "read", (collection: string, key: string) => {
470 if (collection === 'membership:"":events') throw Error("historical membership enumeration forbidden");
471 return read(collection, key);
472 });
473 let actual: T;
474 try {
475 actual = host.run(`move-${id++}`, host.entries.length, operation);
476 } finally {
477 if (guard) guard.mock.restore();
478 }
479 assert.deepEqual(actual, operation(oracle));
480 };
481 try {
482 const block = "function example() {\n return 42;\n}\n";
483 run((p) => p.init({ "a.txt": `header\n${block}`, "b.txt": "destination\n" }, 0));
484 host.enableReaderProvider();
485 run((p) => p.record("mover", { "a.txt": "header\n", "b.txt": `destination\n${block}` }, 1));
486 run((p) => p.publish("mover", "Move function", 2));
487 run((p) => p.record("editor", { "b.txt": `destination\n${block.replace("42", "43")}` }, 3));
488 run((p) => p.publish("editor", "Edit moved function", 4));
489 run((p) => p.drop("cleanup", [2], "Undo edit", 5));
490 run((p) => p.drop("cleanup", [1], "Undo move", 6));
491 assert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), oracle.files());
492 } finally {
493 host.storage.db.close();
494 }
495});
497test("private projection host reopens the database and retries the committed receipt", () => {
498 const filename = join(mkdtempSync(join(tmpdir(), "abso-project-projection-")), "state.sqlite");
499 let host = new ProjectionHost(filename);
500 try {
501 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
502 const length = host.entries.length;
503 const result = host.run("record", length, (p) => p.record("writer", { "a.txt": "two\n" }, 1));
504 host.storage.db.close();
505 host = new ProjectionHost(filename);
506 const before = host.entries.length;
507 assert.deepEqual(
508 host.run("record", length, () => {
509 throw Error("replayed receipt executed");
510 }),
511 result,
512 );
513 assert.equal(host.entries.length, before);
514 host.run("publish", before, (p) => p.publish("writer", "After restart", 2));
515 host.storage.db.close();
516 host = new ProjectionHost(filename);
517 assert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), { "a.txt": "two\n" });
518 host.run("later", host.entries.length, (p) => p.record("writer", { "a.txt": "three\n" }, 3));
519 } finally {
520 host.storage.db.close();
521 }
522});
524test("private projection host reuses its snapshot when an operation appends nothing", () => {
525 const host = new ProjectionHost();
526 try {
527 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
528 const head = host.storage.read("integration:head", "projection");
529 const length = host.entries.length;
530 assert.deepEqual(
531 host.run("read", length, (p) => p.files()),
532 { "a.txt": "one\n" },
533 );
534 assert.deepEqual(host.storage.read("integration:head", "projection"), head);
535 assert.equal(host.entries.length, length);
536 } finally {
537 host.storage.db.close();
538 }
539});
541test("private projection receipts reject changed request, target or authority", () => {
542 const host = new ProjectionHost();
543 const request = {
544 body: JSON.stringify({ kind: "init", files: { "a.txt": "one\n" } }),
545 target: "shared",
546 authority: "writer-a",
547 };
548 try {
549 const result = host.run("request", 0, (p) => p.init({ "a.txt": "one\n" }, 0), false, request);
550 for (const changed of [
551 { ...request, body: "different" },
552 { ...request, target: "draft" },
553 { ...request, authority: "writer-b" },
554 ]) {
555 const writes = host.storage.writes;
556 assert.throws(
557 () =>
558 host.run(
559 "request",
560 0,
561 () => {
562 throw Error("must not execute");
563 },
564 false,
565 changed,
566 ),
567 /request conflict/,
568 );
569 assert.equal(host.storage.writes, writes);
570 }
571 assert.deepEqual(
572 host.run(
573 "request",
574 0,
575 () => {
576 throw Error("must not execute");
577 },
578 false,
579 request,
580 ),
581 result,
582 );
583 } finally {
584 host.storage.db.close();
585 }
586});
588test("private projection derives each concurrent draft from its exact older base", () => {
589 const host = new ProjectionHost();
590 try {
591 host.run("init", 0, (p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0));
592 host.run("left", host.entries.length, (p) => p.record("left", { "a.txt": "LEFT\n" }, 1));
593 host.run("right", host.entries.length, (p) => p.record("right", { "b.txt": "RIGHT\n" }, 2));
594 host.run("publish", host.entries.length, (p) => p.publish("right", "Advance shared", 3));
595 const project = Project.openWriter(host.store, host.storage, host.entries.length);
596 for (const actor of ["left", "right"])
597 for (const path of ["a.txt", "b.txt"])
598 assert.deepEqual(
599 host.draftLines(actor, path),
600 project
601 .draftOf(actor)!
602 .view.lines(path)
603 .map((line) => line.id),
604 );
605 assert.notDeepEqual(host.draftLines("left", "b.txt"), host.draftLines("right", "b.txt"));
606 } finally {
607 host.storage.db.close();
608 }
609});
611test("private draft projection does not enumerate historical membership or canonical frames", (t) => {
612 const host = new ProjectionHost();
613 try {
614 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
615 for (let i = 0; i < 12; i++) {
616 host.run(`record-${i}`, host.entries.length, (p) => p.record("writer", { "a.txt": `${i}\n` }, i * 2 + 1));
617 host.run(`publish-${i}`, host.entries.length, (p) => p.publish("writer", `Revision ${i}`, i * 2 + 2));
618 }
619 host.run("draft", host.entries.length, (p) => p.record("draft", { "a.txt": "pending\n" }, 30));
620 const project = Project.openWriter(host.store, host.storage, host.entries.length);
621 const expected = project
622 .draftOf("draft")!
623 .view.lines("a.txt")
624 .map((line) => line.id);
625 const read = host.storage.read.bind(host.storage);
626 t.mock.method(host.storage, "read", (collection: string, key: string) => {
627 if (
628 collection === "integration:canonical" ||
629 (collection.startsWith("membership:") && (collection.includes(":events") || collection.endsWith(":own")))
630 )
631 throw Error(`historical enumeration forbidden: ${collection}`);
632 return read(collection, key);
633 });
634 t.mock.method(host.storage, "entries", () => {
635 throw Error("collection enumeration forbidden");
636 });
637 assert.deepEqual(host.draftLines("draft", "a.txt"), expected);
638 } finally {
639 host.storage.db.close();
640 }
641});
643test("temporary draft projection leaves no pages after repeated reads or a failed write", () => {
644 const host = new ProjectionHost();
645 try {
646 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
647 host.run("draft", host.entries.length, (p) => p.record("writer", { "a.txt": "draft\n" }, 1));
648 const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all());
649 const before = rows();
650 const expected = Project.openWriter(host.store, host.storage, host.entries.length)
651 .draftOf("writer")!
652 .view.lines("a.txt")
653 .map((line) => line.id);
654 for (let i = 0; i < 3; i++) {
655 assert.deepEqual(host.draftLines("writer", "a.txt"), expected);
656 assert.equal(rows(), before);
657 }
658 host.storage.failWrite = host.storage.writes + 3;
659 assert.throws(() => host.draftLines("writer", "a.txt"), /injected/);
660 assert.equal(rows(), before);
661 host.storage.failWrite = Infinity;
662 assert.deepEqual(host.draftLines("writer", "a.txt"), expected);
663 assert.equal(rows(), before);
664 } finally {
665 host.storage.db.close();
666 }
667});
669test("private host retains intermediate version roots inside one outer commit", () => {
670 const host = new ProjectionHost();
671 try {
672 host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0));
673 host.run("batch", host.entries.length, (p) => {
674 p.record("first", { "a.txt": "two\n" }, 1);
675 p.publish("first", "Two", 2);
676 p.record("old-base", { "a.txt": "older draft\n" }, 3);
677 p.record("second", { "a.txt": "three\n" }, 4);
678 p.publish("second", "Three", 5);
679 });
680 assert.ok(host.storage.read("integration:versions", "1"));
681 assert.ok(host.storage.read("integration:versions", "2"));
682 const project = Project.openWriter(host.store, host.storage, host.entries.length);
683 assert.deepEqual(
684 host.draftLines("old-base", "a.txt"),
685 project
686 .draftOf("old-base")!
687 .view.lines("a.txt")
688 .map((line) => line.id),
689 );
690 } finally {
691 host.storage.db.close();
692 }
693});
695for (const competingPath of ["a.txt", "b.txt"] as const) {
696 for (const mode of ["rollback", "commit"] as const) {
697 test(`actual Project record and publish route privately with ${mode}, competing ${competingPath}, and no old closure`, (t) => {
698 const filename = join(mkdtempSync(join(tmpdir(), "projection-route-")), "state.sqlite");
699 let host = new ProjectionHost(filename);
700 try {
701 host.run("init", 0, (p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0));
702 host.run("left", host.entries.length, (p) => p.record("left", { "a.txt": "LEFT\n" }, 1));
703 host.run("right", host.entries.length, (p) => p.record("right", { [competingPath]: "RIGHT\n" }, 2));
704 host.run("publish", host.entries.length, (p) => p.publish("right", "Advance shared", 3));
705 const expected = "LEFT\n";
706 const oracle = Project.load([...host.entries], new MemoryStore());
707 const recorded = oracle.record("left", { "a.txt": "UPDATED\n" }, 4);
708 const published = oracle.publish("left", "Publish routed edit", 5);
709 assert.equal(published.ok, competingPath !== "a.txt");
710 const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all());
711 const before = rows();
712 let calls = 0;
713 let lastReader: ProjectionReader | undefined;
714 host.readViewProvider = (graph) => {
715 const scope = host.newReadScope(graph);
716 return {
717 keyed: (key) => {
718 calls++;
719 return (lastReader = host.readerForKey(key, graph, scope.guard(graph)));
720 },
721 };
722 };
723 const route = (project: Project) => {
724 calls = 0;
725 const unkeyed = t.mock.method(ViewCache.prototype, "view", () => {
726 throw Error("unkeyed historical View construction is forbidden");
727 });
728 const replay = t.mock.method(Project, "load", () => {
729 throw Error("canonical Project replay is forbidden");
730 });
731 const read = host.storage.read.bind(host.storage);
732 const guard = t.mock.method(host.storage, "read", (collection: string, key: string) => {
733 if (collection === 'membership:"":events') throw Error("old closure membership enumeration forbidden");
734 return read(collection, key);
735 });
736 try {
737 assert.equal(project.draftOf("left")!.view.text("a.txt"), expected);
738 assert.equal(calls, 1);
739 assert.deepEqual(project.record("left", { "a.txt": "UPDATED\n" }, 4), recorded);
740 assert.deepEqual(project.publish("left", "Publish routed edit", 5), published);
741 } finally {
742 replay.mock.restore();
743 unkeyed.mock.restore();
744 guard.mock.restore();
745 }
746 };
747 if (mode === "rollback") {
748 host.withDraftReader("left", () =>
749 route(
750 Project.openWriter(host.store, host.storage, host.entries.length, {
751 readViewProvider: host.readViewProvider,
752 }),
753 ),
754 );
755 assert.equal(rows(), before);
756 } else {
757 const length = host.entries.length;
758 assert.throws(() => host.run("routed", length, route, true), /injected outer rollback/);
759 assert.equal(rows(), before);
760 assert.throws(() => lastReader!.text("a.txt"), /expired|stale/);
761 host.run("routed", length, route);
762 assert.equal(
763 host.storage.db
764 .prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'")
765 .get()!.n,
766 0,
767 );
768 const committed = rows();
769 host.storage.db.close();
770 host = new ProjectionHost(filename);
771 assert.equal(rows(), committed);
772 host.run("routed", length, () => {
773 throw Error("committed retry executed twice");
774 });
775 assert.equal(rows(), committed);
776 host.withDraftReader("left", (reader) => {
777 assert.equal(reader.text("a.txt"), oracle.draftOf("left")!.view.text("a.txt"));
778 assert.equal(reader.text("b.txt"), oracle.draftOf("left")!.view.text("b.txt"));
779 const shared = host.readerForKey(`v @${oracle.version}`, reader.graph);
780 for (const path of ["a.txt", "b.txt"]) assert.equal(shared.text(path), oracle.sharedView().text(path));
781 });
782 assert.equal(rows(), committed);
783 }
784 assert.ok(lastReader);
785 assert.throws(() => lastReader!.text("a.txt"), /expired|stale/);
786 } finally {
787 host.storage.db.close();
788 }
789 });
790 }
791}