- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/state-source.ts --draft perf-cache-older-half --json
- JSON
- /christopher/abso-core/blame/src/engine/state-source.ts?draft=perf-cache-older-half&format=json
766 linescodex-capacity-chair 77% · capacity 21% · perf 2%
766 lines from 27 changes in 18 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;
14}
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 metadataCompare22 | { 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;
perfdraft33 /** Counts every row put at the back of the cache (abso - Performance, 715): a row's `at` says how far forward it is. */
34 #tick = 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.Compare35 /**
36 * The keys written or removed in each open transaction, innermost last (abso Capacity). A rollback drops only those:
37 * every projection scratch scope ends in a rollback, and dropping the whole cache there read the same rows from
38 * storage again within a call and on every call of a kept reader.
39 */
40 readonly #touched: Set<string>[] = [];
41 /**
42 * The biggest one row may be and still be kept (abso Capacity). A few big rows read on every call (each agent with
43 * all the news it was told: 4.3 MB for abso's 109 agents) otherwise push every small page out of the cache.
44 */
45 readonly #maxEntryBytes: number;
capacity260The writer cache stops reading layout pages straight through (abso Capacity, issue 664).
258 read file-lines, file-texts and file-deletes pages straight through the writer cache. A kept reader didn't gain from it (an agent's tree's time was elsewhere: counting authors line by line, fixed in the same version), and adoption, which lays the same files out in a fresh view for each version, lost the cache it relied on: a fresh abso adoption took 17.4 min with it against 11.6 min without (my machine). The option, its wiring and its test are gone; 258's told buckets and author counting stay.
Tests: all of src/engine/test and worker/project/test pass.Compare46 constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096, maxEntryBytes = maxBytes) {
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.Compare47 if (
48 !Number.isSafeInteger(maxBytes) ||
49 maxBytes < 0 ||
50 !Number.isSafeInteger(maxEntries) ||
51 maxEntries < 0 ||
52 !Number.isSafeInteger(maxEntryBytes) ||
53 maxEntryBytes < 0
54 )
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare55 throw new Error("invalid writer cache limits");
56 this.#source = source;
57 this.#maxBytes = maxBytes;
58 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.Compare59 this.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare60 }
61 get retainedBytes(): number {
62 return this.#bytes;
63 }
64 get retainedEntries(): number {
65 return this.#cache.size;
66 }
67 clear(): void {
68 this.#cache.clear();
69 this.#bytes = 0;
70 }
71 #drop(key: string): void {
72 const previous = this.#cache.get(key);
73 if (previous) {
74 this.#cache.delete(key);
75 this.#bytes -= previous.bytes;
76 }
77 }
78 read(collection: string, key: string): unknown {
79 const cacheKey = JSON.stringify([collection, key]);
80 const hit = this.#cache.get(cacheKey);
81 if (hit) {
perfdraft82 // Back to the end only from the older half (abso - Performance, 715): moving on every hit cost about 5 us a
83 // read in a 16,384-row Map, most of a cold collisions call on typescript-rs. A row in the newer half is
84 // evicted after every row in the older half anyway.
85 if (this.#tick - (hit.at ?? 0) > this.#cache.size / 2) {
86 this.#cache.delete(cacheKey);
87 this.#cache.set(cacheKey, hit);
88 hit.at = ++this.#tick;
89 }
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare90 if (hit.kind === "scalar") return hit.value;
91 if (hit.kind === "numbers") return hit.value.slice();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare92 return (JSON.parse(hit.json) as { value?: unknown }).value;
93 }
94 const value = this.#source.read(collection, key);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare95 const overhead = 2 * cacheKey.length + 160;
96 let entry: CachedValue;
97 if (
98 value === undefined ||
99 value === null ||
100 typeof value === "string" ||
101 typeof value === "boolean" ||
102 (typeof value === "number" && Number.isFinite(value))
103 ) {
104 entry = { kind: "scalar", value, bytes: overhead + (typeof value === "string" ? 2 * value.length : 16) };
105 } else if (
106 Array.isArray(value) &&
107 value.length <= 256 &&
108 Object.keys(value).length === value.length &&
109 value.every(Number.isSafeInteger)
110 ) {
111 // Store one private, bounded numeric page. Public reads still receive a
112 // fresh copy; neither the source result nor a reader can mutate the cache.
113 entry = { kind: "numbers", value: value.slice(), bytes: overhead + 32 + value.length * 8 };
114 } else {
115 const json = JSON.stringify({ value });
116 entry = { kind: "json", json, bytes: overhead + 2 * json.length };
117 }
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare118 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.Compare119 // A projection scope's own rows are never read again once it ends in its rollback: forget them with it.
120 if (collection.startsWith("projection-scratch:")) this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare121 return value;
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare122 }
123 #remember(cacheKey: string, entry: CachedValue): void {
124 this.#drop(cacheKey);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare125 // 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.Compare126 if (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) {
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare127 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare128 this.#drop(this.#cache.keys().next().value!);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare130 this.#cache.set(cacheKey, entry);
131 this.#bytes += entry.bytes;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare132 }
133 }
134 write(collection: string, key: string, value: unknown): void {
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare135 const cacheKey = JSON.stringify([collection, key]);
136 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.Compare137 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare138 this.#source.write(collection, key, value);
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare139 // Allocation counters are immutable scalars. Keep successful writes within
140 // the existing cache budget instead of immediately reading them back.
141 if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0))
142 this.#remember(cacheKey, { kind: "scalar", value, bytes: 2 * cacheKey.length + 176 });
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare143 }
144 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.Compare145 const cacheKey = JSON.stringify([collection, key]);
146 this.#drop(cacheKey);
147 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare148 this.#source.remove(collection, key);
149 }
150 entries(collection: string): Iterable<readonly [string, unknown]> {
151 return this.#source.entries(collection);
152 }
153 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.Compare154 const touched = new Set<string>();
155 this.#touched.push(touched);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare156 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.Compare157 const result = this.#source.transaction(body);
158 this.#touched.pop();
159 // Committed into the outer transaction, which may still roll back.
160 const outer = this.#touched.at(-1);
161 if (outer) for (const key of touched) outer.add(key);
162 return result;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare163 } 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.Compare164 this.#touched.pop();
165 // What the transaction wrote, and anything read back after it wrote it, is gone with the rollback.
166 for (const key of touched) this.#drop(key);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare167 throw error;
168 }
169 }
170}
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.Compare172/**
173 * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project
174 * given one skips proving it again, which read every atom and every dependency in the history.
175 */
176const closedSets = new WeakSet<object>();
177export function markClosed<S extends ReadonlySet<unknown>>(set: S): S {
178 closedSets.add(set);
179 return set;
180}
181export function isClosedSet(set: unknown): boolean {
182 return typeof set === "object" && set !== null && closedSets.has(set);
183}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare185/** Immutable membership whose implementation does not retain its enumerated keys. */
186export abstract class StableSet<T> implements ReadonlySet<T> {
187 abstract has(value: T): boolean;
188 abstract values(): SetIterator<T>;
189 /** Only resident membership data; external storage is not charged as heap. */
190 abstract readonly retainedBytes: number;
191 get [Symbol.toStringTag](): string {
192 return "Set";
193 }
194 get size(): number {
195 let count = 0;
196 for (const _ of this) count++;
197 return count;
198 }
199 keys(): SetIterator<T> {
200 return this.values();
201 }
202 *entries(): SetIterator<[T, T]> {
203 for (const value of this) yield [value, value];
204 }
205 [Symbol.iterator](): SetIterator<T> {
206 return this.values();
207 }
208 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
209 for (const value of this) callback.call(thisArg, value, value, this);
210 }
211}
213/** Both operands must be immutable for the lifetime of this union. */
214export class StableUnionSet<T> extends StableSet<T> {
215 readonly #left: StableSet<T>;
216 readonly #right: StableSet<T>;
217 constructor(left: StableSet<T>, right: StableSet<T>) {
218 super();
219 this.#left = left;
220 this.#right = right;
221 }
222 get retainedBytes(): number {
223 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.Compare224 }
225 get left(): StableSet<T> {
226 return this.#left;
227 }
228 get right(): StableSet<T> {
229 return this.#right;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare230 }
231 has(value: T): boolean {
232 return this.#left.has(value) || this.#right.has(value);
233 }
234 *values(): SetIterator<T> {
235 yield* this.#left;
236 for (const value of this.#right) if (!this.#left.has(value)) yield value;
237 }
238}
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare240/** Immutable indexed subtraction retains neither operand's enumerated values. */
241export class StableDifferenceSet<T> extends StableSet<T> {
242 readonly left: StableSet<T>;
243 readonly right: StableSet<T>;
244 constructor(left: StableSet<T>, right: StableSet<T>) {
245 super();
246 this.left = left;
247 this.right = right;
248 }
249 get retainedBytes(): number {
250 return 32 + this.left.retainedBytes + this.right.retainedBytes;
251 }
252 has(value: T): boolean {
253 return this.left.has(value) && !this.right.has(value);
254 }
255 *values(): SetIterator<T> {
256 for (const value of this.left) if (!this.right.has(value)) yield value;
257 }
258}
260/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
261export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
262 return base instanceof StableSet
263 ? new StableUnionSet(base, new StableOverlaySet(overlay))
264 : new Set([...base, ...overlay]);
265}
267/** Both indexed operands must be immutable for the lifetime of the result. */
268export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
269 return left instanceof StableSet && right instanceof StableSet
270 ? new StableDifferenceSet(left, right)
271 : new Set([...left].filter((value) => !right.has(value)));
272}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare274/** An immutable snapshot for the operation's small overlay, not its history. */
275export class StableOverlaySet<T> extends StableSet<T> {
276 readonly #values: Set<T>;
277 constructor(values: Iterable<T>) {
278 super();
279 this.#values = new Set(values);
280 }
281 get retainedBytes(): number {
282 return 64 + this.#values.size * 32;
283 }
284 has(value: T): boolean {
285 return this.#values.has(value);
286 }
287 values(): SetIterator<T> {
288 return this.#values.values();
289 }
290}
292const indexKey = (key: PropertyKey): key is string =>
293 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 cacheCompare295/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
296export function storedNumbers(storage: GraphStateStorage, name: string) {
297 const pageSize = 256;
298 const meta = `${name}:meta`;
299 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
300 // Older experimental writer indexes must be rebuilt from their canonical log.
301 // Never interpret per-element rows as pages or silently lose existing history.
302 const page = (index: number): number[] => {
303 if (storage.read(meta, "format") !== 2)
304 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
305 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
306 if (!values) throw new Error(`missing writer numeric page in ${name}`);
307 return values;
308 };
309 return {
310 get length() {
311 return length();
312 },
313 at(index: number): number {
314 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
315 throw new Error(`writer numeric index out of bounds in ${name}`);
316 const value = page(index)[index % pageSize];
317 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
318 return value;
319 },
320 push(value: number): void {
321 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
322 const index = length();
323 if (index > 0 && storage.read(meta, "format") !== 2)
324 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
325 const offset = index % pageSize;
326 const values = offset === 0 ? [] : page(index);
327 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
328 values.push(value);
329 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
330 if (index === 0) storage.write(meta, "format", 2);
331 storage.write(meta, "length", index + 1);
332 },
333 set(index: number, value: number): void {
334 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
335 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
336 throw new Error(`writer numeric index out of bounds in ${name}`);
337 const values = page(index);
338 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
339 values[index % pageSize] = value;
340 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
341 },
342 };
343}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare345/** 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 gateCompare346export function storedArray<T>(
347 storage: GraphStateStorage,
348 name: string,
349 decode?: (value: T) => T,
350 encode?: (value: T, key: string) => unknown,
351): T[] {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare352 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
353 const read = (key: string) => {
354 const value = storage.read(name, key) as T;
355 return value === undefined || !decode ? value : decode(value);
356 };
357 return new Proxy([] as T[], {
358 get(target, key, receiver) {
359 if (key === "length") return length();
capacity274Cold reads (abso Capacity, issue 664): a packed layout reads only the text pages holding a line it shows; definition code stays in memory up to 4 MB; a stored array's element read skips its length read.
- Layout: each line's file and place are kept and texts are read after the walk, a page at a time, only for shown lines. Every text a file and the files its moved-in lines came from ever had was read for every layout; abso's worker files, split out of index.ts, each read all of index.ts's history. Cold compare 612 to 1224 on abso read text pages 17,080 times, now 2,856.
- Definition code: at 64 KB every large file's parsed code went row by row into scratch and back (25,000 rows each for index.ts). The visible lines are already in memory, so 4 MB at most doubles a file's text for the call. withDefinitionCode takes the limit; its scratch test passes 64 KB.
- storedArray: set writes the row and the length together and nothing shrinks, so no row lies past the length; half of a cold layout's reads were the length.
Side by side on abso's export, same machine, three rounds: cold collisions 10.5 s to 6.2 s, cold compare 12.6 s to 8.6 s. tsc clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, definition-code, definitions, changed-definition, collisions-kept-views and draft-reads-stored tests: 73 pass.Compare360 // No length read first (abso Capacity): set writes the row and the length together and nothing shrinks, so no
361 // row lies past the length. Half of a cold layout's reads were this length.
362 if (indexKey(key)) return read(key);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare363 return Reflect.get(target, key, receiver);
364 },
365 set(_target, key, value) {
366 if (key === "length") {
367 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
368 return true;
369 }
370 if (!indexKey(key)) throw new Error("invalid stored graph array property");
371 const index = Number(key);
372 const size = length();
373 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 gateCompare374 storage.write(name, key, encode ? encode(value, key) : value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare375 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
376 return true;
377 },
378 has(target, key) {
379 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
380 },
381 ownKeys() {
382 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
383 },
384 getOwnPropertyDescriptor(target, key) {
385 if (indexKey(key) && Number(key) < length())
386 return { configurable: true, enumerable: true, writable: true, value: read(key) };
387 return Reflect.getOwnPropertyDescriptor(target, key);
388 },
389 });
390}
392export interface StateMap<K, V> {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare393 keys(): IterableIterator<K>;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare394 get(key: K): V | undefined;
395 set(key: K, value: V): StateMap<K, V>;
396 has(key: K): boolean;
397 delete(key: K): boolean;
398 values(): IterableIterator<V>;
399}
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare401/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare402export function storedLists<V>(
403 storage: GraphStateStorage,
404 name: string,
405 legacyKey = (key: string) => JSON.stringify(["string", key]),
406) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare407 const pageSize = 256;
408 // The previous experimental layout stored one whole historical list per key.
409 const length = (key: string) => {
410 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare411 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare412 throw new Error(`writer list index ${name} requires canonical-log adoption`);
413 const count = stored ?? 0;
414 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
415 return count;
416 };
417 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
418 const page = (key: string, index: number): V[] => {
419 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
420 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
421 throw new Error(`missing or invalid writer list page in ${name}`);
422 return values;
423 };
424 return {
425 length,
426 *keys(): IterableIterator<string> {
427 for (const entry of storage.entries(name)) {
428 void entry;
429 throw new Error(`writer list index ${name} requires canonical-log adoption`);
430 }
431 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
capacity274Cold reads (abso Capacity, issue 664): a packed layout reads only the text pages holding a line it shows; definition code stays in memory up to 4 MB; a stored array's element read skips its length read.
- Layout: each line's file and place are kept and texts are read after the walk, a page at a time, only for shown lines. Every text a file and the files its moved-in lines came from ever had was read for every layout; abso's worker files, split out of index.ts, each read all of index.ts's history. Cold compare 612 to 1224 on abso read text pages 17,080 times, now 2,856.
- Definition code: at 64 KB every large file's parsed code went row by row into scratch and back (25,000 rows each for index.ts). The visible lines are already in memory, so 4 MB at most doubles a file's text for the call. withDefinitionCode takes the limit; its scratch test passes 64 KB.
- storedArray: set writes the row and the length together and nothing shrinks, so no row lies past the length; half of a cold layout's reads were the length.
Side by side on abso's export, same machine, three rounds: cold collisions 10.5 s to 6.2 s, cold compare 12.6 s to 8.6 s. tsc clean; view, state-cache, state-source, graph, graph-long-text, graph-line-chunks, graph-move-write-membership, definition-code, definitions, changed-definition, collisions-kept-views and draft-reads-stored tests: 73 pass.Compare432 },
433 /** Values [index * PAGE, (index + 1) * PAGE) of `key`'s list: one page, not the whole list (abso Capacity). */
434 pageAt(key: string, index: number): readonly V[] {
435 const count = length(key);
436 const values = page(key, index);
437 if (values.length !== Math.min(pageSize, count - index * pageSize))
438 throw new Error(`incomplete writer list page in ${name}`);
439 return values;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare440 },
441 *values(key: string): IterableIterator<V> {
442 const count = length(key);
443 for (let start = 0; start < count; start += pageSize) {
444 const values = page(key, start / pageSize);
445 if (values.length !== Math.min(pageSize, count - start))
446 throw new Error(`incomplete writer list page in ${name}`);
447 yield* values;
448 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare449 },
450 last(key: string): V | undefined {
451 const count = length(key);
452 if (count === 0) return undefined;
453 const values = page(key, Math.floor((count - 1) / pageSize));
454 const expected = ((count - 1) % pageSize) + 1;
455 if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);
456 return values[expected - 1];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare457 },
458 append(key: string, value: V): void {
459 const count = length(key);
460 const offset = count % pageSize;
461 const index = Math.floor(count / pageSize);
462 const values = offset === 0 ? [] : page(key, index);
463 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
464 values.push(value);
465 storage.write(`${name}:pages`, pageKey(key, index), values);
466 storage.write(`${name}:lengths`, key, count + 1);
467 },
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.Compare468 /** Append several values, writing each page they touch once. */
469 appendAll(key: string, more: readonly V[]): void {
470 if (more.length === 0) return;
471 const count = length(key);
472 let index = Math.floor(count / pageSize);
473 let values = count % pageSize === 0 ? [] : page(key, index);
474 if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);
475 for (const value of more) {
476 if (values.length === pageSize) {
477 storage.write(`${name}:pages`, pageKey(key, index++), values);
478 values = [];
479 }
480 values.push(value);
481 }
482 storage.write(`${name}:pages`, pageKey(key, index), values);
483 storage.write(`${name}:lengths`, key, count + more.length);
484 },
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare485 };
486}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare488/** Keys are tagged so numeric graph codes cannot collide with string keys. */
489export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
490 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
491 const map: StateMap<K, V> = {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare492 *keys() {
493 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
494 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare495 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
496 has: (key) => storage.read(name, keyOf(key)) !== undefined,
497 set(key, value) {
498 storage.write(name, keyOf(key), value);
499 return map;
500 },
501 delete(key) {
502 const existed = map.has(key);
503 storage.remove(name, keyOf(key));
504 return existed;
505 },
506 *values() {
507 for (const [, value] of storage.entries(name)) yield value as V;
508 },
509 };
510 return map;
511}
513/**
514 * A Map-compatible persistent index. Iteration follows insertion order and
515 * decodes one row at a time. Returned objects are copies, so mutations need
516 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
517 */
518export class StoredMap<K extends string | number, V> extends Map<K, V> {
519 readonly #storage: GraphStateStorage;
520 readonly #name: string;
521 readonly #encode: (value: V) => unknown;
522 readonly #decode: (value: unknown) => V;
523 constructor(
524 storage: GraphStateStorage,
525 name: string,
526 codec?: { encode(value: V): unknown; decode(value: unknown): V },
527 ) {
528 super();
529 this.#storage = storage;
530 this.#name = name;
531 this.#encode = codec?.encode ?? ((value) => value);
532 this.#decode = codec?.decode ?? ((value) => value as V);
533 }
534 #key(key: K): string {
535 return JSON.stringify([typeof key, key]);
536 }
537 #row(key: K): { slot: number; value: unknown } | undefined {
538 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
539 }
540 override get size(): number {
541 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
542 }
543 override has(key: K): boolean {
544 return this.#row(key) !== undefined;
545 }
546 override get(key: K): V | undefined {
547 const row = this.#row(key);
548 return row === undefined ? undefined : this.#decode(row.value);
549 }
550 override set(key: K, value: V): this {
551 const row = this.#row(key);
552 let slot = row?.slot;
553 if (slot === undefined) {
554 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
555 slot = keys.length;
556 keys.push(key);
557 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
558 }
559 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
560 return this;
561 }
562 override delete(key: K): boolean {
563 if (!this.has(key)) return false;
564 this.#storage.remove(this.#name, this.#key(key));
565 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
566 return true;
567 }
568 override clear(): void {
569 for (const key of this.keys()) this.delete(key);
570 }
571 override *entries(): MapIterator<[K, V]> {
572 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
573 for (let slot = 0; slot < keys.length; slot++) {
574 const key = keys[slot]!;
575 const row = this.#row(key);
576 if (row?.slot === slot) yield [key, this.#decode(row.value)];
577 }
578 }
579 override *keys(): MapIterator<K> {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare580 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
581 for (let slot = 0; slot < keys.length; slot++) {
582 const key = keys[slot]!;
583 if (this.#row(key)?.slot === slot) yield key;
584 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare585 }
586 override *values(): MapIterator<V> {
587 for (const [, value] of this.entries()) yield value;
588 }
589 override [Symbol.iterator](): MapIterator<[K, V]> {
590 return this.entries();
591 }
592 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
593 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
594 }
595}
597/** Persistent membership with streaming iteration and no in-memory key cache. */
598export class StoredSet<K extends string | number> extends Set<K> {
599 readonly #map: StoredMap<K, true>;
600 constructor(storage: GraphStateStorage, name: string) {
601 super();
602 this.#map = new StoredMap(storage, name);
603 }
604 override get size(): number {
605 return this.#map.size;
606 }
607 override has(key: K): boolean {
608 return this.#map.has(key);
609 }
610 override add(key: K): this {
611 this.#map.set(key, true);
612 return this;
613 }
614 override delete(key: K): boolean {
615 return this.#map.delete(key);
616 }
617 override clear(): void {
618 this.#map.clear();
619 }
620 override *values(): SetIterator<K> {
621 yield* this.#map.keys();
622 }
623 override keys(): SetIterator<K> {
624 return this.values();
625 }
626 override *entries(): SetIterator<[K, K]> {
627 for (const key of this.values()) yield [key, key];
628 }
629 override [Symbol.iterator](): SetIterator<K> {
630 return this.values();
631 }
632 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
633 for (const key of this.values()) callback.call(thisArg, key, key, this);
634 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare635}
637/** 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.Compare638/** How many values an atom's long list keeps to a row (readonlyPagedArray). */
639export const LIST_PAGE = 256;
641/** Write a list as readonlyPagedArray reads it: its values LIST_PAGE to a row, and its length. */
642export function writePagedArray(storage: GraphStateStorage, name: string, values: readonly unknown[]): void {
643 for (let start = 0; start < values.length; start += LIST_PAGE)
644 storage.write(`${name}:pages`, String(start / LIST_PAGE), values.slice(start, start + LIST_PAGE));
645 storage.write(`${name}:meta`, "length", values.length);
646}
648/**
649 * A stored list read a page of LIST_PAGE values at a time (abso Capacity): an atom's long lists, which
650 * readonlyStoredArray reads a row per value. Collisions read every key a draft's atoms write; a draft deleting a big
651 * file has thousands, and that was a row each.
652 */
653export function readonlyPagedArray<T>(storage: GraphStateStorage, name: string): readonly T[] {
654 const length = () => {
655 const count = storage.read(`${name}:meta`, "length");
656 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
657 return count as number;
658 };
659 length();
660 let held = -1;
661 let page: readonly unknown[] = [];
662 const at = (index: number): T => {
663 const p = Math.floor(index / LIST_PAGE);
664 if (p !== held) {
665 const raw = storage.read(`${name}:pages`, String(p));
666 if (!Array.isArray(raw)) throw Error("missing stored list page");
667 page = raw;
668 held = p;
669 }
670 const value = page[index % LIST_PAGE];
671 if (value === undefined) throw Error("missing stored list element");
672 return (value && typeof value === "object" ? Object.freeze(value) : value) as T;
673 };
674 function* inOrder(): IterableIterator<T> {
675 const count = length();
676 for (let index = 0; index < count; index++) yield at(index);
677 }
678 return new Proxy([] as T[], {
679 get(target, key, receiver) {
680 if (key === "length") return length();
681 if (key === Symbol.iterator || key === "values") return inOrder;
682 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
683 return Reflect.get(target, key, receiver);
684 },
685 has(target, key) {
686 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
687 },
688 ownKeys() {
689 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
690 },
691 getOwnPropertyDescriptor(target, key) {
692 if (indexKey(key) && Number(key) < length())
693 return { configurable: true, enumerable: true, writable: false, value: at(Number(key)) };
694 return Reflect.getOwnPropertyDescriptor(target, key);
695 },
696 set() {
697 throw Error("stored lists are read-only");
698 },
699 });
700}
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare702export function readonlyStoredArray<T>(
703 storage: GraphStateStorage,
704 name: string,
705 decode?: (value: unknown, index: number) => T,
706): readonly T[] {
707 const length = () => {
708 const count = storage.read(`${name}:meta`, "length");
709 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
710 return count as number;
711 };
712 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 changesCompare713 const at = (index: number): T => {
714 const raw = storage.read(name, String(index));
715 const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T);
716 if (value === undefined) throw Error("missing stored list element");
717 return value && typeof value === "object" ? (Object.freeze(value) as T) : value;
718 };
719 // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a
720 // second disk read per element of a list too long for the cache.
721 function* inOrder(): IterableIterator<T> {
722 const count = length();
723 for (let index = 0; index < count; index++) yield at(index);
724 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare725 return new Proxy([] as T[], {
726 get(target, key, receiver) {
727 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 changesCompare728 if (key === Symbol.iterator || key === "values") return inOrder;
729 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 gateCompare730 return Reflect.get(target, key, receiver);
731 },
732 has(target, key) {
733 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
734 },
735 ownKeys() {
736 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
737 },
738 getOwnPropertyDescriptor(target, key) {
739 if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };
740 if (indexKey(key) && Number(key) < length()) {
741 const raw = storage.read(name, key);
742 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
743 if (value === undefined) throw Error("missing stored list element");
744 return {
745 configurable: true,
746 enumerable: true,
747 writable: false,
748 value: value && typeof value === "object" ? Object.freeze(value) : value,
749 };
750 }
751 return Reflect.getOwnPropertyDescriptor(target, key);
752 },
753 preventExtensions() {
754 throw Error("stored list is read-only");
755 },
756 set() {
757 throw Error("stored list is read-only");
758 },
759 deleteProperty() {
760 throw Error("stored list is read-only");
761 },
762 defineProperty() {
763 throw Error("stored list is read-only");
764 },
765 });