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
show on this site's /mcp
CLI
abso show 165 --json
JSON
/christopher/abso-core/versions/165?format=json

Stream projection atom hashing and comparison and reduce locator writes

of shared·codex-capacity-chair··Not checked

Version 164 · Files at version 165

8 files, 216 lines added, 38 removed.

--- a/src/engine/experimental/projection-atom-index.ts
+++ b/src/engine/experimental/projection-atom-index.ts
@@ -1,4 +1,5 @@
11import { createHash } from "node:crypto";
2+import { jsonValueChunks } from "../json-value-chunks.ts";
23import type { GraphStateStorage } from "../state-source.ts";
34import type { Atom, AttrSet, Relocation } from "../types.ts";
45
@@ -173,6 +174,8 @@
173174
174175/** Opt-in persistent Graph callback: indexes the just-accepted canonical atom. */
175176export function indexAcceptedProjectionAtom(atom: Atom, files: readonly string[], storage: GraphStateStorage): void {
176− const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex");
177+ const hash = createHash("sha256");
178+ for (const chunk of jsonValueChunks(atom)) hash.update(chunk);
179+ const digest = hash.digest("hex");
177180 new ProjectionAtomIndex(storage).put(atom, digest, files);
178181}
--- a/src/engine/experimental/projection-locator.ts
+++ b/src/engine/experimental/projection-locator.ts
@@ -55,14 +55,6 @@
5555 if (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error("invalid locator child");
5656 return row as unknown as Branch;
5757 }
58− #write(node: Node): number {
59− const next = this.#storage.read(this.#collection, "next") ?? 0;
60− if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid locator allocation");
61− if (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error("locator allocation collision");
62− this.#storage.write(this.#collection, String(next), node);
63− this.#storage.write(this.#collection, "next", next + 1);
64− return next;
65− }
6658 /** Update each touched branch once, retaining at most 256 decoded values. */
6759 setMany(root: Page, values: ReadonlyArray<readonly [number, T]>): Page {
6860 page(root);
@@ -149,31 +141,8 @@
149141 }
150142
151143 set(root: Page, id: number, value: T): number {
152− page(root);
153− const key = keyOf(id),
154− checked = structuredClone(this.#decode(structuredClone(value)));
155− return this.#storage.transaction(() => {
156− const visit = (current: Page, parent?: string, digit?: string, depth = 0): number => {
157− if (depth > 8) throw Error("invalid locator depth");
158− if (current === null) return this.#write({ format: 1, kind: "leaf", prefix: key, value: checked });
159− const node = this.#read(current, parent, digit);
160− let common = 0;
161− while (common < node.prefix.length && node.prefix[common] === key[common]) common++;
162− if (common < node.prefix.length) {
163− const leaf = this.#write({ format: 1, kind: "leaf", prefix: key, value: checked });
164− return this.#write({
165− format: 1,
166− kind: "branch",
167− prefix: key.slice(0, common),
168− children: { [node.prefix[common]!]: current, [key[common]!]: leaf },
169− });
170− }
171− if (node.kind === "leaf") return this.#write({ format: 1, kind: "leaf", prefix: key, value: checked });
172− const nextDigit = key[common]!;
173− const child = visit(node.children[nextDigit] ?? null, node.prefix, nextDigit, depth + 1);
174− return this.#write({ ...node, children: { ...node.children, [nextDigit]: child } });
175− };
176− return visit(root);
177− });
144+ // A nonempty batch always produces a root. Share its single allocation-counter
145+ // commit instead of rewriting that counter for every copied path node.
146+ return this.setMany(root, [[id, value]])!;
178147 }
179148}
--- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -1,4 +1,5 @@
11import type { Graph } from "../graph.ts";
2+import { equalJsonValues } from "../json-value-chunks.ts";
23import { orderedChildKey } from "../ordered-index.ts";
34import { resolveScratchMoves } from "../relocation-scratch.ts";
45import type { GraphStateStorage } from "../state-source.ts";
@@ -112,7 +113,7 @@
112113 }
113114 apply(previous: MarkerState, atom: Atom): MarkerState {
114115 this.assertContext(previous);
115− if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch");
116+ if (!equalJsonValues(this.graph.atom(atom.id), atom)) throw Error("canonical atom mismatch");
116117 if (this.members.get(previous.membership, atom.seq)?.present) return previous;
117118 for (const id of atom.deps)
118119 if (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error("missing dependency");
@@ -187,7 +188,7 @@
187188 }
188189 removeAtom(previous: MarkerState, atom: Atom): MarkerState {
189190 this.assertContext(previous);
190− if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch");
191+ if (!equalJsonValues(this.graph.atom(atom.id), atom)) throw Error("canonical atom mismatch");
191192 if (!this.members.get(previous.membership, atom.seq)?.present) return previous;
192193 if (required(this.members.get(previous.membership, atom.seq)).dependents)
193194 throw Error("included dependent prevents removal");
--- /dev/null
+++ b/src/engine/json-value-chunks.ts
@@ -0,0 +1,94 @@
1+/** JSON.stringify-compatible chunks for canonical data, without a whole-value string.
2+ * Individual input strings and object key lists still belong to the caller.
3+ */
4+export function* jsonValueChunks(input: unknown): IterableIterator<string> {
5+ const active = new Set<object>();
6+ function* string(value: string): IterableIterator<string> {
7+ yield '"';
8+ for (let from = 0; from < value.length; ) {
9+ let end = Math.min(from + 16384, value.length);
10+ const last = value.charCodeAt(end - 1),
11+ next = value.charCodeAt(end);
12+ if (last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end--;
13+ yield JSON.stringify(value.slice(from, end)).slice(1, -1);
14+ from = end;
15+ }
16+ yield '"';
17+ }
18+ const normalize = (value: unknown, key: string): unknown => {
19+ if (value !== null && typeof value === "object") {
20+ const toJSON = (value as { toJSON?: unknown }).toJSON;
21+ if (typeof toJSON === "function") return toJSON.call(value, key);
22+ }
23+ return value;
24+ };
25+ const omitted = (value: unknown) => value === undefined || typeof value === "function" || typeof value === "symbol";
26+ function* encode(value: unknown): IterableIterator<string> {
27+ if (typeof value === "string") yield* string(value);
28+ else if (value === null || typeof value === "boolean" || typeof value === "number") yield JSON.stringify(value);
29+ else if (typeof value !== "object" || value === null) throw Error("unsupported canonical JSON value");
30+ else {
31+ if (active.has(value)) throw Error("cyclic canonical JSON value");
32+ if (active.size >= 128) throw Error("canonical JSON depth exceeds bound");
33+ active.add(value);
34+ try {
35+ if (Array.isArray(value)) {
36+ yield "[";
37+ const length = value.length;
38+ for (let i = 0; i < length; i++) {
39+ if (i) yield ",";
40+ const child = normalize(value[i], String(i));
41+ yield* encode(omitted(child) ? null : child);
42+ }
43+ yield "]";
44+ } else {
45+ yield "{";
46+ let first = true;
47+ for (const key of Object.keys(value)) {
48+ const child = normalize((value as Record<string, unknown>)[key], key);
49+ if (omitted(child)) continue;
50+ if (!first) yield ",";
51+ first = false;
52+ yield* string(key);
53+ yield ":";
54+ yield* encode(child);
55+ }
56+ yield "}";
57+ }
58+ } finally {
59+ active.delete(value);
60+ }
61+ }
62+ }
63+ yield* encode(normalize(input, ""));
64+}
66+/** Exact serialized-content equality, retaining only the current pair of chunks. */
67+export function equalJsonValues(left: unknown, right: unknown): boolean {
68+ const a = jsonValueChunks(left),
69+ b = jsonValueChunks(right);
70+ let x = a.next(),
71+ y = b.next(),
72+ i = 0,
73+ j = 0;
74+ try {
75+ for (;;) {
76+ while (!x.done && i === x.value.length) {
77+ x = a.next();
78+ i = 0;
79+ }
80+ while (!y.done && j === y.value.length) {
81+ y = b.next();
82+ j = 0;
83+ }
84+ if (x.done || y.done) return x.done === y.done;
85+ const length = Math.min(x.value.length - i, y.value.length - j);
86+ if (x.value.slice(i, i + length) !== y.value.slice(j, j + length)) return false;
87+ i += length;
88+ j += length;
89+ }
90+ } finally {
91+ a.return?.();
92+ b.return?.();
93+ }
94+}
--- /dev/null
+++ b/src/engine/test/json-value-chunks.test.ts
@@ -0,0 +1,66 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { test } from "node:test";
4+import { equalJsonValues, jsonValueChunks } from "../json-value-chunks.ts";
5+
6+test("canonical JSON chunks preserve scalar, container and toJSON encoding", () => {
7+ const values = [
8+ null,
9+ true,
10+ false,
11+ 0,
12+ -0,
13+ 1.25,
14+ NaN,
15+ Infinity,
16+ { z: undefined, a: [undefined, null, 'quoted"\n\t\\', "\ud800", "\udc00", "\u2028\u2029"] },
17+ new Array(3),
18+ { 20: "twenty", 2: "two", before: 1, after: 2 },
19+ {
20+ nested: {
21+ toJSON(key: string) {
22+ return { key, value: "converted" };
23+ },
24+ },
25+ },
26+ JSON.parse('{"__proto__":"data","constructor":"also data"}'),
27+ ];
28+ for (const value of values) assert.equal([...jsonValueChunks(value)].join(""), JSON.stringify(value));
29+ for (const left of values)
30+ for (const right of values)
31+ assert.equal(equalJsonValues(left, right), JSON.stringify(left) === JSON.stringify(right));
32+});
34+test("canonical JSON string chunks preserve every surrogate split and bound escaped output", () => {
35+ for (const offset of [16382, 16383, 16384, 16385]) {
36+ const value = { text: `${"a".repeat(offset)}\ud83d\ude80${"\u0000".repeat(40000)}\ud800` };
37+ const hash = createHash("sha256");
38+ for (const chunk of jsonValueChunks(value)) {
39+ assert.ok(chunk.length <= 16384 * 6);
40+ hash.update(chunk);
41+ }
42+ assert.equal(hash.digest("hex"), createHash("sha256").update(JSON.stringify(value)).digest("hex"));
43+ }
44+});
46+test("canonical JSON visits large arrays incrementally and rejects cycles", () => {
47+ let reads = 0;
48+ const values = new Proxy(new Array(10000), {
49+ get(target, key, receiver) {
50+ if (typeof key === "string" && /^[0-9]+$/.test(key)) {
51+ reads++;
52+ return Number(key);
53+ }
54+ return Reflect.get(target, key, receiver);
55+ },
56+ });
57+ const chunks = jsonValueChunks(values);
58+ assert.equal(chunks.next().value, "[");
59+ assert.equal(reads, 0);
60+ assert.equal(chunks.next().value, "0");
61+ assert.equal(reads, 1);
62+ chunks.return?.();
63+ const cyclic: unknown[] = [];
64+ cyclic.push(cyclic);
65+ assert.throws(() => [...jsonValueChunks(cyclic)], /cyclic/);
66+});
--- a/src/engine/test/projection-atom-index.test.ts
+++ b/src/engine/test/projection-atom-index.test.ts
@@ -11,6 +11,21 @@
1111import { Repo } from "./helpers.ts";
1212import { SqlState } from "./storage-helper.ts";
1313
14+test("accepted atom indexing preserves the original digest without serializing the whole atom", (t) => {
15+ const db = new SqlState();
16+ t.after(() => db.db.close());
17+ const repo = Repo.init({ "a.txt": `${"x".repeat(16383)}\ud83d\ude80\n${"\u0000".repeat(20000)}\n` });
18+ const atom = repo.graph.atom("a0");
19+ const expected = createHash("sha256").update(JSON.stringify(atom)).digest("hex");
20+ const stringify = JSON.stringify;
21+ t.mock.method(JSON, "stringify", (...args: Parameters<typeof JSON.stringify>) => {
22+ assert.notEqual(args[0], atom, "indexing must not rematerialize the full atom JSON");
23+ return stringify(...args);
24+ });
25+ indexAcceptedProjectionAtom(atom, ["a.txt"], db);
26+ assert.equal(new ProjectionAtomIndex(db).openAccepted("a0").digest, expected);
27+});
1429test("projection atom descriptors exclude inserted text and read one indexed item", () => {
1530 const db = new SqlState();
1631 try {
--- a/src/engine/test/projection-locator.test.ts
+++ b/src/engine/test/projection-locator.test.ts
@@ -114,6 +114,7 @@
114114 let seed = 12345;
115115 const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);
116116 const keys = [0, 0xffffffff, 1, 16, 255, 256, ...Array.from({ length: 60 }, random)];
117+ const expected = new Map<number, number>();
117118 for (let round = 0; round < 8; round++) {
118119 const edits: [number, number][] = Array.from({ length: 64 }, (_, i) => [
119120 keys[random() % keys.length]!,
@@ -122,8 +123,15 @@
122123 const prior: number | null = left;
123124 const oldEntries: (readonly [number, number])[] = [...batched.entries(prior)];
124125 left = batched.setMany(left, edits);
125− for (const [key, value] of edits) right = sequential.set(right, key, value);
126+ for (const [key, value] of edits) {
127+ right = sequential.set(right, key, value);
128+ expected.set(key, value);
129+ }
126130 assert.deepEqual([...batched.entries(left)], [...sequential.entries(right)]);
131+ assert.deepEqual(
132+ [...batched.entries(left)],
133+ [...expected].sort(([a], [b]) => a - b),
134+ );
127135 assert.deepEqual([...batched.entries(prior)], oldEntries);
128136 }
129137 } finally {
--- a/src/engine/test/projection-marker.test.ts
+++ b/src/engine/test/projection-marker.test.ts
@@ -6,6 +6,28 @@
66import { Repo } from "./helpers.ts";
77import { SqlState } from "./storage-helper.ts";
88
9+test("projection apply and removal compare atom contents without whole-atom JSON", (t) => {
10+ const storage = new SqlState();
11+ t.after(() => storage.db.close());
12+ const repo = Repo.init({ "f.txt": `${"x".repeat(40000)}\n` });
13+ const atom = repo.graph.atom("a0");
14+ const projection = new MarkerProjection(storage, repo.graph, "f.txt", "streamed-comparison");
15+ const stringify = JSON.stringify;
16+ t.mock.method(JSON, "stringify", (...args: Parameters<typeof JSON.stringify>) => {
17+ assert.notEqual(args[0], atom, "projection validation must not serialize the full atom");
18+ return stringify(...args);
19+ });
20+ const state = projection.apply(projection.empty(), atom);
21+ const before = storage.writes;
22+ const altered = { ...atom, message: "forged" };
23+ assert.throws(() => projection.apply(state, altered), /canonical atom mismatch/);
24+ assert.throws(() => projection.removeAtom(state, altered), /canonical atom mismatch/);
25+ assert.equal(storage.writes, before);
26+ const removed = projection.removeAtom(state, atom);
27+ assert.deepEqual(projection.lines(removed, "f.txt"), []);
28+ assert.equal(projection.lines(state, "f.txt").length, 1);
29+});
931test("typed marker projection matches mixed multi-file edits and reverse removals", () => {
1032 const db = new SqlState();
1133 try {