Fix disk-backed historical paths, empty queues and canonical frame integrity
of shared·codex-capacity-chair··Not checked
Version 163 · Files at version 164
11 files, 167 lines added, 11 removed.
--- a/server/src/decoded-frames.ts
+++ b/server/src/decoded-frames.ts
@@ -49,7 +49,7 @@
5050 yield { seq, bytes: size, entry: smallFrameJson(log.frameChunks(seq)) as Entry }; 52− storeJson(state, String(seq), log.frameChunks(seq));
52+ storeJson(state, String(seq), log.frameChunks(seq), { finiteNumbers: true }); 5353 yield { seq, bytes: size, entry: storedJsonView(new StoredJson(reads, String(seq))) as Entry }; --- a/server/src/json-events.ts
+++ b/server/src/json-events.ts
@@ -6,7 +6,10 @@
66 | { kind: "value"; value: number | boolean | null }; 88/** Structural JSON decoding. Retains nesting and one bounded string fragment, not a decoded tree. */ 9−export function* jsonEvents(chunks: Iterable<string>): IterableIterator<JsonEvent> {
9+export function* jsonEvents( 10+ chunks: Iterable<string>, 11+ options: { finiteNumbers?: boolean } = {}, 12+): IterableIterator<JsonEvent> { 1013 const cursor = new JsonChunkCursor(chunks); 1114 const whitespace = () => { 1215 while (cursor.peek() !== undefined && /[ \t\n\r]/.test(cursor.peek()!)) cursor.take(); @@ -61,7 +64,9 @@
6164 yield { kind: "value", value: token === "null" ? null : token === "true" }; 6366 if (!/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw Error("invalid JSON scalar"); 64− yield { kind: "value", value: Number(token) };
67+ const number = Number(token); 68+ if (options.finiteNumbers && !Number.isFinite(number)) throw Error("non-finite JSON number"); 69+ yield { kind: "value", value: number }; --- a/server/src/small-frame-json.ts
+++ b/server/src/small-frame-json.ts
@@ -10,6 +10,13 @@
1010 // Count UTF-8 after joining so a surrogate pair split across chunks counts once. 1111 if (new TextEncoder().encode(text).byteLength > 4096) throw Error("small canonical frame exceeds bound"); 1212 // Preserve depth, key and scalar limits; the fast path must not change acceptance. 13− for (const event of jsonEvents([text])) void event;
14− return JSON.parse(text);
13+ for (const event of jsonEvents([text], { finiteNumbers: true })) void event; 14+ const freeze = (value: unknown): unknown => { 15+ if (value !== null && typeof value === "object") { 16+ for (const child of Object.values(value)) freeze(child); 17+ Object.freeze(value); 21+ return freeze(JSON.parse(text)); --- a/server/src/stored-json.ts
+++ b/server/src/stored-json.ts
@@ -3,10 +3,15 @@
33import { type JsonEvent, jsonEvents } from "./json-events.ts"; 55/** Temporary decoded JSON on disk. A root is published only after complete parsing. */ 6−export function storeJson(storage: GraphStateStorage, namespace: string, chunks: Iterable<string>): number {
6+export function storeJson( 7+ storage: GraphStateStorage, 9+ chunks: Iterable<string>, 10+ options: { finiteNumbers?: boolean } = {}, 712 return storage.transaction(() => { 813 if (storage.read(namespace, "root") !== undefined) throw Error("decoded JSON already exists"); 9− const events = jsonEvents(chunks);
14+ const events = jsonEvents(chunks, options); 1116 const take = (): JsonEvent => { 1217 const event = events.next(); --- /dev/null
+++ b/server/test/canonical-frame-numbers.test.ts
@@ -0,0 +1,32 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { withDecodedFrames } from "../src/decoded-frames.ts"; 4+import { SqliteLog } from "../src/engine-project.ts"; 5+import { SqliteWriterState } from "../src/writer-host.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+for (const padding of [0, 5000]) { 9+ test(`canonical frames reject numeric overflow with ${padding} padding bytes and clean scratch`, (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const log = new SqliteLog(storage); 13+ const json = `{"type":"join","agent":"${"a".repeat(padding)}","version":1e400}`; 14+ storage.sql.exec("INSERT INTO log(seq,part,text) VALUES(?,?,?)", 0, 0, json); 15+ SqliteWriterState.initialize(storage); 16+ const rows = () => storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(); 17+ const before = rows(); 24+ { from: 0, to: 1, maxEntries: 1, maxBytes: 10000, digest: "" }, 25+ (frames) => [...frames], 27+ /non-finite JSON number/, 29+ assert.deepEqual(rows(), before); 30+ assert.equal(storage.db.prepare("SELECT text FROM log WHERE seq=0 AND part=0").get()!.text, json); --- /dev/null
+++ b/server/test/projected-path-history.test.ts
@@ -0,0 +1,42 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { answer } from "../../worker/project/http.ts"; 4+import { Project } from "../../worker/project/project.ts"; 5+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 6+import { EngineProject } from "../src/engine-project.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("tree and path history after a move match memory without persistent read writes", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ const memory = EngineProject.open(storage); 13+ assert.equal(answer(memory, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }).status, 200); 14+ assert.equal(answer(memory, "move", "alice", { from: "a.txt", to: "b.txt" }).status, 200); 15+ assert.equal(answer(memory, "publish", "alice", { message: "Move" }).status, 200); 18+ ["tree", { version: 0 }], 19+ ["path", { path: "a.txt" }], 20+ ["path", { path: "b.txt" }], 22+ const expected = requests.map(([op, body]) => answer(memory, op, "alice", body)); 23+ for (const result of expected) assert.equal(result.status, 200, JSON.stringify(result)); 24+ t.mock.method(Project, "load", () => { 25+ throw Error("full-history replay forbidden"); 27+ const runtime = () => new DiskFirstRuntime(storage, "path-history", "path-history"); 28+ while (!runtime().preparePage(() => {}).ready) {} 29+ const rows = () => storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(); 30+ const before = rows(); 31+ for (let i = 0; i < requests.length; i++) { 32+ const [op, body] = requests[i]!; 35+ (calls) => answer(calls, op, "alice", body), 41+ assert.deepEqual(rows(), before); --- a/server/test/projected-queue.test.ts
+++ b/server/test/projected-queue.test.ts
@@ -76,6 +76,13 @@
7878 assert.deepEqual(landed.versions, [{ id: 1, version: 1 }]); 79+ const empty = runtime().read( 80+ (c) => (c as unknown as { project: Project }).project.queueCandidate(4), 83+ assert.deepEqual(empty.ids, []); 84+ assert.deepEqual(empty.files, candidate.files); 85+ assert.equal(empty.tree, candidate.tree); 8188 (c) => c.shared().files["a.txt"], --- /dev/null
+++ b/server/test/small-frame-integrity.test.ts
@@ -0,0 +1,24 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { jsonEvents } from "../src/json-events.ts"; 4+import { smallFrameJson } from "../src/small-frame-json.ts"; 6+test("small decoded frames freeze nested objects and arrays", () => { 7+ const value = smallFrameJson(['{"items":[{"value":1}]}']) as { items: { value: number }[] }; 8+ assert.equal(Object.isFrozen(value), true); 9+ assert.equal(Object.isFrozen(value.items), true); 10+ assert.equal(Object.isFrozen(value.items[0]), true); 11+ assert.throws(() => value.items.push({ value: 2 }), TypeError); 12+ assert.throws(() => { 13+ value.items[0]!.value = 3; 15+ assert.deepEqual(value, { items: [{ value: 1 }] }); 18+test("both JSON paths refuse non-finite numeric values", () => { 19+ for (const input of ["1e400", "-1e400", '{"n":1e400}', "[1e400]"]) { 20+ assert.throws(() => smallFrameJson([input]), /non-finite/); 21+ assert.throws(() => [...jsonEvents([input], { finiteNumbers: true })], /non-finite/); 23+ assert.equal(smallFrameJson(["1e308"]), 1e308); --- /dev/null
+++ b/src/engine/test/projection-reader-integrity.test.ts
@@ -0,0 +1,29 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts"; 4+import { ProjectionReader } from "../experimental/projection-reader.ts"; 5+import { Graph } from "../graph.ts"; 6+import { Repo } from "./helpers.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("file lookup rejects a missing marker for an included writer instead of following ancestry", (t) => { 10+ const storage = new SqlState(); 11+ t.after(() => storage.db.close()); 12+ const repo = Repo.init({ "f.txt": "one\ntwo\n" }); 13+ const graph = new Graph({ storage }); 14+ graph.add(repo.graph.atom("a0")); 15+ const adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "included-marker"); 16+ const state = adapter.apply(adapter.empty(), graph.atom("a0")); 17+ const reader = new ProjectionReader(adapter, state, () => {}); 18+ const line = [...adapter.lineIds(state, "f.txt")][0]!; 19+ assert.equal(reader.fileOf(line), "f.txt"); 20+ const markerKey = graph.lineN(line) + 1; 21+ const get = adapter.markers.get.bind(adapter.markers); 22+ t.mock.method(adapter.markers, "get", (root: Parameters<typeof get>[0], key: number) => 23+ key === markerKey ? undefined : get(root, key), 25+ t.mock.method(graph, "lineParent", () => { 26+ throw Error("included writer must not use ancestry fallback"); 28+ assert.throws(() => reader.fileOf(line), /missing projected line/); --- a/worker/project/pathindex.ts
+++ b/worker/project/pathindex.ts
@@ -141,7 +141,9 @@
143143 for (let v = index.upTo + 1; v <= last(space); v++) { 144− if (space.name === SHARED && !this.#keptFiles(space, v)) {
144+ // Persistent graphs use the indexed version reader; a raw View would 145+ // rebuild move scratch state and copy historical membership during a read. 146+ if (space.name === SHARED && !this.#deps.graph.hasOrderedChildren && !this.#keptFiles(space, v)) { 145147 if (v > 0 && !views.has(v - 1)) views.set(v - 1, new View(this.#deps.graph, new Set(setAt(v - 1)))); 146148 views.set(v, new View(this.#deps.graph, new Set(setAt(v)))); --- a/worker/project/queue.ts
+++ b/worker/project/queue.ts
@@ -237,9 +237,12 @@
238238 const items = host.queued().slice(0, Math.max(0, n)); 239239 const changes = items.flatMap((q) => q.changes); 240− const view = host.sharedOverlay
241− ? host.sharedOverlay(changes)
242− : host.view(unionOverlay(host.setOf(host.shared()), changes));
241+ changes.length === 0 243+ : host.sharedOverlay 244+ ? host.sharedOverlay(changes) 245+ : host.view(unionOverlay(host.setOf(host.shared()), changes)); 243246 const files = view.files(); 244247 const modes = modesOf(view); 245248 const blobs = view.blobs();