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 4 to 318

Compare

+247 −0 in 1 place
new file, 247 lines
1+import { MemoryStore, Project } from "../../worker/project/project.ts";
2+import { withDecodedFrames } from "./decoded-frames.ts";
3+import type { SqliteLog, SqliteStorage } from "./engine-project.ts";
4+import { SqliteHistoryState } from "./history-state.ts";
5+import type { WriterProjectionSession } from "./writer-host.ts";
6+import { SqliteWriterState, type WriterRoot, writerFrameChunksDigest } from "./writer-host.ts";
7+
8+type Cursor = { root: WriterRoot; next: number; digest: string };
9+const same = (a: WriterRoot, b: WriterRoot) =>
10+ a.format === b.format &&
11+ a.generation === b.generation &&
12+ a.logLength === b.logLength &&
13+ a.sharedVersion === b.sharedVersion &&
14+ a.digest === b.digest;
16+/** Derived historical state, bound to the host's exact canonical root. */
17+export class SqliteHistoryHost {
18+ readonly #storage: SqliteStorage;
19+ readonly #namespace: string;
20+ readonly #meta: SqliteWriterState;
21+ constructor(storage: SqliteStorage, namespace: string) {
22+ if (!namespace || namespace.length > 80) throw Error("invalid historical host namespace");
23+ this.#storage = storage;
24+ this.#namespace = namespace;
25+ this.#meta = new SqliteWriterState(storage, `${namespace}:control`);
26+ }
27+ #validate(root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) {
28+ const result: unknown = authority();
29+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
30+ throw Error("historical authority must be synchronous");
31+ if (!same(root, currentRoot())) throw Error("historical canonical root changed");
32+ }
33+ #beginReset() {
34+ this.#meta.remove("history", "cursor");
35+ this.#meta.remove("history", "verification");
36+ this.#meta.write("history", "reset", true);
37+ return { ready: false, next: 0 };
38+ }
39+ #resetPage() {
40+ const sql = this.#storage.sql;
41+ const clauses: [string, string, (string | number)[]][] = [
42+ ["writer_state", "namespace = ?", [this.#namespace]],
43+ [
44+ "writer_state",
45+ "namespace >= ? AND namespace < ?",
46+ [`${this.#namespace}:history:`, `${this.#namespace}:history;`],
47+ ],
48+ ["writer_history_keys", "namespace = ?", [this.#namespace]],
49+ ["writer_history_heads", "namespace = ?", [this.#namespace]],
50+ ];
51+ for (const [table, condition, bindings] of clauses) {
52+ const rows = sql.exec(`SELECT rowid AS id FROM ${table} WHERE ${condition} LIMIT 256`, ...bindings).toArray() as {
53+ id: number;
54+ }[];
55+ if (!rows.length) continue;
56+ sql.exec(`DELETE FROM ${table} WHERE rowid IN (${rows.map(() => "?").join(",")})`, ...rows.map((row) => row.id));
57+ return { ready: false, next: 0 };
58+ }
59+ this.#meta.remove("history", "reset");
60+ return { ready: false, next: 0 };
61+ }
63+ prepare(log: SqliteLog, root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) {
64+ return this.#storage.transactionSync(() => {
65+ this.#validate(root, currentRoot, authority);
66+ SqliteHistoryState.initialize(this.#storage);
67+ if (this.#meta.read("history", "reset") === true) {
68+ const result = this.#resetPage();
69+ this.#validate(root, currentRoot, authority);
70+ return result;
71+ }
72+ let cursor = this.#meta.read("history", "cursor") as Cursor | undefined;
73+ if (cursor && !same(cursor.root, root)) {
74+ if (cursor.next > root.logLength) return this.#beginReset();
75+ const saved = this.#meta.read("history", "verification") as Cursor | undefined;
76+ const verification = saved && same(saved.root, root) ? saved : { root, next: 0, digest: "" };
77+ const budget = log.adoptionPageBytes(verification.next);
78+ let bytes = 0,
79+ count = 0;
80+ while (verification.next < cursor.next && count < 32) {
81+ const size = log.frameBytes(verification.next);
82+ if (bytes && size > budget - bytes) break;
83+ verification.digest = writerFrameChunksDigest(
84+ verification.digest,
85+ verification.next,
86+ log.frameChunks(verification.next),
87+ );
88+ verification.next++;
89+ bytes += size;
90+ count++;
91+ }
92+ this.#validate(root, currentRoot, authority);
93+ if (verification.next < cursor.next) {
94+ this.#meta.write("history", "verification", verification);
95+ return { ready: false, next: cursor.next };
96+ }
97+ if (verification.digest !== cursor.digest) return this.#beginReset();
98+ cursor = { ...cursor, root };
99+ this.#meta.write("history", "cursor", cursor);
100+ this.#meta.remove("history", "verification");
101+ }
102+ if (cursor?.next === root.logLength) return { ready: true, next: cursor.next };
103+ const from = cursor?.next ?? 0;
104+ const state = new SqliteHistoryState(this.#storage, this.#namespace, from);
105+ let digest = cursor?.digest ?? "";
106+ const budget = log.adoptionPageBytes(from);
107+ const decoded = withDecodedFrames(
108+ this.#storage,
109+ `${this.#namespace}:decoded`,
110+ log,
111+ { from, to: root.logLength, maxEntries: 32, maxBytes: budget, digest },
112+ (frames) => {
113+ const page =
114+ from > 0
115+ ? (() => {
116+ const extended = Project.extendHistoricalPage(state, {
117+ from,
118+ frames,
119+ maxEntries: 32,
120+ maxBytes: budget,
121+ decodedFrames: true,
122+ beginRevision: (revision) => state.beginRevision(revision),
123+ validateAuthority: () => this.#validate(root, currentRoot, authority),
124+ });
125+ return { ...extended, ready: extended.next === root.logLength };
126+ })()
127+ : Project.adoptWriterPage(state, {
128+ source: root,
129+ from,
130+ frames,
131+ maxEntries: 32,
132+ maxBytes: budget,
133+ decodedFrames: true,
134+ currentSource: () => currentRoot(),
135+ beginRevision: (revision) => state.beginRevision(revision),
136+ });
137+ return page;
138+ },
139+ );
140+ const page = decoded.result;
141+ digest = decoded.digest;
142+ if (page.ready && digest !== root.digest) throw Error("historical canonical digest mismatch");
143+ this.#validate(root, currentRoot, authority);
144+ state.seal();
145+ this.#meta.write("history", "cursor", { root, next: page.next, digest } satisfies Cursor);
146+ return { ready: page.ready, next: page.next };
147+ });
148+ }
149+ /** Called inside the canonical writer transaction, before its receipt commits. */
150+ advance(
151+ log: SqliteLog,
152+ previous: WriterRoot,
153+ committed: WriterRoot,
154+ currentRoot: () => WriterRoot,
155+ authority: () => void,
156+ ): void {
157+ this.#storage.transactionSync(() => {
158+ const validate = () => this.#validate(committed, currentRoot, authority);
159+ validate();
160+ const cursor = this.#meta.read("history", "cursor") as Cursor | undefined;
161+ if (
162+ !cursor ||
163+ !same(cursor.root, previous) ||
164+ cursor.next !== previous.logLength ||
165+ cursor.digest !== previous.digest
166+ )
167+ throw Error("historical committed prefix is stale");
168+ if (committed.logLength < previous.logLength || committed.generation < previous.generation)
169+ throw Error("historical root cannot move backwards");
170+ let from = previous.logLength,
171+ digest = previous.digest;
172+ while (from < committed.logLength) {
173+ const budget = log.adoptionPageBytes(from);
174+ const state = new SqliteHistoryState(this.#storage, this.#namespace, from);
175+ const decoded = withDecodedFrames(
176+ this.#storage,
177+ `${this.#namespace}:decoded`,
178+ log,
179+ { from, to: committed.logLength, maxEntries: 32, maxBytes: budget, digest },
180+ (frames) => {
181+ const page = Project.extendHistoricalPage(state, {
182+ from,
183+ frames,
184+ maxEntries: 32,
185+ maxBytes: budget,
186+ decodedFrames: true,
187+ beginRevision: (revision) => state.beginRevision(revision),
188+ validateAuthority: validate,
189+ });
190+ return page;
191+ },
192+ );
193+ const page = decoded.result;
194+ digest = decoded.digest;
195+ state.seal();
196+ from = page.next;
197+ }
198+ if (digest !== committed.digest) throw Error("historical canonical tail digest mismatch");
199+ validate();
200+ this.#meta.write("history", "cursor", { root: committed, next: from, digest } satisfies Cursor);
201+ });
202+ }
203+ read<T>(
204+ root: WriterRoot,
205+ currentRoot: () => WriterRoot,
206+ authority: () => void,
207+ at: number,
208+ operation: (project: Project) => T,
209+ viewProvider?: WriterProjectionSession["historicalReadViewProvider"],
210+ ): T {
211+ return this.#storage.transactionSync(() => {
212+ let active = true;
213+ const assertScope = () => {
214+ if (!active) throw Error("historical scope ended");
215+ };
216+ const validate = () => {
217+ assertScope();
218+ this.#validate(root, currentRoot, authority);
219+ };
220+ try {
221+ validate();
222+ const cursor = this.#meta.read("history", "cursor") as Cursor | undefined;
223+ if (!cursor || !same(cursor.root, root) || cursor.next !== root.logLength || cursor.digest !== root.digest)
224+ throw Error("historical state is not ready for canonical root");
225+ if (!Number.isSafeInteger(at) || at < 0 || at > root.logLength)
226+ throw Error("historical position outside authority");
227+ const state = new SqliteHistoryState(this.#storage, this.#namespace, root.logLength);
228+ const historical = state.at(at, assertScope);
229+ const project =
230+ at === 0
231+ ? new Project(new MemoryStore())
232+ : Project.openHistorical(
233+ historical,
234+ at,
235+ new SqliteWriterState(this.#storage, `${this.#namespace}:scratch`),
236+ assertScope,
237+ viewProvider?.(historical),
238+ );
239+ const result = structuredClone(operation(project));
240+ validate();
241+ return result;
242+ } finally {
243+ active = false;
244+ }
245+ });
246+ }
247+}
MCP
compare on this site's /mcp
CLI
abso diff 4 318 server/src/history-host.ts --json
JSON
/christopher/abso-core/compare/4..318?file=server%2Fsrc%2Fhistory-host.ts&format=json