Stream canonical log append and bound JSON string decoding allocations
of shared·codex-capacity-chair··Not checked
Version 166 · Files at version 167
4 files, 97 lines added, 4 removed.
--- a/server/src/engine-project.ts
+++ b/server/src/engine-project.ts
@@ -3,6 +3,7 @@
33// 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the 44// writer-adoption and R2 version parts are left out. 6+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts"; 67import { blame, folderBlame, why } from "../../worker/project/blame.ts"; 78import { feedEvents } from "../../worker/project/feed.ts"; 89import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts"; @@ -33,6 +34,22 @@
37+/** Retains one log row plus an encoder fragment, preserving legacy row boundaries. */ 38+export function* streamedLogParts(value: unknown): IterableIterator<string> { 40+ for (const chunk of jsonValueChunks(value)) { 42+ while (pending.length > LOG_PART_CHARACTERS) { 43+ let end = LOG_PART_CHARACTERS; 44+ const last = pending.charCodeAt(end - 1); 45+ if (last >= 0xd800 && last <= 0xdbff) end--; 46+ yield pending.slice(0, end); 47+ pending = pending.slice(end); 50+ if (pending) yield pending; 3653/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */ 3754function linesIn(entry: Entry): number { @@ -424,11 +441,11 @@
424441 if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys); 426443 for (const entry of entries) { 427− const json = JSON.stringify(entry);
428− logParts(json).forEach((text, part) => {
445+ for (const text of streamedLogParts(entry)) { 429446 chars += text.length; 430− this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part, text);
431− });
447+ this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part++, text); 434451 // Chars are only added to once counted: a log from before the count is summed whole first (logSize). --- a/server/src/json-chunk-cursor.ts
+++ b/server/src/json-chunk-cursor.ts
@@ -27,6 +27,24 @@
2727 if (this.take() !== '"') throw Error("expected JSON string"); 30+ // Copy ordinary text in bounded slices instead of allocating a string 31+ // concatenation for every character of a large canonical field. 33+ const start = this.#offset; 34+ const end = Math.min(this.#chunk.length, start + 16384 - buffer.length); 35+ while (this.#offset < end) { 36+ const code = this.#chunk.charCodeAt(this.#offset); 37+ if (code < 32 || code === 34 || code === 92) break; 40+ if (this.#offset > start) { 41+ buffer += this.#chunk.slice(start, this.#offset); 42+ if (buffer.length === 16384) { 3048 let char = this.take(); 3250 if (buffer) yield buffer; --- /dev/null
+++ b/server/test/streamed-log-append.test.ts
@@ -0,0 +1,27 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { LOG_PART_CHARACTERS, logParts, streamedLogParts } from "../src/engine-project.ts"; 5+test("streamed canonical rows exactly match legacy serialization and boundaries", () => { 6+ for (const offset of [-2, -1, 0, 1, 2]) { 7+ const value = { text: "x".repeat(LOG_PART_CHARACTERS - 9 + offset) + '😀\ud800\n"', rest: [null, false, 3] }; 8+ assert.deepEqual([...streamedLogParts(value)], logParts(JSON.stringify(value))); 10+ const value = { files: Array.from({ length: 100 }, (_, i) => `${i}:` + "中".repeat(20000)) }; 11+ assert.deepEqual([...streamedLogParts(value)], logParts(JSON.stringify(value))); 14+test("canonical row streaming never stringifies a whole object or a large string", (t) => { 15+ const stringify = JSON.stringify; 16+ t.mock.method(JSON, "stringify", (value: unknown) => { 17+ assert.ok(typeof value !== "object", "whole-object serialization is forbidden"); 18+ if (typeof value === "string") assert.ok(value.length <= 16384); 19+ return stringify(value); 22+ for (const part of streamedLogParts({ text: "x".repeat(6_000_000) })) { 23+ assert.ok(part.length <= LOG_PART_CHARACTERS); 24+ length += part.length; 26+ assert.equal(length, 6_000_011); --- /dev/null
+++ b/server/test/streamed-log-transaction.test.ts
@@ -0,0 +1,31 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { MemoryStore, Project } from "../../worker/project/project.ts"; 4+import { logParts, SqliteLog } from "../src/engine-project.ts"; 5+import { memoryStorage } from "./helpers.ts"; 7+test("streamed append preserves exact rows and rolls back a partial frame on storage failure", (t) => { 8+ const memory = new MemoryStore(); 9+ new Project(memory).init({ "large.txt": "😀".repeat(700000) }, 0); 10+ const expected = memory.entries.flatMap((entry, seq) => 11+ logParts(JSON.stringify(entry)).map((text, part) => ({ seq, part, text })), 13+ const storage = memoryStorage(); 14+ t.after(() => storage.db.close()); 15+ const log = new SqliteLog(storage); 16+ const beforeGeneration = log.generation(); 17+ const exec = storage.sql.exec.bind(storage.sql); 19+ storage.sql.exec = (query, ...bindings) => { 20+ if (query.startsWith("INSERT INTO log") && ++inserts === 2) throw Error("injected row failure"); 21+ return exec(query, ...bindings); 23+ assert.throws(() => log.append(memory.entries), /injected row failure/); 24+ storage.sql.exec = exec; 25+ assert.deepEqual(storage.db.prepare("SELECT * FROM log").all(), []); 26+ assert.equal(log.generation(), beforeGeneration); 27+ log.append(memory.entries); 28+ const rows = storage.db.prepare("SELECT seq, part, text FROM log ORDER BY seq, part").all(); 29+ assert.deepEqual(JSON.parse(JSON.stringify(rows)), expected); 30+ assert.equal(log.generation(), beforeGeneration + 1);