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
blame on this site's /mcp
CLI
abso blame src/engine/state-source.ts --version 258 --json
JSON
/christopher/abso-core/blame/src/engine/state-source.ts?version=258&format=json
761 linescodex-capacity-chair 78% · capacity 22%Last change capacity in version 258,

761 lines from 27 changes in 17 versions.

codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1/**
2 * Indexed graph storage. Values must be copied on write and read: a caller
3 * mutating a returned list must not silently change persisted state. Hosts
4 * provide transactions that roll back every write when the callback throws.
5 * The namespace belongs to one graph and must not be shared by concurrent
6 * Graph instances. Opening a graph does not scan its stored collections.
7 */
8export interface GraphStateStorage {
9 read(collection: string, key: string): unknown;
10 write(collection: string, key: string, value: unknown): void;
11 remove(collection: string, key: string): void;
12 entries(collection: string): Iterable<readonly [string, unknown]>;
13 transaction<T>(body: () => T): T;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare16/**
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare17 * Operation-local read cache with fixed payload and entry limits. Private numeric
18 * pages, immutable scalars and serialized objects preserve the copy contract. Discard it after an outer host
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare19 * rollback or any mutation made through another storage instance.
20 */
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare21type CachedValue = { bytes: number } & (
22 | { kind: "scalar"; value: string | number | boolean | null | undefined }
23 | { kind: "numbers"; value: readonly number[] }
24 | { kind: "json"; json: string }
25);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare27export class CachedStateStorage implements GraphStateStorage {
28 readonly #source: GraphStateStorage;
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare29 readonly #cache = new Map<string, CachedValue>();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare30 readonly #maxBytes: number;
31 readonly #maxEntries: number;
32 #bytes = 0;
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare33 /**
34 * The keys written or removed in each open transaction, innermost last (abso Capacity). A rollback drops only those:
35 * every projection scratch scope ends in a rollback, and dropping the whole cache there read the same rows from
36 * storage again within a call and on every call of a kept reader.
37 */
38 readonly #touched: Set<string>[] = [];
39 /**
40 * The biggest one row may be and still be kept (abso Capacity). A few big rows read on every call (each agent with
41 * all the news it was told: 4.3 MB for abso's 109 agents) otherwise push every small page out of the cache.
42 */
43 readonly #maxEntryBytes: number;
capacity258Told lists out of agent rows, in 64 bucket rows per agent; layout pages read through the writer cache; a laid-out file's authors counted by writer (abso Capacity, issue 664; Security yes on ask 2102; Agent VCS approved). - writer-agents.ts: each agent's told keys (the news it has been told) live in 64 rows of their own, project:agents:told, keyed by the agent's name and a fixed hash bucket (FNV-1a mod 64), each holding its bucket's keys sorted; the agent row no longer carries them. told.has reads one bucket and told.add rewrites one; status, where and drafts never read them. A row written before keeps its list, read alongside the buckets (StoredTold.listed) until the agent's row is next written, which moves the list into the buckets; a fresh adoption writes the new form from the start. Removing an agent clears its buckets; delete and purge clear the writer state with them. abso's 109 agent rows were 4.3 MB, the largest 100.9 KB. - CachedStateStorage can read collections straight through; the writer passes file-lines, file-texts and file-deletes pages, which are read only to lay a file out (the view keeps the layout) and pushed out the small rows read on every call. - authorsInView: a laid-out file's lines by author from its visible lines' writers, each writer's author once (tree with authors, folder blame, and the totals adoption keeps), instead of an atom id and line id per line. Tests: told-buckets (new: news on a stored writer against the in-memory project, every step's news asked twice, before and after an agent's told keys are half in an old row's list and half in buckets, with a writer opened afresh; the old list moves into the buckets on the agent's next write; an agent never reads another's buckets; a rollback leaves the buckets as they were). state-cache: a collection read straight through is never kept and pushes nothing out. All of src/engine/test (295) and worker/project/test (351, one skipped) pass.Compare44 /**
45 * Collections read straight through, never kept (abso Capacity): a file's packed line pages are read only to lay the
46 * file out, and the view keeps the layout, so keeping the pages too held them twice and pushed out the small rows
47 * read on every call (an agent's tree re-read 3,500 of them each time).
48 */
49 readonly #passThrough: (collection: string) => boolean;
50 constructor(
51 source: GraphStateStorage,
52 maxBytes = 1_048_576,
53 maxEntries = 4096,
54 maxEntryBytes = maxBytes,
55 passThrough: (collection: string) => boolean = () => false,
56 ) {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare57 if (
58 !Number.isSafeInteger(maxBytes) ||
59 maxBytes < 0 ||
60 !Number.isSafeInteger(maxEntries) ||
61 maxEntries < 0 ||
62 !Number.isSafeInteger(maxEntryBytes) ||
63 maxEntryBytes < 0
64 )
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare65 throw new Error("invalid writer cache limits");
66 this.#source = source;
67 this.#maxBytes = maxBytes;
68 this.#maxEntries = maxEntries;
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare69 this.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes);
capacity258Told lists out of agent rows, in 64 bucket rows per agent; layout pages read through the writer cache; a laid-out file's authors counted by writer (abso Capacity, issue 664; Security yes on ask 2102; Agent VCS approved). - writer-agents.ts: each agent's told keys (the news it has been told) live in 64 rows of their own, project:agents:told, keyed by the agent's name and a fixed hash bucket (FNV-1a mod 64), each holding its bucket's keys sorted; the agent row no longer carries them. told.has reads one bucket and told.add rewrites one; status, where and drafts never read them. A row written before keeps its list, read alongside the buckets (StoredTold.listed) until the agent's row is next written, which moves the list into the buckets; a fresh adoption writes the new form from the start. Removing an agent clears its buckets; delete and purge clear the writer state with them. abso's 109 agent rows were 4.3 MB, the largest 100.9 KB. - CachedStateStorage can read collections straight through; the writer passes file-lines, file-texts and file-deletes pages, which are read only to lay a file out (the view keeps the layout) and pushed out the small rows read on every call. - authorsInView: a laid-out file's lines by author from its visible lines' writers, each writer's author once (tree with authors, folder blame, and the totals adoption keeps), instead of an atom id and line id per line. Tests: told-buckets (new: news on a stored writer against the in-memory project, every step's news asked twice, before and after an agent's told keys are half in an old row's list and half in buckets, with a writer opened afresh; the old list moves into the buckets on the agent's next write; an agent never reads another's buckets; a rollback leaves the buckets as they were). state-cache: a collection read straight through is never kept and pushes nothing out. All of src/engine/test (295) and worker/project/test (351, one skipped) pass.Compare70 this.#passThrough = passThrough;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare71 }
72 get retainedBytes(): number {
73 return this.#bytes;
74 }
75 get retainedEntries(): number {
76 return this.#cache.size;
77 }
78 clear(): void {
79 this.#cache.clear();
80 this.#bytes = 0;
81 }
82 #drop(key: string): void {
83 const previous = this.#cache.get(key);
84 if (previous) {
85 this.#cache.delete(key);
86 this.#bytes -= previous.bytes;
87 }
88 }
89 read(collection: string, key: string): unknown {
capacity258Told lists out of agent rows, in 64 bucket rows per agent; layout pages read through the writer cache; a laid-out file's authors counted by writer (abso Capacity, issue 664; Security yes on ask 2102; Agent VCS approved). - writer-agents.ts: each agent's told keys (the news it has been told) live in 64 rows of their own, project:agents:told, keyed by the agent's name and a fixed hash bucket (FNV-1a mod 64), each holding its bucket's keys sorted; the agent row no longer carries them. told.has reads one bucket and told.add rewrites one; status, where and drafts never read them. A row written before keeps its list, read alongside the buckets (StoredTold.listed) until the agent's row is next written, which moves the list into the buckets; a fresh adoption writes the new form from the start. Removing an agent clears its buckets; delete and purge clear the writer state with them. abso's 109 agent rows were 4.3 MB, the largest 100.9 KB. - CachedStateStorage can read collections straight through; the writer passes file-lines, file-texts and file-deletes pages, which are read only to lay a file out (the view keeps the layout) and pushed out the small rows read on every call. - authorsInView: a laid-out file's lines by author from its visible lines' writers, each writer's author once (tree with authors, folder blame, and the totals adoption keeps), instead of an atom id and line id per line. Tests: told-buckets (new: news on a stored writer against the in-memory project, every step's news asked twice, before and after an agent's told keys are half in an old row's list and half in buckets, with a writer opened afresh; the old list moves into the buckets on the agent's next write; an agent never reads another's buckets; a rollback leaves the buckets as they were). state-cache: a collection read straight through is never kept and pushes nothing out. All of src/engine/test (295) and worker/project/test (351, one skipped) pass.Compare90 if (this.#passThrough(collection)) return this.#source.read(collection, key);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare91 const cacheKey = JSON.stringify([collection, key]);
92 const hit = this.#cache.get(cacheKey);
93 if (hit) {
94 this.#cache.delete(cacheKey);
95 this.#cache.set(cacheKey, hit);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare96 if (hit.kind === "scalar") return hit.value;
97 if (hit.kind === "numbers") return hit.value.slice();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare98 return (JSON.parse(hit.json) as { value?: unknown }).value;
99 }
100 const value = this.#source.read(collection, key);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare101 const overhead = 2 * cacheKey.length + 160;
102 let entry: CachedValue;
103 if (
104 value === undefined ||
105 value === null ||
106 typeof value === "string" ||
107 typeof value === "boolean" ||
108 (typeof value === "number" && Number.isFinite(value))
109 ) {
110 entry = { kind: "scalar", value, bytes: overhead + (typeof value === "string" ? 2 * value.length : 16) };
111 } else if (
112 Array.isArray(value) &&
113 value.length <= 256 &&
114 Object.keys(value).length === value.length &&
115 value.every(Number.isSafeInteger)
116 ) {
117 // Store one private, bounded numeric page. Public reads still receive a
118 // fresh copy; neither the source result nor a reader can mutate the cache.
119 entry = { kind: "numbers", value: value.slice(), bytes: overhead + 32 + value.length * 8 };
120 } else {
121 const json = JSON.stringify({ value });
122 entry = { kind: "json", json, bytes: overhead + 2 * json.length };
123 }
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare124 this.#remember(cacheKey, entry);
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare125 // A projection scope's own rows are never read again once it ends in its rollback: forget them with it.
126 if (collection.startsWith("projection-scratch:")) this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare127 return value;
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare128 }
129 #remember(cacheKey: string, entry: CachedValue): void {
130 this.#drop(cacheKey);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare131 // Payload accounting is bounded, not a measurement of actual isolate heap.
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare132 if (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) {
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare133 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare134 this.#drop(this.#cache.keys().next().value!);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare135 this.#cache.set(cacheKey, entry);
136 this.#bytes += entry.bytes;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare137 }
138 }
139 write(collection: string, key: string, value: unknown): void {
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare140 const cacheKey = JSON.stringify([collection, key]);
141 this.#drop(cacheKey);
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare142 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare143 this.#source.write(collection, key, value);
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare144 // Allocation counters are immutable scalars. Keep successful writes within
145 // the existing cache budget instead of immediately reading them back.
146 if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0))
147 this.#remember(cacheKey, { kind: "scalar", value, bytes: 2 * cacheKey.length + 176 });
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare148 }
149 remove(collection: string, key: string): void {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare150 const cacheKey = JSON.stringify([collection, key]);
151 this.#drop(cacheKey);
152 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare153 this.#source.remove(collection, key);
154 }
155 entries(collection: string): Iterable<readonly [string, unknown]> {
156 return this.#source.entries(collection);
157 }
158 transaction<T>(body: () => T): T {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare159 const touched = new Set<string>();
160 this.#touched.push(touched);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare161 try {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare162 const result = this.#source.transaction(body);
163 this.#touched.pop();
164 // Committed into the outer transaction, which may still roll back.
165 const outer = this.#touched.at(-1);
166 if (outer) for (const key of touched) outer.add(key);
167 return result;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare168 } catch (error) {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare169 this.#touched.pop();
170 // What the transaction wrote, and anything read back after it wrote it, is gone with the rollback.
171 for (const key of touched) this.#drop(key);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare172 throw error;
173 }
174 }
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare177/**
178 * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project
179 * given one skips proving it again, which read every atom and every dependency in the history.
180 */
181const closedSets = new WeakSet<object>();
182export function markClosed<S extends ReadonlySet<unknown>>(set: S): S {
183 closedSets.add(set);
184 return set;
186export function isClosedSet(set: unknown): boolean {
187 return typeof set === "object" && set !== null && closedSets.has(set);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare190/** Immutable membership whose implementation does not retain its enumerated keys. */
191export abstract class StableSet<T> implements ReadonlySet<T> {
192 abstract has(value: T): boolean;
193 abstract values(): SetIterator<T>;
194 /** Only resident membership data; external storage is not charged as heap. */
195 abstract readonly retainedBytes: number;
196 get [Symbol.toStringTag](): string {
197 return "Set";
198 }
199 get size(): number {
200 let count = 0;
201 for (const _ of this) count++;
202 return count;
203 }
204 keys(): SetIterator<T> {
205 return this.values();
206 }
207 *entries(): SetIterator<[T, T]> {
208 for (const value of this) yield [value, value];
209 }
210 [Symbol.iterator](): SetIterator<T> {
211 return this.values();
212 }
213 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
214 for (const value of this) callback.call(thisArg, value, value, this);
215 }
218/** Both operands must be immutable for the lifetime of this union. */
219export class StableUnionSet<T> extends StableSet<T> {
220 readonly #left: StableSet<T>;
221 readonly #right: StableSet<T>;
222 constructor(left: StableSet<T>, right: StableSet<T>) {
223 super();
224 this.#left = left;
225 this.#right = right;
226 }
227 get retainedBytes(): number {
228 return 32 + this.#left.retainedBytes + this.#right.retainedBytes;
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare229 }
230 get left(): StableSet<T> {
231 return this.#left;
232 }
233 get right(): StableSet<T> {
234 return this.#right;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare235 }
236 has(value: T): boolean {
237 return this.#left.has(value) || this.#right.has(value);
238 }
239 *values(): SetIterator<T> {
240 yield* this.#left;
241 for (const value of this.#right) if (!this.#left.has(value)) yield value;
242 }
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare245/** Immutable indexed subtraction retains neither operand's enumerated values. */
246export class StableDifferenceSet<T> extends StableSet<T> {
247 readonly left: StableSet<T>;
248 readonly right: StableSet<T>;
249 constructor(left: StableSet<T>, right: StableSet<T>) {
250 super();
251 this.left = left;
252 this.right = right;
253 }
254 get retainedBytes(): number {
255 return 32 + this.left.retainedBytes + this.right.retainedBytes;
256 }
257 has(value: T): boolean {
258 return this.left.has(value) && !this.right.has(value);
259 }
260 *values(): SetIterator<T> {
261 for (const value of this.left) if (!this.right.has(value)) yield value;
262 }
265/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
266export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
267 return base instanceof StableSet
268 ? new StableUnionSet(base, new StableOverlaySet(overlay))
269 : new Set([...base, ...overlay]);
272/** Both indexed operands must be immutable for the lifetime of the result. */
273export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
274 return left instanceof StableSet && right instanceof StableSet
275 ? new StableDifferenceSet(left, right)
276 : new Set([...left].filter((value) => !right.has(value)));
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare279/** An immutable snapshot for the operation's small overlay, not its history. */
280export class StableOverlaySet<T> extends StableSet<T> {
281 readonly #values: Set<T>;
282 constructor(values: Iterable<T>) {
283 super();
284 this.#values = new Set(values);
285 }
286 get retainedBytes(): number {
287 return 64 + this.#values.size * 32;
288 }
289 has(value: T): boolean {
290 return this.#values.has(value);
291 }
292 values(): SetIterator<T> {
293 return this.#values.values();
294 }
297const indexKey = (key: PropertyKey): key is string =>
298 typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
codex-capacity-chair113Page disk-first numeric graph indexes under bounded storage cacheCompare300/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
301export function storedNumbers(storage: GraphStateStorage, name: string) {
302 const pageSize = 256;
303 const meta = `${name}:meta`;
304 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
305 // Older experimental writer indexes must be rebuilt from their canonical log.
306 // Never interpret per-element rows as pages or silently lose existing history.
307 const page = (index: number): number[] => {
308 if (storage.read(meta, "format") !== 2)
309 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
310 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
311 if (!values) throw new Error(`missing writer numeric page in ${name}`);
312 return values;
313 };
314 return {
315 get length() {
316 return length();
317 },
318 at(index: number): number {
319 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
320 throw new Error(`writer numeric index out of bounds in ${name}`);
321 const value = page(index)[index % pageSize];
322 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
323 return value;
324 },
325 push(value: number): void {
326 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
327 const index = length();
328 if (index > 0 && storage.read(meta, "format") !== 2)
329 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
330 const offset = index % pageSize;
331 const values = offset === 0 ? [] : page(index);
332 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
333 values.push(value);
334 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
335 if (index === 0) storage.write(meta, "format", 2);
336 storage.write(meta, "length", index + 1);
337 },
338 set(index: number, value: number): void {
339 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
340 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
341 throw new Error(`writer numeric index out of bounds in ${name}`);
342 const values = page(index);
343 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
344 values[index % pageSize] = value;
345 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
346 },
347 };
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare350/** Array-shaped access without retaining its historical values in memory. */
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare351export function storedArray<T>(
352 storage: GraphStateStorage,
353 name: string,
354 decode?: (value: T) => T,
355 encode?: (value: T, key: string) => unknown,
356): T[] {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare357 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
358 const read = (key: string) => {
359 const value = storage.read(name, key) as T;
360 return value === undefined || !decode ? value : decode(value);
361 };
362 return new Proxy([] as T[], {
363 get(target, key, receiver) {
364 if (key === "length") return length();
365 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
366 return Reflect.get(target, key, receiver);
367 },
368 set(_target, key, value) {
369 if (key === "length") {
370 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
371 return true;
372 }
373 if (!indexKey(key)) throw new Error("invalid stored graph array property");
374 const index = Number(key);
375 const size = length();
376 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare377 storage.write(name, key, encode ? encode(value, key) : value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare378 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
379 return true;
380 },
381 has(target, key) {
382 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
383 },
384 ownKeys() {
385 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
386 },
387 getOwnPropertyDescriptor(target, key) {
388 if (indexKey(key) && Number(key) < length())
389 return { configurable: true, enumerable: true, writable: true, value: read(key) };
390 return Reflect.getOwnPropertyDescriptor(target, key);
391 },
392 });
395export interface StateMap<K, V> {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare396 keys(): IterableIterator<K>;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare397 get(key: K): V | undefined;
398 set(key: K, value: V): StateMap<K, V>;
399 has(key: K): boolean;
400 delete(key: K): boolean;
401 values(): IterableIterator<V>;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare404/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare405export function storedLists<V>(
406 storage: GraphStateStorage,
407 name: string,
408 legacyKey = (key: string) => JSON.stringify(["string", key]),
409) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare410 const pageSize = 256;
411 // The previous experimental layout stored one whole historical list per key.
412 const length = (key: string) => {
413 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare414 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare415 throw new Error(`writer list index ${name} requires canonical-log adoption`);
416 const count = stored ?? 0;
417 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
418 return count;
419 };
420 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
421 const page = (key: string, index: number): V[] => {
422 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
423 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
424 throw new Error(`missing or invalid writer list page in ${name}`);
425 return values;
426 };
427 return {
428 length,
429 *keys(): IterableIterator<string> {
430 for (const entry of storage.entries(name)) {
431 void entry;
432 throw new Error(`writer list index ${name} requires canonical-log adoption`);
433 }
434 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
435 },
436 *values(key: string): IterableIterator<V> {
437 const count = length(key);
438 for (let start = 0; start < count; start += pageSize) {
439 const values = page(key, start / pageSize);
440 if (values.length !== Math.min(pageSize, count - start))
441 throw new Error(`incomplete writer list page in ${name}`);
442 yield* values;
443 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare444 },
445 last(key: string): V | undefined {
446 const count = length(key);
447 if (count === 0) return undefined;
448 const values = page(key, Math.floor((count - 1) / pageSize));
449 const expected = ((count - 1) % pageSize) + 1;
450 if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);
451 return values[expected - 1];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare452 },
453 append(key: string, value: V): void {
454 const count = length(key);
455 const offset = count % pageSize;
456 const index = Math.floor(count / pageSize);
457 const values = offset === 0 ? [] : page(key, index);
458 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
459 values.push(value);
460 storage.write(`${name}:pages`, pageKey(key, index), values);
461 storage.write(`${name}:lengths`, key, count + 1);
462 },
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare463 /** Append several values, writing each page they touch once. */
464 appendAll(key: string, more: readonly V[]): void {
465 if (more.length === 0) return;
466 const count = length(key);
467 let index = Math.floor(count / pageSize);
468 let values = count % pageSize === 0 ? [] : page(key, index);
469 if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);
470 for (const value of more) {
471 if (values.length === pageSize) {
472 storage.write(`${name}:pages`, pageKey(key, index++), values);
473 values = [];
474 }
475 values.push(value);
476 }
477 storage.write(`${name}:pages`, pageKey(key, index), values);
478 storage.write(`${name}:lengths`, key, count + more.length);
479 },
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare480 };
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare483/** Keys are tagged so numeric graph codes cannot collide with string keys. */
484export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
485 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
486 const map: StateMap<K, V> = {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare487 *keys() {
488 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
489 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare490 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
491 has: (key) => storage.read(name, keyOf(key)) !== undefined,
492 set(key, value) {
493 storage.write(name, keyOf(key), value);
494 return map;
495 },
496 delete(key) {
497 const existed = map.has(key);
498 storage.remove(name, keyOf(key));
499 return existed;
500 },
501 *values() {
502 for (const [, value] of storage.entries(name)) yield value as V;
503 },
504 };
505 return map;
508/**
509 * A Map-compatible persistent index. Iteration follows insertion order and
510 * decodes one row at a time. Returned objects are copies, so mutations need
511 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
512 */
513export class StoredMap<K extends string | number, V> extends Map<K, V> {
514 readonly #storage: GraphStateStorage;
515 readonly #name: string;
516 readonly #encode: (value: V) => unknown;
517 readonly #decode: (value: unknown) => V;
518 constructor(
519 storage: GraphStateStorage,
520 name: string,
521 codec?: { encode(value: V): unknown; decode(value: unknown): V },
522 ) {
523 super();
524 this.#storage = storage;
525 this.#name = name;
526 this.#encode = codec?.encode ?? ((value) => value);
527 this.#decode = codec?.decode ?? ((value) => value as V);
528 }
529 #key(key: K): string {
530 return JSON.stringify([typeof key, key]);
531 }
532 #row(key: K): { slot: number; value: unknown } | undefined {
533 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
534 }
535 override get size(): number {
536 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
537 }
538 override has(key: K): boolean {
539 return this.#row(key) !== undefined;
540 }
541 override get(key: K): V | undefined {
542 const row = this.#row(key);
543 return row === undefined ? undefined : this.#decode(row.value);
544 }
545 override set(key: K, value: V): this {
546 const row = this.#row(key);
547 let slot = row?.slot;
548 if (slot === undefined) {
549 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
550 slot = keys.length;
551 keys.push(key);
552 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
553 }
554 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
555 return this;
556 }
557 override delete(key: K): boolean {
558 if (!this.has(key)) return false;
559 this.#storage.remove(this.#name, this.#key(key));
560 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
561 return true;
562 }
563 override clear(): void {
564 for (const key of this.keys()) this.delete(key);
565 }
566 override *entries(): MapIterator<[K, V]> {
567 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
568 for (let slot = 0; slot < keys.length; slot++) {
569 const key = keys[slot]!;
570 const row = this.#row(key);
571 if (row?.slot === slot) yield [key, this.#decode(row.value)];
572 }
573 }
574 override *keys(): MapIterator<K> {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare575 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
576 for (let slot = 0; slot < keys.length; slot++) {
577 const key = keys[slot]!;
578 if (this.#row(key)?.slot === slot) yield key;
579 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare580 }
581 override *values(): MapIterator<V> {
582 for (const [, value] of this.entries()) yield value;
583 }
584 override [Symbol.iterator](): MapIterator<[K, V]> {
585 return this.entries();
586 }
587 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
588 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
589 }
592/** Persistent membership with streaming iteration and no in-memory key cache. */
593export class StoredSet<K extends string | number> extends Set<K> {
594 readonly #map: StoredMap<K, true>;
595 constructor(storage: GraphStateStorage, name: string) {
596 super();
597 this.#map = new StoredMap(storage, name);
598 }
599 override get size(): number {
600 return this.#map.size;
601 }
602 override has(key: K): boolean {
603 return this.#map.has(key);
604 }
605 override add(key: K): this {
606 this.#map.set(key, true);
607 return this;
608 }
609 override delete(key: K): boolean {
610 return this.#map.delete(key);
611 }
612 override clear(): void {
613 this.#map.clear();
614 }
615 override *values(): SetIterator<K> {
616 yield* this.#map.keys();
617 }
618 override keys(): SetIterator<K> {
619 return this.values();
620 }
621 override *entries(): SetIterator<[K, K]> {
622 for (const key of this.values()) yield [key, key];
623 }
624 override [Symbol.iterator](): SetIterator<K> {
625 return this.values();
626 }
627 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
628 for (const key of this.values()) callback.call(thisArg, key, key, this);
629 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare630}
632/** Read-only array access to individually stored values, without copying the list. */
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare633/** How many values an atom's long list keeps to a row (readonlyPagedArray). */
634export const LIST_PAGE = 256;
636/** Write a list as readonlyPagedArray reads it: its values LIST_PAGE to a row, and its length. */
637export function writePagedArray(storage: GraphStateStorage, name: string, values: readonly unknown[]): void {
638 for (let start = 0; start < values.length; start += LIST_PAGE)
639 storage.write(`${name}:pages`, String(start / LIST_PAGE), values.slice(start, start + LIST_PAGE));
640 storage.write(`${name}:meta`, "length", values.length);
643/**
644 * A stored list read a page of LIST_PAGE values at a time (abso Capacity): an atom's long lists, which
645 * readonlyStoredArray reads a row per value. Collisions read every key a draft's atoms write; a draft deleting a big
646 * file has thousands, and that was a row each.
647 */
648export function readonlyPagedArray<T>(storage: GraphStateStorage, name: string): readonly T[] {
649 const length = () => {
650 const count = storage.read(`${name}:meta`, "length");
651 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
652 return count as number;
653 };
654 length();
655 let held = -1;
656 let page: readonly unknown[] = [];
657 const at = (index: number): T => {
658 const p = Math.floor(index / LIST_PAGE);
659 if (p !== held) {
660 const raw = storage.read(`${name}:pages`, String(p));
661 if (!Array.isArray(raw)) throw Error("missing stored list page");
662 page = raw;
663 held = p;
664 }
665 const value = page[index % LIST_PAGE];
666 if (value === undefined) throw Error("missing stored list element");
667 return (value && typeof value === "object" ? Object.freeze(value) : value) as T;
668 };
669 function* inOrder(): IterableIterator<T> {
670 const count = length();
671 for (let index = 0; index < count; index++) yield at(index);
672 }
673 return new Proxy([] as T[], {
674 get(target, key, receiver) {
675 if (key === "length") return length();
676 if (key === Symbol.iterator || key === "values") return inOrder;
677 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
678 return Reflect.get(target, key, receiver);
679 },
680 has(target, key) {
681 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
682 },
683 ownKeys() {
684 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
685 },
686 getOwnPropertyDescriptor(target, key) {
687 if (indexKey(key) && Number(key) < length())
688 return { configurable: true, enumerable: true, writable: false, value: at(Number(key)) };
689 return Reflect.getOwnPropertyDescriptor(target, key);
690 },
691 set() {
692 throw Error("stored lists are read-only");
693 },
694 });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare697export function readonlyStoredArray<T>(
698 storage: GraphStateStorage,
699 name: string,
700 decode?: (value: unknown, index: number) => T,
701): readonly T[] {
702 const length = () => {
703 const count = storage.read(`${name}:meta`, "length");
704 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
705 return count as number;
706 };
707 length();
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare708 const at = (index: number): T => {
709 const raw = storage.read(name, String(index));
710 const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T);
711 if (value === undefined) throw Error("missing stored list element");
712 return value && typeof value === "object" ? (Object.freeze(value) as T) : value;
713 };
714 // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a
715 // second disk read per element of a list too long for the cache.
716 function* inOrder(): IterableIterator<T> {
717 const count = length();
718 for (let index = 0; index < count; index++) yield at(index);
719 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare720 return new Proxy([] as T[], {
721 get(target, key, receiver) {
722 if (key === "length") return length();
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare723 if (key === Symbol.iterator || key === "values") return inOrder;
724 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare725 return Reflect.get(target, key, receiver);
726 },
727 has(target, key) {
728 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
729 },
730 ownKeys() {
731 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
732 },
733 getOwnPropertyDescriptor(target, key) {
734 if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };
735 if (indexKey(key) && Number(key) < length()) {
736 const raw = storage.read(name, key);
737 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
738 if (value === undefined) throw Error("missing stored list element");
739 return {
740 configurable: true,
741 enumerable: true,
742 writable: false,
743 value: value && typeof value === "object" ? Object.freeze(value) : value,
744 };
745 }
746 return Reflect.getOwnPropertyDescriptor(target, key);
747 },
748 preventExtensions() {
749 throw Error("stored list is read-only");
750 },
751 set() {
752 throw Error("stored list is read-only");
753 },
754 deleteProperty() {
755 throw Error("stored list is read-only");
756 },
757 defineProperty() {
758 throw Error("stored list is read-only");
759 },
760 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare761}