Bound persistent writer read caching and verify rollback isolation
of shared·codex-capacity-chair··Not checked
Version 110 · Files at version 111
4 files, 148 lines added, 8 removed.
--- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -13,6 +13,83 @@
1313 transaction<T>(body: () => T): T; 17+ * Operation-local read cache with fixed payload and entry limits. Serialized 18+ * values preserve the storage copy contract. Discard it after an outer host 19+ * rollback or any mutation made through another storage instance. 21+export class CachedStateStorage implements GraphStateStorage { 22+ readonly #source: GraphStateStorage; 23+ readonly #cache = new Map<string, { json: string; bytes: number }>(); 24+ readonly #maxBytes: number; 25+ readonly #maxEntries: number; 27+ constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096) { 28+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(maxEntries) || maxEntries < 0) 29+ throw new Error("invalid writer cache limits"); 30+ this.#source = source; 31+ this.#maxBytes = maxBytes; 32+ this.#maxEntries = maxEntries; 34+ get retainedBytes(): number { 37+ get retainedEntries(): number { 38+ return this.#cache.size; 44+ #drop(key: string): void { 45+ const previous = this.#cache.get(key); 47+ this.#cache.delete(key); 48+ this.#bytes -= previous.bytes; 51+ read(collection: string, key: string): unknown { 52+ const cacheKey = JSON.stringify([collection, key]); 53+ const hit = this.#cache.get(cacheKey); 55+ this.#cache.delete(cacheKey); 56+ this.#cache.set(cacheKey, hit); 57+ return (JSON.parse(hit.json) as { value?: unknown }).value; 59+ const value = this.#source.read(collection, key); 60+ const json = JSON.stringify({ value }); 61+ // Charge two bytes per UTF-16 unit and a conservative fixed entry cost. 62+ // This bounds retained payload; it is not an isolate heap measurement. 63+ const bytes = 2 * (json.length + cacheKey.length) + 128; 64+ if (bytes <= this.#maxBytes && this.#maxEntries > 0) { 65+ while (this.#bytes + bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries) 66+ this.#drop(this.#cache.keys().next().value!); 67+ this.#cache.set(cacheKey, { json, bytes }); 68+ this.#bytes += bytes; 72+ write(collection: string, key: string, value: unknown): void { 73+ this.#drop(JSON.stringify([collection, key])); 74+ this.#source.write(collection, key, value); 76+ remove(collection: string, key: string): void { 77+ this.#drop(JSON.stringify([collection, key])); 78+ this.#source.remove(collection, key); 80+ entries(collection: string): Iterable<readonly [string, unknown]> { 81+ return this.#source.entries(collection); 83+ transaction<T>(body: () => T): T { 85+ return this.#source.transaction(body); 1693/** Immutable membership whose implementation does not retain its enumerated keys. */ 1794export abstract class StableSet<T> implements ReadonlySet<T> { 1895 abstract has(value: T): boolean; --- /dev/null
+++ b/src/engine/test/state-cache.test.ts
@@ -0,0 +1,59 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { CachedStateStorage } from "../state-source.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("bounded writer cache copies values, invalidates writes and clears after rollback", () => { 7+ const source = new SqlState(); 8+ const cache = new CachedStateStorage(source, 1024, 3); 9+ source.write("rows", "a", { list: [1] }); 10+ const first = cache.read("rows", "a") as { list: number[] }; 12+ const reads = source.reads; 13+ assert.deepEqual(cache.read("rows", "a"), { list: [1] }); 14+ assert.equal(source.reads, reads); 15+ cache.write("rows", "a", { list: [3] }); 16+ assert.deepEqual(cache.read("rows", "a"), { list: [3] }); 19+ cache.transaction(() => { 20+ cache.write("rows", "a", { list: [4] }); 21+ assert.deepEqual(cache.read("rows", "a"), { list: [4] }); 22+ throw new Error("rollback"); 26+ assert.equal(cache.retainedEntries, 0); 27+ assert.deepEqual(cache.read("rows", "a"), { list: [3] }); 28+ cache.remove("rows", "a"); 29+ assert.equal(cache.read("rows", "a"), undefined); 30+ cache.write("rows", "a", "restored"); 31+ assert.equal(cache.read("rows", "a"), "restored"); 35+test("writer cache evicts by both payload and entry count and skips oversized values", () => { 36+ const source = new SqlState(); 37+ const cache = new CachedStateStorage(source, 1024, 3); 38+ for (let i = 0; i < 100; i++) { 39+ cache.write("rows", String(i), "small"); 40+ assert.equal(cache.read("rows", String(i)), "small"); 41+ assert.ok(cache.retainedBytes <= 1024); 42+ assert.ok(cache.retainedEntries <= 3); 44+ const reads = source.reads; 45+ cache.read("rows", "99"); 46+ assert.equal(source.reads, reads); 47+ cache.read("rows", "0"); 48+ assert.equal(source.reads, reads + 1); 49+ cache.write("rows", "large", "x".repeat(1024)); 50+ const before = cache.retainedBytes; 51+ cache.read("rows", "large"); 52+ assert.equal(cache.retainedBytes, before); 53+ const afterLarge = source.reads; 54+ cache.read("rows", "large"); 55+ assert.equal(source.reads, afterLarge + 1); 57+ assert.equal(cache.retainedBytes, 0); --- a/src/engine/test/storage-helper.ts
+++ b/src/engine/test/storage-helper.ts
@@ -2,13 +2,16 @@
22import type { GraphStateStorage } from "../state-source.ts"; 44export class SqlState implements GraphStateStorage { 5− readonly db = new DatabaseSync(":memory:");
5+ readonly db: DatabaseSync; 10− constructor() {
11− this.db.exec("CREATE TABLE state (collection TEXT, key TEXT, value TEXT, PRIMARY KEY(collection,key))");
10+ constructor(filename = ":memory:") { 11+ this.db = new DatabaseSync(filename); 13+ "CREATE TABLE IF NOT EXISTS state (collection TEXT, key TEXT, value TEXT, PRIMARY KEY(collection,key))", 1316 read(collection: string, key: string): unknown { --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -14,6 +14,7 @@
1515import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from "../../src/engine/index.ts"; 1718 type GraphStateStorage, @@ -346,9 +347,9 @@
347348 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) { 348349 this.#store = store; 349− this.#writerStorage = options.writerStorage;
350− if (options.writerStorage) {
351− const storage = options.writerStorage;
350+ this.#writerStorage = options.writerStorage ? new CachedStateStorage(options.writerStorage) : undefined; 351+ if (this.#writerStorage) { 352+ const storage = this.#writerStorage; 352353 // A stored Graph cannot be replayed over itself. Check before any 353354 // constructor writes so an accidental reopen preserves the namespace. @@ -398,8 +399,8 @@
398399 throw new Error(`log entry ${at} holds no atom ${seq}`); 400401 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for. 401− this.#graph = options.writerStorage
402− ? new Graph({ storage: options.writerStorage })
402+ this.#graph = this.#writerStorage 403+ ? new Graph({ storage: this.#writerStorage }) 404405 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })