Lines 1–15 at 318 (were 1–12 at 160)
1−import { canonicalJson } from "../../worker/project/operation-protocol.ts";
1+import { createHash } from "node:crypto"; 2+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts"; 23import { Project, type WriterSource } from "../../worker/project/project.ts"; 34import type { ProjectOptions } from "../../worker/project/project-types.ts"; 45import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts"; 6+import { SqliteHistoryHost } from "./history-host.ts"; 57import { SqliteProjectionStore } from "./projection-store.ts"; 8+import { requestIdentityDigest } from "./request-identity-digest.ts"; 69import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts"; 811type Services = Pick<ProjectOptions, "hasBlob" | "whole">; 9−type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "ready"; next: number };
12+type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "history" | "ready"; next: number }; 1114/** One synchronous page or call per invocation. No object retains a loaded Project. 1215 * The owner schedules subsequent pages and supplies fresh authorization for every call. */ Lines 18–29 at 318 (were 15–24 at 160)
1518 readonly #namespace: string; 1619 readonly #projection: SqliteProjectionStore; 1720 readonly #services: Services; 21+ readonly #history: SqliteHistoryHost; 1822 constructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) { 1923 this.#storage = storage; 2024 this.#namespace = namespace; 2125 this.#services = services; 26+ this.#history = new SqliteHistoryHost(storage, `${namespace}:history`); 2227 this.#projection = new SqliteProjectionStore( Lines 36–102 at 318 (were 31–41 at 160)
34− return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { indexProjectionAtoms: true });
39+ return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { 40+ indexProjectionAtoms: true, 41+ history: this.#history, 3745 return new SqliteWriterState(this.#storage, this.#namespace); 47+ #saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) { 48+ // Receipt payloads can exceed the graph-state value bound. Keep each stored 49+ // piece small without increasing that bound for engine state. 50+ const characters = 64 * 1024; 51+ const digest = createHash("sha256"); 55+ for (const chunk of jsonValueChunks({ result }, { maxDepth: Infinity, unboxPrimitives: true })) { 56+ digest.update(chunk); 57+ length += chunk.length; 59+ while (pending.length >= characters) { 60+ state.write(`runtime:receipt:${id}`, String(parts++), pending.slice(0, characters)); 61+ pending = pending.slice(characters); 64+ if (pending) state.write(`runtime:receipt:${id}`, String(parts++), pending); 65+ state.write("runtime:receipts", id, { 70+ digest: digest.digest("hex"), 74+ state: SqliteWriterState, 76+ receipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string }, 78+ if (receipt.format === 2) return structuredClone(receipt.result) as T; 80+ receipt.format !== 3 || 81+ !Number.isSafeInteger(receipt.parts) || 82+ receipt.parts! < 1 || 83+ !Number.isSafeInteger(receipt.characters) || 84+ receipt.characters! < 1 || 85+ receipt.parts !== Math.ceil(receipt.characters! / (64 * 1024)) 87+ throw Error("invalid receipt header"); 89+ for (let part = 0; part < receipt.parts!; part++) { 90+ const chunk = state.read(`runtime:receipt:${id}`, String(part)); 91+ if (typeof chunk !== "string" || chunk.length !== Math.min(64 * 1024, receipt.characters! - part * 64 * 1024)) 92+ throw Error("incomplete receipt payload"); 95+ if (createHash("sha256").update(json).digest("hex") !== receipt.digest) 96+ throw Error("receipt payload digest mismatch"); 97+ return (JSON.parse(json) as { result: T }).result; 39100 #validate(validate: () => void) { 40101 const result: unknown = validate(); 41102 if (result && (typeof result === "object" || typeof result === "function") && "then" in result) Lines 106–134 at 318 (were 45–63 at 160)
45106 SqliteWriterState.initialize(this.#storage); 46107 const state = this.#state(); 47108 const format = state.read("runtime", "format"); 48− if (format !== undefined && format !== 1) throw Error("unsupported disk-first runtime format");
49− if (format === undefined) state.write("runtime", "format", 1);
109+ if (format !== undefined && format !== 1 && format !== 2 && format !== 3 && format !== 4 && format !== 5) 110+ throw Error("unsupported disk-first runtime format"); 111+ // Format 5 additionally fences indexed insertion runs and lines from older readers. 112+ // Never lower this marker in place. 113+ if (format !== 5) state.write("runtime", "format", 5); 52116 /** Initializes an empty canonical log without replay. Existing history must be adopted. */ 53− initialize<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
118+ operation: (calls: EngineProject) => T, 119+ validate: () => void, 120+ request?: { id: string; identity: unknown }, 54122 return this.#storage.transactionSync(() => { 55123 this.#validate(validate); 56124 const log = new SqliteLog(this.#storage); 57125 if (log.seq() !== 0) throw Error("disk-first initialization requires an empty log"); 126+ if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity"); 58127 const project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() }); 59128 const result = structuredClone(operation(new EngineProject(project))); 60129 this.#validate(validate); 130+ if (request && log.seq() > 0) 131+ this.#saveReceipt(this.#setup(), request.id, requestIdentityDigest(request.identity), result); Lines 146–157 at 318 (were 75–80 at 160)
75146 if (ready !== undefined && ready !== true) throw Error("invalid runtime readiness marker"); 76147 if (ready === true) { 77148 const root = host.root(); 149+ const history = this.#history.prepare(log, root, () => host.root(), validate); 150+ if (!history.ready) { 151+ state.remove("runtime", "history-ready"); 152+ return { ready: false, phase: "history", next: history.next }; 154+ state.write("runtime", "history-ready", true); 78155 const scope = this.#projection.open({ state, log, root }); 80157 this.#validate(validate); Lines 168–174 at 318 (were 91–97 at 160)
91168 from: cursor?.next ?? 0, 92169 digest: cursor?.digest ?? "", 94− maxBytes: 1_048_576,
171+ maxBytes: log.adoptionPageBytes(cursor?.next ?? 0), Lines 185–197 at 318 (were 108–115 at 160)
110187 this.#validate(validate); 111− if (page.ready) state.write("runtime", "ready", true);
112− return { ready: page.ready, phase: page.ready ? "ready" : "projection", next: root.logLength };
188+ if (!page.ready) return { ready: false, phase: "projection", next: root.logLength }; 189+ const history = this.#history.prepare(log, root, () => host.root(), validate); 190+ if (history.ready) { 191+ state.write("runtime", "ready", true); 192+ state.write("runtime", "history-ready", true); 194+ return { ready: history.ready, phase: history.ready ? "ready" : "history", next: history.next }; Lines 200–210 at 318 (were 118–124 at 160)
120202 throw Error("disk-first adoption is not complete"); 121− if (this.#state().read("runtime", "format") !== 1 || this.#state().read("runtime", "ready") !== true)
204+ this.#state().read("runtime", "format") !== 5 || 205+ this.#state().read("runtime", "ready") !== true || 206+ this.#state().read("runtime", "history-ready") !== true 122208 throw Error("disk-first adoption is not complete"); 124210 read<T>(operation: (calls: EngineProject) => T, validate: () => void): T { Lines 229–245 at 318 (were 143–155 at 160)
143229 const host = this.#host(); 145231 if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity"); 146− const identity = request ? canonicalJson(request.identity) : undefined;
232+ const identity = request ? requestIdentityDigest(request.identity) : undefined; 148− const receipt = state.read("runtime:receipts", request.id) as { identity: string; result: T } | undefined;
234+ const receipt = state.read("runtime:receipts", request.id) as 235+ | { format: number; identity: string; result: T } 150− if (receipt.identity !== identity) throw Error("disk-first request identity was reused");
238+ if (receipt.format !== 2 && receipt.format !== 3) throw Error("unsupported disk-first receipt format"); 239+ if (receipt.identity !== identity) 240+ throw Object.assign(Error("disk-first request identity was reused"), { code: "request-reused" }); 151241 this.#validate(validate); 152− return structuredClone(receipt.result);
242+ return this.#receiptResult<T>(state, request.id, receipt); 155245 return host.runCalls({ Lines 249–255 at 318 (were 159–165 at 160)
159249 checkerReady: false, 160250 operation: (calls) => structuredClone(operation(calls)), 161251 commitReceipt: (result) => { 162− if (request) state.write("runtime:receipts", request.id, { identity, result });
252+ if (request) this.#saveReceipt(state, request.id, identity!, result);