Skip to content

abso-core

Public

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

Check passed

Versions 44 to 318

Compare

+257 −0 in 1 place
new file, 257 lines
1+import { createHash } from "node:crypto";
2+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts";
3+import { Project, type WriterSource } from "../../worker/project/project.ts";
4+import type { ProjectOptions } from "../../worker/project/project-types.ts";
5+import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts";
6+import { SqliteHistoryHost } from "./history-host.ts";
7+import { SqliteProjectionStore } from "./projection-store.ts";
8+import { requestIdentityDigest } from "./request-identity-digest.ts";
9+import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts";
11+type Services = Pick<ProjectOptions, "hasBlob" | "whole">;
12+type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "history" | "ready"; next: number };
14+/** One synchronous page or call per invocation. No object retains a loaded Project.
15+ * The owner schedules subsequent pages and supplies fresh authorization for every call. */
16+export class DiskFirstRuntime {
17+ readonly #storage: SqliteStorage;
18+ readonly #namespace: string;
19+ readonly #projection: SqliteProjectionStore;
20+ readonly #services: Services;
21+ readonly #history: SqliteHistoryHost;
22+ constructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {
23+ this.#storage = storage;
24+ this.#namespace = namespace;
25+ this.#services = services;
26+ this.#history = new SqliteHistoryHost(storage, `${namespace}:history`);
27+ this.#projection = new SqliteProjectionStore(
28+ {
29+ database,
30+ namespace: `${namespace}:views`,
31+ registry: `${namespace}:roots`,
32+ defaultFile: "__abso_projection_default__",
33+ },
34+ 1,
35+ { indexedAtoms: true },
36+ );
37+ }
38+ #host() {
39+ return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, {
40+ indexProjectionAtoms: true,
41+ history: this.#history,
42+ });
43+ }
44+ #state() {
45+ return new SqliteWriterState(this.#storage, this.#namespace);
46+ }
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");
52+ let pending = "",
53+ parts = 0,
54+ length = 0;
55+ for (const chunk of jsonValueChunks({ result }, { maxDepth: Infinity, unboxPrimitives: true })) {
56+ digest.update(chunk);
57+ length += chunk.length;
58+ pending += chunk;
59+ while (pending.length >= characters) {
60+ state.write(`runtime:receipt:${id}`, String(parts++), pending.slice(0, characters));
61+ pending = pending.slice(characters);
62+ }
63+ }
64+ if (pending) state.write(`runtime:receipt:${id}`, String(parts++), pending);
65+ state.write("runtime:receipts", id, {
66+ format: 3,
67+ identity,
68+ parts,
69+ characters: length,
70+ digest: digest.digest("hex"),
71+ });
72+ }
73+ #receiptResult<T>(
74+ state: SqliteWriterState,
75+ id: string,
76+ receipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string },
77+ ): T {
78+ if (receipt.format === 2) return structuredClone(receipt.result) as T;
79+ if (
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))
86+ )
87+ throw Error("invalid receipt header");
88+ let json = "";
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");
93+ json += chunk;
94+ }
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;
98+ }
100+ #validate(validate: () => void) {
101+ const result: unknown = validate();
102+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
103+ throw Error("runtime authorization must be synchronous");
104+ }
105+ #setup() {
106+ SqliteWriterState.initialize(this.#storage);
107+ const state = this.#state();
108+ const format = state.read("runtime", "format");
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);
114+ return state;
115+ }
116+ /** Initializes an empty canonical log without replay. Existing history must be adopted. */
117+ initialize<T>(
118+ operation: (calls: EngineProject) => T,
119+ validate: () => void,
120+ request?: { id: string; identity: unknown },
121+ ): T {
122+ return this.#storage.transactionSync(() => {
123+ this.#validate(validate);
124+ const log = new SqliteLog(this.#storage);
125+ 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");
127+ const project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });
128+ const result = structuredClone(operation(new EngineProject(project)));
129+ this.#validate(validate);
130+ if (request && log.seq() > 0)
131+ this.#saveReceipt(this.#setup(), request.id, requestIdentityDigest(request.identity), result);
132+ return result;
133+ });
134+ }
135+ preparePage(validate: () => void): Progress {
136+ return this.#storage.transactionSync(() => {
137+ this.#validate(validate);
138+ const log = new SqliteLog(this.#storage);
139+ if (log.seq() === 0) {
140+ this.#validate(validate);
141+ return { ready: false, phase: "empty", next: 0 };
142+ }
143+ const state = this.#setup();
144+ const host = this.#host();
145+ const ready = state.read("runtime", "ready");
146+ if (ready !== undefined && ready !== true) throw Error("invalid runtime readiness marker");
147+ if (ready === true) {
148+ 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 };
153+ }
154+ state.write("runtime", "history-ready", true);
155+ const scope = this.#projection.open({ state, log, root });
156+ scope.close();
157+ this.#validate(validate);
158+ return { ready: true, phase: "ready", next: root.logLength };
159+ }
160+ const bound = state.read("host", "canonical-root");
161+ if (bound === undefined) {
162+ const cursor = state.read("host", "adoption-root") as
163+ | { source: WriterSource; next: number; digest: string }
164+ | undefined;
165+ const page = host.adoptVerifiedPage(
166+ {
167+ expected: cursor?.source ?? host.source(),
168+ from: cursor?.next ?? 0,
169+ digest: cursor?.digest ?? "",
170+ maxEntries: 32,
171+ maxBytes: log.adoptionPageBytes(cursor?.next ?? 0),
172+ },
173+ validate,
174+ );
175+ this.#validate(validate);
176+ return { ready: false, phase: "writer", next: page.next };
177+ }
178+ const root = host.root();
179+ const page = this.#projection.adopt({
180+ state,
181+ expected: root,
182+ currentRoot: () => host.root(),
183+ maxAtoms: 32,
184+ maxVersions: 1,
185+ maxSteps: 32,
186+ });
187+ this.#validate(validate);
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);
193+ }
194+ return { ready: history.ready, phase: history.ready ? "ready" : "history", next: history.next };
195+ });
196+ }
197+ #requireReady() {
198+ if (
199+ this.#storage.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'").toArray()
200+ .length === 0
201+ )
202+ throw Error("disk-first adoption is not complete");
203+ if (
204+ this.#state().read("runtime", "format") !== 5 ||
205+ this.#state().read("runtime", "ready") !== true ||
206+ this.#state().read("runtime", "history-ready") !== true
207+ )
208+ throw Error("disk-first adoption is not complete");
209+ }
210+ read<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
211+ this.#requireReady();
212+ const host = this.#host();
213+ return host.readCalls({
214+ expected: host.source(),
215+ validateAuthority: validate,
216+ services: this.#services,
217+ operation: (calls) => structuredClone(operation(calls)),
218+ });
219+ }
220+ write<T>(
221+ operation: (calls: EngineProject) => T,
222+ validate: () => void,
223+ request?: { id: string; identity: unknown },
224+ ): T {
225+ return this.#storage.transactionSync(() => {
226+ this.#validate(validate);
227+ this.#requireReady();
228+ const state = this.#state();
229+ const host = this.#host();
230+ host.root();
231+ if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity");
232+ const identity = request ? requestIdentityDigest(request.identity) : undefined;
233+ if (request) {
234+ const receipt = state.read("runtime:receipts", request.id) as
235+ | { format: number; identity: string; result: T }
236+ | undefined;
237+ if (receipt) {
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" });
241+ this.#validate(validate);
242+ return this.#receiptResult<T>(state, request.id, receipt);
243+ }
244+ }
245+ return host.runCalls({
246+ expected: host.source(),
247+ validateAuthority: validate,
248+ services: this.#services,
249+ checkerReady: false,
250+ operation: (calls) => structuredClone(operation(calls)),
251+ commitReceipt: (result) => {
252+ if (request) this.#saveReceipt(state, request.id, identity!, result);
253+ },
254+ });
255+ });
256+ }
257+}
MCP
compare on this site's /mcp
CLI
abso diff 44 318 server/src/disk-first-runtime.ts --json
JSON
/christopher/abso-core/compare/44..318?file=server%2Fsrc%2Fdisk-first-runtime.ts&format=json