- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/state-source.ts?draft=perf-cache-older-half&format=json
766 linescodex-capacity-chair 77% · capacity 21% · perf 2%Last change perf in version 1, 1 version changed it
codex-capacity-policy has unpushed changes at lines 1–25no start notelast edit
1/**
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}
16/**
17 * 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
19 * rollback or any mutation made through another storage instance.
20 */
21type CachedValue = { bytes: number; at?: number } & (
22 | { kind: "scalar"; value: string | number | boolean | null | undefined }
23 | { kind: "numbers"; value: readonly number[] }
24 | { kind: "json"; json: string }
25);
27export class CachedStateStorage implements GraphStateStorage {
28 readonly #source: GraphStateStorage;
29 readonly #cache = new Map<string, CachedValue>();
30 readonly #maxBytes: number;
31 readonly #maxEntries: number;
32 #bytes = 0;
33 /** 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;
35 /**
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;
46 constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096, maxEntryBytes = maxBytes) {
47 if (
48 !Number.isSafeInteger(maxBytes) ||
49 maxBytes < 0 ||
50 !Number.isSafeInteger(maxEntries) ||
51 maxEntries < 0 ||
52 !Number.isSafeInteger(maxEntryBytes) ||
53 maxEntryBytes < 0
54 )
55 throw new Error("invalid writer cache limits");
56 this.#source = source;
57 this.#maxBytes = maxBytes;
58 this.#maxEntries = maxEntries;
59 this.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes);
60 }
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) {
82 // 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 }
90 if (hit.kind === "scalar") return hit.value;
91 if (hit.kind === "numbers") return hit.value.slice();
92 return (JSON.parse(hit.json) as { value?: unknown }).value;
93 }
94 const value = this.#source.read(collection, key);
95 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 }
118 this.#remember(cacheKey, entry);
119 // 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);
121 return value;
122 }
123 #remember(cacheKey: string, entry: CachedValue): void {
124 this.#drop(cacheKey);
125 // Payload accounting is bounded, not a measurement of actual isolate heap.
126 if (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) {
127 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
128 this.#drop(this.#cache.keys().next().value!);
129 entry.at = ++this.#tick;
130 this.#cache.set(cacheKey, entry);
131 this.#bytes += entry.bytes;
132 }
133 }
134 write(collection: string, key: string, value: unknown): void {
135 const cacheKey = JSON.stringify([collection, key]);
136 this.#drop(cacheKey);
137 this.#touched.at(-1)?.add(cacheKey);
138 this.#source.write(collection, key, value);
139 // 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 });
143 }
144 remove(collection: string, key: string): void {
145 const cacheKey = JSON.stringify([collection, key]);
146 this.#drop(cacheKey);
147 this.#touched.at(-1)?.add(cacheKey);
148 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 {
154 const touched = new Set<string>();
155 this.#touched.push(touched);
156 try {
157 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;
163 } catch (error) {
164 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);
167 throw error;
168 }
169 }
170}
172/**
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}
185/** 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;
224 }
225 get left(): StableSet<T> {
226 return this.#left;
227 }
228 get right(): StableSet<T> {
229 return this.#right;
230 }
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}
240/** 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}
274/** 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));
295/** 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}
345/** Array-shaped access without retaining its historical values in memory. */
346export function storedArray<T>(
347 storage: GraphStateStorage,
348 name: string,
349 decode?: (value: T) => T,
350 encode?: (value: T, key: string) => unknown,
351): T[] {
352 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();
360 // 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);
363 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");
374 storage.write(name, key, encode ? encode(value, key) : value);
375 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> {
393 keys(): IterableIterator<K>;
394 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}
401/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
402export function storedLists<V>(
403 storage: GraphStateStorage,
404 name: string,
405 legacyKey = (key: string) => JSON.stringify(["string", key]),
406) {
407 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;
411 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
412 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;
432 },
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;
440 },
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 }
449 },
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];
457 },
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 },
468 /** 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 },
485 };
486}
488/** 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> = {
492 *keys() {
493 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
494 },
495 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> {
580 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 }
585 }
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 }
635}
637/** Read-only array access to individually stored values, without copying the list. */
638/** 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}
702export 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();
713 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 }
725 return new Proxy([] as T[], {
726 get(target, key, receiver) {
727 if (key === "length") return length();
728 if (key === Symbol.iterator || key === "values") return inOrder;
729 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
730 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 });
766}