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
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/server/src/disk-first-runtime.ts?version=162&format=json
251 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 162, 2 versions changed it

You're reading version 162. The newest is 318, and 1 version since then changed this file. Go to the newestCompare with 318

1import { createHash } from "node:crypto";
2import { canonicalJson } from "../../worker/project/operation-protocol.ts";
3import { Project, type WriterSource } from "../../worker/project/project.ts";
4import type { ProjectOptions } from "../../worker/project/project-types.ts";
5import { EngineProject, SqliteLog, type SqliteStorage } from "./engine-project.ts";
6import { SqliteHistoryHost } from "./history-host.ts";
7import { SqliteProjectionStore } from "./projection-store.ts";
8import { SqliteWriterHost, SqliteWriterState } from "./writer-host.ts";
9
10type Services = Pick<ProjectOptions, "hasBlob" | "whole">;
11type Progress = { ready: boolean; phase: "empty" | "writer" | "projection" | "history" | "ready"; next: number };
13/** One synchronous page or call per invocation. No object retains a loaded Project.
14 * The owner schedules subsequent pages and supplies fresh authorization for every call. */
15export class DiskFirstRuntime {
16 readonly #storage: SqliteStorage;
17 readonly #namespace: string;
18 readonly #projection: SqliteProjectionStore;
19 readonly #services: Services;
20 readonly #history: SqliteHistoryHost;
21 constructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {
22 this.#storage = storage;
23 this.#namespace = namespace;
24 this.#services = services;
25 this.#history = new SqliteHistoryHost(storage, `${namespace}:history`);
26 this.#projection = new SqliteProjectionStore(
27 {
28 database,
29 namespace: `${namespace}:views`,
30 registry: `${namespace}:roots`,
31 defaultFile: "__abso_projection_default__",
32 },
33 1,
34 { indexedAtoms: true },
35 );
36 }
37 #host() {
38 return new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, {
39 indexProjectionAtoms: true,
40 history: this.#history,
41 });
42 }
43 #state() {
44 return new SqliteWriterState(this.#storage, this.#namespace);
45 }
46 #saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) {
47 // Receipt payloads can exceed the graph-state value bound. Keep each stored
48 // piece small without increasing that bound for engine state.
49 const json = JSON.stringify({ result });
50 const characters = 64 * 1024;
51 const parts = Math.ceil(json.length / characters);
52 for (let part = 0; part < parts; part++)
53 state.write(`runtime:receipt:${id}`, String(part), json.slice(part * characters, (part + 1) * characters));
54 state.write("runtime:receipts", id, {
55 format: 3,
56 identity,
57 parts,
58 characters: json.length,
59 digest: createHash("sha256").update(json).digest("hex"),
60 });
61 }
62 #receiptResult<T>(
63 state: SqliteWriterState,
64 id: string,
65 receipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string },
66 ): T {
67 if (receipt.format === 2) return structuredClone(receipt.result) as T;
68 if (
69 receipt.format !== 3 ||
70 !Number.isSafeInteger(receipt.parts) ||
71 receipt.parts! < 1 ||
72 !Number.isSafeInteger(receipt.characters) ||
73 receipt.characters! < 1 ||
74 receipt.parts !== Math.ceil(receipt.characters! / (64 * 1024))
75 )
76 throw Error("invalid receipt header");
77 let json = "";
78 for (let part = 0; part < receipt.parts!; part++) {
79 const chunk = state.read(`runtime:receipt:${id}`, String(part));
80 if (typeof chunk !== "string" || chunk.length !== Math.min(64 * 1024, receipt.characters! - part * 64 * 1024))
81 throw Error("incomplete receipt payload");
82 json += chunk;
83 }
84 if (createHash("sha256").update(json).digest("hex") !== receipt.digest)
85 throw Error("receipt payload digest mismatch");
86 return (JSON.parse(json) as { result: T }).result;
87 }
89 #validate(validate: () => void) {
90 const result: unknown = validate();
91 if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
92 throw Error("runtime authorization must be synchronous");
93 }
94 #setup() {
95 SqliteWriterState.initialize(this.#storage);
96 const state = this.#state();
97 const format = state.read("runtime", "format");
98 if (format !== undefined && format !== 1 && format !== 2 && format !== 3 && format !== 4 && format !== 5)
99 throw Error("unsupported disk-first runtime format");
100 // Format 5 additionally fences indexed insertion runs and lines from older readers.
101 // Never lower this marker in place.
102 if (format !== 5) state.write("runtime", "format", 5);
103 return state;
104 }
105 /** Initializes an empty canonical log without replay. Existing history must be adopted. */
106 initialize<T>(
107 operation: (calls: EngineProject) => T,
108 validate: () => void,
109 request?: { id: string; identity: unknown },
110 ): T {
111 return this.#storage.transactionSync(() => {
112 this.#validate(validate);
113 const log = new SqliteLog(this.#storage);
114 if (log.seq() !== 0) throw Error("disk-first initialization requires an empty log");
115 if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity");
116 const project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });
117 const result = structuredClone(operation(new EngineProject(project)));
118 this.#validate(validate);
119 if (request && log.seq() > 0)
120 this.#saveReceipt(
121 this.#setup(),
122 request.id,
123 createHash("sha256").update(canonicalJson(request.identity)).digest("hex"),
124 result,
125 );
126 return result;
127 });
128 }
129 preparePage(validate: () => void): Progress {
130 return this.#storage.transactionSync(() => {
131 this.#validate(validate);
132 const log = new SqliteLog(this.#storage);
133 if (log.seq() === 0) {
134 this.#validate(validate);
135 return { ready: false, phase: "empty", next: 0 };
136 }
137 const state = this.#setup();
138 const host = this.#host();
139 const ready = state.read("runtime", "ready");
140 if (ready !== undefined && ready !== true) throw Error("invalid runtime readiness marker");
141 if (ready === true) {
142 const root = host.root();
143 const history = this.#history.prepare(log, root, () => host.root(), validate);
144 if (!history.ready) {
145 state.remove("runtime", "history-ready");
146 return { ready: false, phase: "history", next: history.next };
147 }
148 state.write("runtime", "history-ready", true);
149 const scope = this.#projection.open({ state, log, root });
150 scope.close();
151 this.#validate(validate);
152 return { ready: true, phase: "ready", next: root.logLength };
153 }
154 const bound = state.read("host", "canonical-root");
155 if (bound === undefined) {
156 const cursor = state.read("host", "adoption-root") as
157 | { source: WriterSource; next: number; digest: string }
158 | undefined;
159 const page = host.adoptVerifiedPage(
160 {
161 expected: cursor?.source ?? host.source(),
162 from: cursor?.next ?? 0,
163 digest: cursor?.digest ?? "",
164 maxEntries: 32,
165 maxBytes: log.adoptionPageBytes(cursor?.next ?? 0),
166 },
167 validate,
168 );
169 this.#validate(validate);
170 return { ready: false, phase: "writer", next: page.next };
171 }
172 const root = host.root();
173 const page = this.#projection.adopt({
174 state,
175 expected: root,
176 currentRoot: () => host.root(),
177 maxAtoms: 32,
178 maxVersions: 1,
179 maxSteps: 32,
180 });
181 this.#validate(validate);
182 if (!page.ready) return { ready: false, phase: "projection", next: root.logLength };
183 const history = this.#history.prepare(log, root, () => host.root(), validate);
184 if (history.ready) {
185 state.write("runtime", "ready", true);
186 state.write("runtime", "history-ready", true);
187 }
188 return { ready: history.ready, phase: history.ready ? "ready" : "history", next: history.next };
189 });
190 }
191 #requireReady() {
192 if (
193 this.#storage.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'").toArray()
194 .length === 0
195 )
196 throw Error("disk-first adoption is not complete");
197 if (
198 this.#state().read("runtime", "format") !== 5 ||
199 this.#state().read("runtime", "ready") !== true ||
200 this.#state().read("runtime", "history-ready") !== true
201 )
202 throw Error("disk-first adoption is not complete");
203 }
204 read<T>(operation: (calls: EngineProject) => T, validate: () => void): T {
205 this.#requireReady();
206 const host = this.#host();
207 return host.readCalls({
208 expected: host.source(),
209 validateAuthority: validate,
210 services: this.#services,
211 operation: (calls) => structuredClone(operation(calls)),
212 });
213 }
214 write<T>(
215 operation: (calls: EngineProject) => T,
216 validate: () => void,
217 request?: { id: string; identity: unknown },
218 ): T {
219 return this.#storage.transactionSync(() => {
220 this.#validate(validate);
221 this.#requireReady();
222 const state = this.#state();
223 const host = this.#host();
224 host.root();
225 if (request && (!request.id || request.id.length > 128)) throw Error("invalid disk-first request identity");
226 const identity = request ? createHash("sha256").update(canonicalJson(request.identity)).digest("hex") : undefined;
227 if (request) {
228 const receipt = state.read("runtime:receipts", request.id) as
229 | { format: number; identity: string; result: T }
230 | undefined;
231 if (receipt) {
232 if (receipt.format !== 2 && receipt.format !== 3) throw Error("unsupported disk-first receipt format");
233 if (receipt.identity !== identity)
234 throw Object.assign(Error("disk-first request identity was reused"), { code: "request-reused" });
235 this.#validate(validate);
236 return this.#receiptResult<T>(state, request.id, receipt);
237 }
238 }
239 return host.runCalls({
240 expected: host.source(),
241 validateAuthority: validate,
242 services: this.#services,
243 checkerReady: false,
244 operation: (calls) => structuredClone(operation(calls)),
245 commitReceipt: (result) => {
246 if (request) this.#saveReceipt(state, request.id, identity!, result);
247 },
248 });
249 });
250 }