11 files, 591 lines added, 67 removed.
--- a/src/engine/experimental/projection-atom-adoption.ts
+++ b/src/engine/experimental/projection-atom-adoption.ts
@@ -1,5 +1,6 @@
11import { createHash } from "node:crypto"; 22import type { Atom } from "../types.ts"; 3+import { ProjectionAtomDescriptor } from "./projection-atom-index.ts"; 34import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts"; 45import { adoptMovesStep } from "./projection-move-adoption.ts"; @@ -81,7 +82,7 @@
8384 previous: MarkerState; 84− atom: Atom;
85+ atom: Atom | ProjectionAtomDescriptor; @@ -101,8 +102,36 @@
102103 throw Error("invalid atom adoption page bounds"); 103104 const atom = input.atom; 104− const identity = digest([input.source, input.previous, atom, input.remove]);
105− if (digest(p.graph.atom(atom.id)) !== digest(atom)) throw Error("canonical adoption atom mismatch");
105+ const indexed = atom instanceof ProjectionAtomDescriptor ? atom : undefined; 106+ const full = indexed ? undefined : (atom as Atom); 107+ const identity = digest([ 110+ indexed ? [indexed.id, indexed.seq, indexed.digest] : atom, 114+ if (p.graph.idOfSeq(indexed.seq) !== indexed.id) throw Error("canonical adoption atom mismatch"); 115+ } else if (digest(p.graph.atom(atom.id)) !== digest(full)) throw Error("canonical adoption atom mismatch"); 116+ const inserts = indexed?.count("inserts") ?? full!.inserts.length; 117+ const run = (i: number) => 119+ ? indexed.item("inserts", i) 120+ : { file: full!.inserts[i]!.file, parent: full!.inserts[i]!.parent, lines: full!.inserts[i]!.lines.length }; 121+ const deps = indexed?.count("deps") ?? full!.deps.length; 122+ const dependency = (i: number) => (indexed ? indexed.item("deps", i) : full!.deps[i]!); 123+ const deletes = indexed?.count("deletes") ?? full!.deletes.length; 124+ const deletion = (i: number) => (indexed ? indexed.item("deletes", i) : full!.deletes[i]!); 125+ const attrs = indexed?.count("attrs") ?? full!.attrs?.length ?? 0; 126+ const attribute = (i: number) => (indexed ? indexed.item("attrs", i) : full!.attrs![i]!); 127+ const moves = indexed?.count("moves") ?? full!.moves?.length ?? 0; 128+ const fullFiles = indexed ? undefined : p.graph.filesOf(atom.id); 129+ const files = indexed?.count("files") ?? fullFiles!.length; 130+ const file = (i: number) => (indexed ? indexed.item("files", i) : fullFiles![i]!); 131+ const seqOf = (id: string) => { 132+ if (!p.graph.has(id)) throw Error("missing dependency"); 133+ return Number(id.slice(1)); 106135 const collection = `atom-adoption:${this.task}`; 107136 const validate = () => { 108137 const result: unknown = input.validateSource(); @@ -121,19 +150,19 @@
122151 throw Error("invalid or changed atom adoption cursor"); 123152 p.assertContext(cursor.state); 124− if (cursor.run > atom.inserts.length || cursor.line > (atom.inserts[cursor.run]?.lines.length ?? 0))
153+ if (cursor.run > inserts || cursor.line > (cursor.run < inserts ? run(cursor.run).lines : 0)) 125154 throw Error("invalid atom adoption line position"); 126155 const limits: Record<Phase, number> = { 127− dependencies: atom.deps.length,
128− files: atom.inserts.length + 1,
130− deletes: atom.deletes.length,
131− counts: atom.deps.length,
132− attributes: atom.attrs?.length ?? 0,
133− contributions: p.graph.filesOf(atom.id).length,
162+ contributions: files, 136− cleanup: atom.attrs?.length ?? 0,
139168 if (cursor.index > limits[cursor.phase]) throw Error("invalid atom adoption phase position"); @@ -158,35 +187,35 @@
158187 cursor!.index = 0; 160189 const state = cursor.state; 161− const contributionFiles = p.graph.filesOf(atom.id);
162191 while (cursor.phase !== "done" && steps < input.maxSteps) { 164193 switch (cursor.phase) { 165194 case "dependencies": { 166− if (input.remove || cursor.index === atom.deps.length) {
195+ if (input.remove || cursor.index === deps) { 170− const id = atom.deps[cursor.index++]!;
171− if (!p.members.get(state.membership, p.graph.atom(id).seq)?.present) throw Error("missing dependency");
199+ const id = dependency(cursor.index++); 200+ if (!p.members.get(state.membership, seqOf(id))?.present) throw Error("missing dependency"); 175− if (input.remove || cursor.index > atom.inserts.length) {
204+ if (input.remove || cursor.index > inserts) { 179− p.ensureFile(state, cursor.index === 0 ? p.path : atom.inserts[cursor.index - 1]!.file);
208+ p.ensureFile(state, cursor.index === 0 ? p.path : run(cursor.index - 1).file); 184− if (cursor.run === atom.inserts.length) {
213+ if (cursor.run === inserts) { 188− const run = atom.inserts[cursor.run]!;
189− if (cursor.line === run.lines.length) {
217+ const currentRun = run(cursor.run); 218+ if (cursor.line === currentRun.lines) { @@ -202,11 +231,11 @@
205− if (cursor.index === atom.deletes.length) {
234+ if (cursor.index === deletes) { 209− const marker = p.markers.get(state.locator, p.graph.lineN(atom.deletes[cursor.index++]!) + 1);
238+ const marker = p.markers.get(state.locator, p.graph.lineN(deletion(cursor.index++)) + 1); 210239 if (!marker) throw Error("missing deleted marker"); 211240 state.sequence = p.sequence.update(state.sequence, { 212241 kind: "visibility", @@ -216,11 +245,11 @@
219− if (cursor.index === atom.deps.length) {
248+ if (cursor.index === deps) { 223− const seq = p.graph.atom(atom.deps[cursor.index++]!).seq;
252+ const seq = seqOf(dependency(cursor.index++)); 224253 const member = p.members.get(state.membership, seq); 225254 if (!member?.present || (input.remove && member.dependents < 1)) throw Error("invalid dependency count"); 226255 state.membership = p.members.set(state.membership, seq, { @@ -230,25 +259,24 @@
232261 case "attributes": { 233− const attrs = atom.attrs ?? [];
234− if (cursor.index === attrs.length) {
262+ if (cursor.index === attrs) { 238− const attr = attrs[cursor.index++]!;
266+ const attr = attribute(cursor.index++); 239267 const key = JSON.stringify([attr.file, attr.name]); 240268 if (!p.storage.read(`${collection}:attributes`, key)) { 241− p.updateAttributes(state, { ...atom, attrs: [attr] }, !input.remove);
269+ p.updateAttributes(state, { seq: atom.seq, attrs: [attr] }, !input.remove); 242270 p.storage.write(`${collection}:attributes`, key, true); 246274 case "contributions": { 247− if (cursor.index === contributionFiles.length) {
275+ if (cursor.index === files) { 251− const path = contributionFiles[cursor.index++]!;
279+ const path = file(cursor.index++); 252280 p.ensureFile(state, path); 253281 const key = p.fileKey(path)!; 254282 const marker = p.markers.get(state.locator, key); @@ -266,20 +294,33 @@
269− if (atom.moves?.length) {
270− const result = adoptMovesStep(p, state, this.task, identity);
298+ const result = adoptMovesStep( 305+ count: (id) => indexed.related(id).count("moves"), 307+ const atom = indexed.related(id); 308+ return k < atom.count("moves") ? atom.item("moves", k) : undefined; 271313 Object.assign(state, result.state); 272314 if (!result.done) break; 277− const attrs = atom.attrs ?? [];
278− if (cursor.index === attrs.length) {
319+ if (cursor.index === attrs) { 282− const attr = attrs[cursor.index++]!;
323+ const attr = attribute(cursor.index++); 283324 p.storage.remove(`${collection}:attributes`, JSON.stringify([attr.file, attr.name])); --- /dev/null
+++ b/src/engine/experimental/projection-atom-index.ts
@@ -0,0 +1,177 @@
1+import { createHash } from "node:crypto"; 2+import type { GraphStateStorage } from "../state-source.ts"; 3+import type { Atom, AttrSet, Relocation } from "../types.ts"; 5+type Field = "deps" | "inserts" | "deletes" | "attrs" | "moves" | "files"; 16+ counts: Record<Field, number>; 19+const fields: Field[] = ["deps", "inserts", "deletes", "attrs", "moves", "files"]; 21+// Checksums detect record damage; authority comes from the canonical writer transaction. 22+const checksum = (value: unknown): string => createHash("sha256").update(JSON.stringify(value)).digest("hex"); 23+const headerChecksum = (header: Omit<Header, "checksum">): string => 24+ checksum([header.format, header.id, header.seq, header.digest, fields.map((field) => header.counts[field])]); 26+function shape(value: unknown, keys: readonly string[]): asserts value is Record<string, unknown> { 29+ typeof value !== "object" || 30+ Array.isArray(value) || 31+ Object.keys(value).length !== keys.length || 32+ keys.some((key) => !Object.hasOwn(value, key)) 34+ throw Error("invalid projection atom record"); 36+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 37+const atomId = (value: unknown): value is string => 38+ typeof value === "string" && /^a(0|[1-9][0-9]*)$/.test(value) && integer(Number(value.slice(1))); 39+const lineId = (value: unknown): value is string => 40+ typeof value === "string" && 41+ /^a(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(value) && 42+ value.split(".").every((part, i) => integer(Number(i === 0 ? part.slice(1) : part))); 43+const parent = (value: unknown) => typeof value === "string" && (value.startsWith("^") || lineId(value)); 44+function itemValue(field: Field, value: unknown): unknown { 45+ if (field === "deps" || field === "deletes" || field === "files") { 46+ if (!(field === "deps" ? atomId(value) : field === "deletes" ? lineId(value) : typeof value === "string")) 47+ throw Error("invalid projection atom item"); 48+ } else if (field === "inserts") { 49+ shape(value, ["file", "parent", "lines"]); 50+ if (typeof value.file !== "string" || !parent(value.parent) || !integer(value.lines)) 51+ throw Error("invalid projection atom run"); 52+ } else if (field === "moves") { 53+ shape(value, ["line", "parent"]); 54+ if (!lineId(value.line) || !parent(value.parent)) throw Error("invalid projection atom move"); 56+ shape(value, ["file", "name", "value"]); 58+ typeof value.file !== "string" || 59+ !["exists", "exec", "link", "blob"].includes(String(value.name)) || 60+ (value.value !== null && typeof value.value !== "string") 62+ throw Error("invalid projection atom attribute"); 64+ return structuredClone(value); 67+/** Derived index only. The caller supplies an already validated canonical atom and 68+ * its digest inside the canonical indexing transaction. This builder does not 69+ * claim bounded decoding of the original atom. */ 70+export class ProjectionAtomIndex { 71+ readonly storage: GraphStateStorage; 72+ constructor(storage: GraphStateStorage) { 73+ this.storage = storage; 75+ put(atom: Atom, digest: string, files: readonly string[]): void { 76+ if (!/^[a-f0-9]{64}$/.test(digest) || !Number.isSafeInteger(atom.seq) || atom.seq < 0 || atom.id !== `a${atom.seq}`) 77+ throw Error("invalid projection atom identity"); 78+ const name = `projection-atom-index:${atom.id}`; 79+ this.storage.transaction(() => { 80+ if (this.storage.read(name, "header") !== undefined) throw Error("projection atom index already exists"); 81+ const counts = {} as Record<Field, number>; 82+ for (const field of fields) { 83+ const values = field === "files" ? files : (atom[field] ?? []); 84+ counts[field] = values.length; 85+ for (let i = 0; i < values.length; i++) { 88+ ? { file: atom.inserts[i]!.file, parent: atom.inserts[i]!.parent, lines: atom.inserts[i]!.lines.length } 90+ const item = itemValue(field, value); 91+ this.storage.write(name, `${field}:${i}`, { 93+ checksum: checksum([atom.id, digest, field, i, item]), 97+ const header = { format: 1 as const, id: atom.id, seq: atom.seq, digest, counts }; 98+ this.storage.write(name, "header", { ...header, checksum: headerChecksum(header) } satisfies Header); 101+ /** Read a descriptor from a source-fenced, atomically maintained writer index. */ 102+ openAccepted(id: string): ProjectionAtomDescriptor { 103+ if (!atomId(id)) throw Error("invalid projection atom identity"); 104+ const header = this.storage.read(`projection-atom-index:${id}`, "header"); 105+ shape(header, ["format", "id", "seq", "digest", "counts", "checksum"]); 106+ if (typeof header.digest !== "string") throw Error("invalid projection atom digest"); 107+ return this.open(id, header.digest); 110+ open(id: string, digest: string): ProjectionAtomDescriptor { 111+ if (!/^a(0|[1-9][0-9]*)$/.test(id) || !/^[a-f0-9]{64}$/.test(digest)) 112+ throw Error("invalid projection atom identity"); 113+ const name = `projection-atom-index:${id}`; 114+ const raw = this.storage.read(name, "header"); 115+ shape(raw, ["format", "id", "seq", "digest", "counts", "checksum"]); 116+ shape(raw.counts, fields); 117+ const header = raw as unknown as Header; 119+ header.checksum !== headerChecksum(header) || 120+ header.format !== 1 || 122+ header.digest !== digest || 123+ !Number.isSafeInteger(header.seq) || 125+ id !== `a${header.seq}` || 127+ Object.keys(header.counts).length !== fields.length || 128+ fields.some((field) => !Number.isSafeInteger(header.counts[field]) || header.counts[field] < 0) 130+ throw Error("missing or invalid projection atom index"); 131+ return new ProjectionAtomDescriptor(this.storage, name, structuredClone(header)); 134+export class ProjectionAtomDescriptor { 135+ readonly id: string; 136+ readonly seq: number; 137+ readonly digest: string; 138+ readonly #storage: GraphStateStorage; 139+ readonly #name: string; 140+ readonly #counts: Record<Field, number>; 141+ constructor(storage: GraphStateStorage, name: string, header: Header) { 142+ this.#storage = storage; 144+ this.id = header.id; 145+ this.seq = header.seq; 146+ this.digest = header.digest; 147+ this.#counts = { ...header.counts }; 149+ related(id: string): ProjectionAtomDescriptor { 150+ return new ProjectionAtomIndex(this.#storage).openAccepted(id); 153+ count(field: Field): number { 154+ if (!fields.includes(field)) throw Error("invalid projection atom field"); 155+ return this.#counts[field]; 157+ item(field: "inserts", index: number): Run; 158+ item(field: "attrs", index: number): AttrSet; 159+ item(field: "moves", index: number): Relocation; 160+ item(field: "deps" | "deletes" | "files", index: number): string; 161+ item(field: Field, index: number): unknown { 162+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.count(field)) 163+ throw Error("projection atom item out of range"); 164+ const value = this.#storage.read(this.#name, `${field}:${index}`); 165+ if (value === undefined) throw Error("missing projection atom item"); 166+ shape(value, ["value", "checksum"]); 167+ if (value.checksum !== checksum([this.id, this.digest, field, index, value.value])) 168+ throw Error("invalid projection atom item checksum"); 169+ return itemValue(field, value.value); 173+/** Opt-in persistent Graph callback: indexes the just-accepted canonical atom. */ 174+export function indexAcceptedProjectionAtom(atom: Atom, files: readonly string[], storage: GraphStateStorage): void { 175+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex"); 176+ new ProjectionAtomIndex(storage).put(atom, digest, files); --- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -380,7 +380,7 @@
381381 return paths.sort(); 383− updateAttributes(state: MarkerState, atom: Atom, adding: boolean): void {
383+ updateAttributes(state: MarkerState, atom: Pick<Atom, "seq" | "attrs">, adding: boolean): void { 384384 this.assertContext(state); 385385 const index = this.attributePriorities, 386386 hex = (n: number) => n.toString(16).padStart(14, "0"); --- a/src/engine/experimental/projection-move-adoption.ts
+++ b/src/engine/experimental/projection-move-adoption.ts
@@ -3,7 +3,7 @@
33import { orderedChildKey } from "../ordered-index.ts"; 44import type { GraphStateStorage } from "../state-source.ts"; 55import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts"; 6−import { resolveMovesPage } from "./projection-move-resolution.ts";
6+import { graphMoveSource, type ProjectionMoveSource, resolveMovesPage } from "./projection-move-resolution.ts"; 88type Phase = "files" | "resolve" | "plans" | "park" | "place" | "cleanup" | "done"; @@ -41,6 +41,7 @@
4141 previous: MarkerState, 44+ source: ProjectionMoveSource = graphMoveSource(p.graph), 4445): { done: boolean; state: MarkerState } { 4546 p.assertContext(previous); 4647 if (!task || task.length > 128 || !/^[a-f0-9]{64}$/.test(identity)) throw Error("invalid move adoption identity"); @@ -83,10 +84,9 @@
8485 throw Error("invalid move adoption cursor"); 8586 const mover = p.graph.movers()[cursor.mover]; 86− if (cursor.move > (mover === undefined ? 0 : (p.graph.atom(mover).moves?.length ?? 0)))
87− throw Error("invalid move adoption offset");
87+ if (cursor.move > (mover === undefined ? 0 : source.count(mover))) throw Error("invalid move adoption offset"); 8888 let state = { ...previous }; 89− const has = (id: string) => p.members.get(state.membership, p.graph.atom(id).seq)?.present ?? false;
89+ const has = (id: string) => p.members.get(state.membership, Number(id.slice(1)))?.present ?? false; 9090 switch (cursor.phase) { @@ -96,14 +96,16 @@
99− const moves = p.graph.atom(p.graph.movers()[cursor.mover]!).moves ?? [];
100− if (cursor.move > moves.length) throw Error("invalid move adoption offset");
101− if (cursor.move === moves.length) {
99+ const moverId = p.graph.movers()[cursor.mover]!; 100+ const count = source.count(moverId); 101+ if (cursor.move > count) throw Error("invalid move adoption offset"); 102+ if (cursor.move === count) { 106− const move = moves[cursor.move++]!;
107+ const move = source.at(moverId, cursor.move++); 108+ if (!move) throw Error("missing indexed move"); 107109 if (cursor.phase === "files") { 108110 if (move.parent.startsWith("^")) p.ensureFile(state, move.parent.slice(1)); @@ -119,7 +121,7 @@
119121 if (parent === undefined) throw Error("missing relocation ancestry"); 120122 const parentKey = parent.startsWith("^") ? p.fileKey(parent.slice(1)) : p.graph.lineN(parent) + 1; 121123 if (parentKey === undefined) throw Error("missing relocation file"); 122− const seq = selected ? p.graph.atom(selected.atom).seq : p.graph.writerSeqOf(n);
124+ const seq = selected ? Number(selected.atom.slice(1)) : p.graph.writerSeqOf(n); 123125 const key = orderedChildKey({ 125127 replaces: selected ? 0 : Number(p.graph.replacesN(n)), @@ -132,7 +134,7 @@
135− if (resolveMovesPage(p.graph, has, scratch, identity, 1).done) cursor.phase = "plans";
137+ if (resolveMovesPage(p.graph, has, scratch, identity, 1, source).done) cursor.phase = "plans"; --- a/src/engine/experimental/projection-move-resolution.ts
+++ b/src/engine/experimental/projection-move-resolution.ts
@@ -2,8 +2,16 @@
22import type { Graph, RelocationInfo } from "../graph.ts"; 33import { isStartNode } from "../keys.ts"; 44import type { GraphStateStorage } from "../state-source.ts"; 5−import type { NodeId } from "../types.ts";
5+import type { NodeId, Relocation } from "../types.ts"; 7+export interface ProjectionMoveSource { 8+ count(id: string): number; 9+ at(id: string, k: number): Relocation | undefined; 11+export function graphMoveSource(graph: Graph): ProjectionMoveSource { 12+ return { count: (id) => graph.atom(id).moves?.length ?? 0, at: (id, k) => graph.atom(id).moves?.[k] }; 917 phase: "scan" | "walk" | "entry" | "weakest" | "repick" | "mark" | "done"; @@ -33,7 +41,7 @@
3442 throw Error("invalid move resolution record"); 36−function readProgress(value: unknown, graph: Graph): Progress | undefined {
44+function readProgress(value: unknown, graph: Graph, source: ProjectionMoveSource): Progress | undefined { 3745 if (value === undefined) return undefined; 3846 shape(value, "format checksum state"); 3947 if (value.format !== 1 || value.checksum !== digest(value.state)) throw Error("damaged move resolution cursor"); @@ -51,8 +59,7 @@
5260 throw Error("invalid move resolution position"); 5361 const mover = graph.movers()[Number(state.mover)]; 54− if (Number(state.move) > (mover === undefined ? 0 : (graph.atom(mover).moves?.length ?? 0)))
55− throw Error("invalid move offset");
62+ if (Number(state.move) > (mover === undefined ? 0 : source.count(mover))) throw Error("invalid move offset"); 5663 for (const key of ["line", "slow", "fast", "meeting", "entry", "current"]) 5764 if (state[key] !== null && (typeof state[key] !== "string" || !state[key] || String(state[key]).length > 4096)) 5865 throw Error("invalid move ancestry cursor"); @@ -61,7 +68,7 @@
6168 if (move === null) continue; 6269 shape(move, "atom line parent k"); 6370 if (typeof move.atom !== "string" || !integer(move.k)) throw Error("invalid saved move"); 64− const canonical = graph.atom(move.atom).moves?.[move.k];
71+ const canonical = source.at(move.atom, move.k); 6572 if (!canonical || canonical.line !== move.line || canonical.parent !== move.parent) 6673 throw Error("saved move identity mismatch"); @@ -83,11 +90,12 @@
8390 storage: GraphStateStorage, 93+ source: ProjectionMoveSource = graphMoveSource(graph), 8694): { done: boolean; steps: number } { 8795 if (!identity || identity.length > 4096 || !Number.isSafeInteger(maxSteps) || maxSteps < 1 || maxSteps > 256) 8896 throw Error("invalid move resolution page"); 8997 return storage.transaction(() => { 90− let state = readProgress(storage.read("progress", "cursor"), graph);
98+ let state = readProgress(storage.read("progress", "cursor"), graph, source); 9199 if (state && state.identity !== identity) throw Error("move resolution identity changed"); @@ -144,14 +152,16 @@
147− const moves = graph.atom(id).moves ?? [];
148− if (state.move === moves.length) {
155+ const count = source.count(id); 156+ if (state.move === count) { 153161 const k = state.move++; 154− const candidate: RelocationInfo = { atom: id, ...moves[k]!, k };
162+ const move = source.at(id, k); 163+ if (!move) throw Error("missing indexed move"); 164+ const candidate: RelocationInfo = { atom: id, ...move, k }; 155165 if (state.phase === "scan") { 156166 if (!storage.read("seen", candidate.line)) { 157167 storage.write("seen", candidate.line, true); --- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -277,6 +277,8 @@
277277 #textCache = new Map<number, readonly string[]>(); 280+ readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void; 281283 * `texts`, when given, says where each atom's lines' text can be read back 282284 * (#46): the graph then keeps no text, only each line's place, and reads an @@ -287,8 +289,13 @@
287289 texts?: (seq: number) => readonly (readonly string[])[]; 288290 lists?: (seq: number) => AtomLists; 289291 storage?: GraphStateStorage; 292+ /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */ 293+ indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void; 296+ if (options.indexAcceptedAtom && !options.storage) 297+ throw Error("accepted atom indexing requires persistent storage"); 298+ this.#indexAcceptedAtom = options.indexAcceptedAtom; 292299 if (options.texts) { 293300 this.#texts = options.texts; 294301 this.#lineText = undefined; @@ -994,7 +1001,13 @@
9941001 * The atom is frozen. Adding to the graph does not add it to any set. 9961003 add(atom: Atom): void { 997− if (this.#storage) this.#storage.transaction(() => this.#add(atom));
1005+ this.#storage.transaction(() => { 1007+ const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!); 1008+ if (result && typeof result === "object" && "then" in result) 1009+ throw Error("accepted atom indexing must be synchronous"); 9981011 else this.#add(atom); --- /dev/null
+++ b/src/engine/test/projection-atom-index.test.ts
@@ -0,0 +1,227 @@
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 { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts"; 8+import { indexAcceptedProjectionAtom, ProjectionAtomIndex } from "../experimental/projection-atom-index.ts"; 9+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts"; 10+import { Graph } from "../graph.ts"; 11+import { Repo } from "./helpers.ts"; 12+import { SqlState } from "./storage-helper.ts"; 14+test("projection atom descriptors exclude inserted text and read one indexed item", () => { 15+ const db = new SqlState(); 17+ const repo = Repo.init({ "a.txt": "large text\n".repeat(1000) }); 18+ const atom = repo.graph.atom("a0"), 19+ digest = "a".repeat(64); 20+ new ProjectionAtomIndex(db).put(atom, digest, ["a.txt"]); 21+ const descriptor = new ProjectionAtomIndex(db).open("a0", digest); 22+ const before = db.reads; 23+ assert.equal(descriptor.count("inserts"), 1); 24+ assert.deepEqual(descriptor.item("inserts", 0), { file: "a.txt", parent: "^a.txt", lines: 1000 }); 25+ assert.equal(db.reads - before, 1); 26+ assert.throws(() => descriptor.item("inserts", 1), /out of range/); 27+ assert.throws(() => new ProjectionAtomIndex(db).open("a0", "b".repeat(64)), /invalid/); 28+ const rows = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 29+ assert.ok(!JSON.stringify(rows).includes("large text")); 30+ assert.throws(() => new ProjectionAtomIndex(db).put(atom, digest, ["a.txt"]), /already exists/); 31+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), rows); 37+test("descriptor builds roll back every write and corrupted records refuse", () => { 38+ const db = new SqlState(); 40+ const repo = Repo.init({ "a.txt": "one\n" }); 41+ const atom = repo.graph.atom("a0"), 42+ digest = "c".repeat(64); 43+ const index = new ProjectionAtomIndex(db); 46+ atom.inserts.length + 47+ atom.deletes.length + 48+ (atom.attrs?.length ?? 0) + 49+ (atom.moves?.length ?? 0) + 51+ for (let offset = 1; offset <= writeCount; offset++) { 52+ db.failWrite = db.writes + offset; 53+ assert.throws(() => index.put(atom, digest, ["a.txt"]), /injected/); 54+ assert.deepEqual(db.db.prepare("SELECT * FROM state").all(), []); 56+ db.failWrite = Infinity; 57+ index.put(atom, digest, ["a.txt"]); 58+ const name = "projection-atom-index:a0"; 59+ const header = db.read(name, "header") as { counts: Record<string, number> }; 60+ for (const invalid of [ 62+ { ...header, extra: true }, 63+ { ...header, counts: { ...header.counts, moves: -1 } }, 64+ { ...header, counts: [] }, 65+ { ...header, counts: { ...header.counts, inserts: 0 } }, 67+ db.write(name, "header", invalid); 68+ assert.throws(() => new ProjectionAtomIndex(db).open("a0", digest), /invalid/); 70+ db.write(name, "header", header); 71+ const descriptor = new ProjectionAtomIndex(db).open("a0", digest); 72+ const original = db.read(name, "inserts:0") as { value: unknown; checksum: string }; 73+ for (const invalid of [ 75+ { file: "a.txt", parent: "bad", lines: 1 }, 76+ { file: "a.txt", parent: "^a.txt", lines: -1 }, 77+ { file: "a.txt", parent: "^a.txt", lines: 1, extra: true }, 78+ { ...original, value: { file: "a.txt", parent: "^a.txt", lines: 2 } }, 80+ db.write(name, "inserts:0", invalid); 81+ assert.throws(() => descriptor.item("inserts", 0), /invalid/); 83+ db.write(name, "inserts:0", original); 84+ const run = descriptor.item("inserts", 0); 86+ assert.equal(descriptor.item("inserts", 0).lines, 1); 92+test("descriptor-driven insertion adoption never reads full atom storage", () => { 93+ const db = new SqlState(); 95+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n" }); 96+ const atom = repo.graph.atom("a0"), 97+ digest = "d".repeat(64); 98+ const graph = new Graph({ storage: db }); 100+ new ProjectionAtomIndex(db).put(atom, digest, graph.filesOf(atom.id)); 101+ const projection = new ExperimentalMarkerProjection(db, graph, "a.txt", "indexed-adoption"); 102+ const previous = projection.empty(); 103+ const read = db.read.bind(db); 104+ db.read = (collection, key) => { 105+ if (collection === "atoms") throw Error("full atom read forbidden"); 106+ return read(collection, key); 110+ const descriptor = new ProjectionAtomIndex(db).open(atom.id, digest); 111+ const result = new ProjectionAtomAdoption(projection, "indexed").page({ 115+ source: "e".repeat(64), 117+ validateSource: () => {}, 119+ assert.ok(result.steps <= 2); 120+ assert.ok(++pages < 100); 122+ assert.deepEqual(projection.lines(result.state), ["a0.0", "a0.1", "a0.2"]); 126+ assert.ok(pages > 1); 132+test("indexed adoption reopens through dependencies, attributes, deletion and reverse removal without atom reads", () => { 133+ const directory = mkdtempSync(join(tmpdir(), "abso-descriptor-")), 134+ filename = join(directory, "state.sqlite"); 135+ let db = new SqlState(filename); 136+ const oracleDb = new SqlState(); 138+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n", "b.txt": "" }); 140+ repo.graph.atom("a0"), 142+ edits: [{ file: "a.txt", old: "two\n", new: "replacement\n" }], 143+ attrs: [{ file: "b.txt", name: "exec", value: "1" }], 146+ atoms.push(repo.edit({ move: { file: "a.txt", start: 0, end: 1, to: "b.txt", at: 0 } })); 147+ const graph = new Graph({ storage: db }); 148+ for (const atom of atoms) { 150+ new ProjectionAtomIndex(db).put(atom, "a".repeat(64), graph.filesOf(atom.id)); 152+ const oracle = new ExperimentalMarkerProjection(oracleDb, repo.graph, "a.txt", "oracle"); 153+ let expected = oracle.empty(); 154+ let state = new ExperimentalMarkerProjection(db, graph, "a.txt", "indexed").empty(); 156+ for (const [atom, remove] of [ 157+ ...atoms.map((atom) => [atom, false] as const), 158+ ...atoms.toReversed().map((atom) => [atom, true] as const), 160+ const previous = state, 161+ id = String(task++); 165+ const read = db.read.bind(db); 166+ db.read = (collection, key) => { 167+ if (collection === "atoms") throw Error("full atom read forbidden"); 168+ return read(collection, key); 170+ const p = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "indexed"); 171+ const descriptor = new ProjectionAtomIndex(db).open(atom.id, "a".repeat(64)); 172+ const result = new ProjectionAtomAdoption(p, id).page({ 176+ source: "b".repeat(64), 178+ validateSource: () => {}, 180+ state = result.state; 182+ assert.ok(++pages < 100); 184+ db = new SqlState(filename); 186+ expected = remove ? oracle.removeAtom(expected, atom) : oracle.apply(expected, atom); 187+ const actual = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "indexed"); 188+ for (const path of ["a.txt", "b.txt"]) { 189+ assert.deepEqual(actual.lines(state, path), oracle.lines(expected, path)); 190+ assert.deepEqual(actual.attrs(state, path), oracle.attrs(expected, path)); 192+ assert.deepEqual(actual.knownPaths(state), oracle.knownPaths(expected)); 196+ oracleDb.db.close(); 197+ unlinkSync(filename); 198+ rmdirSync(directory); 202+test("accepted graph and descriptor commit together and retry after callback failure", () => { 203+ const db = new SqlState(); 205+ const atom = Repo.init({ "a.txt": "one\n" }).graph.atom("a0"); 207+ const graph = new Graph({ 209+ indexAcceptedAtom: (accepted, files, storage) => { 210+ indexAcceptedProjectionAtom(accepted, files, storage); 211+ if (fail) throw Error("after descriptor failure"); 214+ const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 215+ assert.throws(() => graph.add(atom), /after descriptor failure/); 216+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before); 217+ assert.equal(graph.size, 0); 220+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex"); 221+ assert.equal(new ProjectionAtomIndex(db).open("a0", digest).item("inserts", 0).lines, 1); 222+ assert.equal(new Graph({ storage: db }).size, 1); 223+ assert.throws(() => new Graph({ indexAcceptedAtom: indexAcceptedProjectionAtom }), /requires persistent/); --- a/src/engine/test/projection-marker-cycle.test.ts
+++ b/src/engine/test/projection-marker-cycle.test.ts
@@ -1,6 +1,7 @@
11import assert from "node:assert/strict"; 22import { test } from "node:test"; 33import { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts"; 4+import { indexAcceptedProjectionAtom, ProjectionAtomIndex } from "../experimental/projection-atom-index.ts"; 45import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts"; 56import { Graph } from "../graph.ts"; 67import { CachedStateStorage } from "../state-source.ts"; @@ -8,12 +9,15 @@
89import { Repo, Rng } from "./helpers.ts"; 910import { SqlState } from "./storage-helper.ts"; 11−for (const paged of [false, true])
12+for (const paged of [false, true, "indexed"] as const) 1213 test(`typed marker projection matches competing cyclic moves and removals (paged=${paged})`, () => { 1314 const db = new SqlState(); 1516 const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, n) => `${n}\n`).join("") }), 16− graph = new Graph({ storage: new CachedStateStorage(db) }),
18+ storage: new CachedStateStorage(db), 19+ indexAcceptedAtom: paged === "indexed" ? indexAcceptedProjectionAtom : undefined, 1721 rng = new Rng(45131); 1822 graph.add(repo.graph.atom("a0")); 1923 const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "cycle"); @@ -26,14 +30,25 @@
2630 const job = new ProjectionAtomAdoption(p, String(task++)); 2731 const previous = state; 2832 for (let pages = 0; pages < 10000; pages++) { 29− const result = job.page({
30− previous,
31− atom,
32− remove,
33− source: "c".repeat(64),
34− maxSteps: 3,
35− validateSource: () => {},
36− });
33+ const read = db.read.bind(db); 34+ if (paged === "indexed") 35+ db.read = (collection, key) => { 36+ if (collection === "atoms") throw Error("full atom read forbidden"); 37+ return read(collection, key); 43+ atom: paged === "indexed" ? new ProjectionAtomIndex(db).openAccepted(atom.id) : atom, 45+ source: "c".repeat(64), 47+ validateSource: () => {}, 3752 assert.ok(result.steps <= 3); 3853 assert.equal(result.atomicMoveWork, false); 3954 if (result.done) return result.state; --- a/worker/project/project-types.ts
+++ b/worker/project/project-types.ts
@@ -567,6 +567,8 @@
568568/** What the project needs from the store of binary files' bytes. */ 569569export interface ProjectOptions { 570+ /** Optional derived atom indexing within persistent graph acceptance. */ 571+ indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void; 570572 /** Private experimental reader route; never falls back for unsupported membership. */ 571573 readViewProvider?: (graph: Graph) => ReadViewProvider; --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -348,6 +348,8 @@
348348 readonly #hasBlob: (sha256: string) => boolean; 350350 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) { 351+ if (options.indexAcceptedAtom && !options.writerStorage) 352+ throw Error("accepted atom indexing requires writer storage"); 351353 this.#store = store; 352354 this.#writerStorage = options.writerStorage ? new CachedStateStorage(options.writerStorage) : undefined; 353355 if (this.#writerStorage) { @@ -402,7 +404,7 @@
403405 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for. 404406 this.#graph = this.#writerStorage 405− ? new Graph({ storage: this.#writerStorage })
407+ ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom }) 407409 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) }) --- a/worker/project/test/project-writer-storage.test.ts
+++ b/worker/project/test/project-writer-storage.test.ts
@@ -1,5 +1,10 @@
11import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 23import { test } from "node:test"; 5+ indexAcceptedProjectionAtom, 7+} from "../../../src/engine/experimental/projection-atom-index.ts"; 38import { Graph } from "../../../src/engine/graph.ts"; 49import { StableSet, storedArray } from "../../../src/engine/state-source.ts"; 510import { SqlState } from "../../../src/engine/test/storage-helper.ts"; @@ -206,3 +211,33 @@
206211 assert.deepEqual(Project.openWriter(store, storage, entries.length).files(), { "a.txt": "ONE\n" }); 207212 storage.db.close(); 215+test("opted-in descriptor indexing survives writer reopen and rolls back canonical append failure", () => { 216+ const fixture = setup(); 217+ const { storage, entries, store } = fixture; 218+ const options = { indexAcceptedAtom: indexAcceptedProjectionAtom }; 220+ let project = new Project(store, { writerStorage: storage, ...options }); 221+ storage.transaction(() => project.init({ "a.txt": "one\n" }, 0)); 222+ project = Project.openWriter(store, storage, entries.length, options); 223+ const rows = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 226+ () => storage.transaction(() => project.record("writer", { "a.txt": "two\n" }, 1)), 227+ /canonical append failure/, 229+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), rows); 231+ project = Project.openWriter(store, storage, entries.length, options); 232+ storage.transaction(() => project.record("writer", { "a.txt": "two\n" }, 1)); 233+ storage.transaction(() => project.publish("writer", "Indexed", 2)); 234+ const graph = new Graph({ storage }); 235+ for (const atom of graph.atoms()) { 236+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex"); 237+ assert.equal(new ProjectionAtomIndex(storage).open(atom.id, digest).seq, atom.seq); 239+ assert.deepEqual(Project.openWriter(store, storage, entries.length, options).files(), { "a.txt": "two\n" });