Skip to content

abso-core

Public
Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/ordered-index.ts?format=json
152 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 131, 1 version changed it
1import type { GraphStateStorage } from "./state-source.ts";
2
3const WIDTH = 57;
4type Leaf = { prefix: string; value: number };
5type Branch = { prefix: string; children: (number | null)[] };
6type Node = Leaf | Branch;
7const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
8
9/** Exact existing layout priority, encoded for ascending lexical traversal. */
10export function orderedChildKey(child: {
11 replaces: number;
12 lamport: number;
13 seq: number;
14 k: number;
15 n: number;
16}): string {
17 if (![child.lamport, child.seq, child.k, child.n].every(safe) || ![0, 1].includes(child.replaces))
18 throw new Error("invalid ordered child priority");
19 const hex = (n: number) => n.toString(16).padStart(14, "0");
20 return `${1 - child.replaces}${hex(Number.MAX_SAFE_INTEGER - child.lamport)}${hex(Number.MAX_SAFE_INTEGER - child.seq)}${hex(child.k)}${hex(child.n)}`;
23/** Compressed radix tree with at most 16 references per node and 57 levels.
24 * No collection scan or history-sized sibling array is needed. Values are
25 * immutable numeric identities; the caller owns namespace isolation. */
26export class OrderedIndex {
27 readonly #storage: GraphStateStorage;
28 readonly #collection: string;
29 readonly #group: string;
30 constructor(storage: GraphStateStorage, collection: string, group: string) {
31 this.#storage = storage;
32 this.#collection = collection;
33 this.#group = group;
34 }
35 #key(id: number | "meta"): string {
36 return JSON.stringify([this.#group, id]);
37 }
38 #next(): number | undefined {
39 const meta = this.#storage.read(this.#collection, this.#key("meta")) as
40 | { format?: unknown; next?: unknown; count?: unknown }
41 | undefined;
42 if (meta === undefined) {
43 if (this.#storage.read(this.#collection, this.#key(0)) !== undefined)
44 throw new Error("missing ordered index metadata");
45 return undefined;
46 }
47 if (
48 meta?.format !== 1 ||
49 !safe(meta.next) ||
50 meta.next < 1 ||
51 !safe(meta.count) ||
52 meta.count < 1 ||
53 meta.count > meta.next
54 )
55 throw new Error("invalid ordered index metadata");
56 return meta.next;
57 }
58 get size(): number {
59 if (this.#next() === undefined) return 0;
60 return (this.#storage.read(this.#collection, this.#key("meta")) as { count: number }).count;
61 }
62 #write(id: number, node: Node): void {
63 this.#storage.write(this.#collection, this.#key(id), node);
64 }
65 #read(id: number, expected: string): Node {
66 const node = this.#storage.read(this.#collection, this.#key(id)) as Node | undefined;
67 if (
68 !node ||
69 typeof node.prefix !== "string" ||
70 !/^[0-9a-f]*$/.test(node.prefix) ||
71 node.prefix.length > WIDTH ||
72 !node.prefix.startsWith(expected)
73 )
74 throw new Error("invalid ordered index node");
75 if ("value" in node) {
76 if (node.prefix.length !== WIDTH || !safe(node.value) || "children" in node)
77 throw new Error("invalid ordered index leaf");
78 } else if (
79 node.prefix.length >= WIDTH ||
80 !Array.isArray(node.children) ||
81 node.children.length !== 16 ||
82 !node.children.every((id) => id === null || safe(id)) ||
83 node.children.filter((id) => id !== null).length < 2
84 ) {
85 throw new Error("invalid ordered index branch");
86 }
87 return node;
88 }
89 /** Nested host transactions must roll back all allocation, split and link writes. */
90 insert(key: string, value: number): void {
91 if (key.length !== WIDTH || !/^[0-9a-f]+$/.test(key) || !safe(value))
92 throw new Error("invalid ordered index entry");
93 this.#storage.transaction(() => {
94 let next = this.#next();
95 let count = this.size;
96 if (next === undefined) {
97 this.#write(0, { prefix: key, value });
98 this.#storage.write(this.#collection, this.#key("meta"), { format: 1, next: 1, count: 1 });
99 return;
100 }
101 const allocate = (node: Node): number => {
102 if (next! >= Number.MAX_SAFE_INTEGER) throw new Error("ordered index identity exhausted");
103 const id = next!++;
104 this.#write(id, node);
105 return id;
106 };
107 const add = (id: number, expected: string): void => {
108 const node = this.#read(id, expected);
109 let common = 0;
110 while (common < node.prefix.length && node.prefix[common] === key[common]) common++;
111 if (common < node.prefix.length) {
112 count++;
113 const children: (number | null)[] = Array(16).fill(null);
114 children[parseInt(node.prefix[common]!, 16)] = allocate(node);
115 children[parseInt(key[common]!, 16)] = allocate({ prefix: key, value });
116 this.#write(id, { prefix: key.slice(0, common), children });
117 } else if ("value" in node) {
118 if (node.value !== value) throw new Error("ordered index key reused");
119 } else {
120 const digit = parseInt(key[common]!, 16);
121 const child = node.children[digit]!;
122 if (child === null) {
123 count++;
124 node.children[digit] = allocate({ prefix: key, value });
125 this.#write(id, node);
126 } else add(child, node.prefix + key[common]);
127 }
128 };
129 add(0, "");
130 this.#storage.write(this.#collection, this.#key("meta"), { format: 1, next, count });
131 });
132 }
133 *values(after?: string): IterableIterator<number> {
134 if (after !== undefined && (after.length !== WIDTH || !/^[0-9a-f]+$/.test(after)))
135 throw new Error("invalid ordered index cursor");
136 if (this.#next() === undefined) return;
137 const walk = function* (this: OrderedIndex, id: number, expected: string): IterableIterator<number> {
138 if (after !== undefined && expected < after.slice(0, expected.length)) return;
139 const node = this.#read(id, expected);
140 if (after !== undefined && node.prefix < after.slice(0, node.prefix.length)) return;
141 if ("value" in node) {
142 if (after === undefined || node.prefix > after) yield node.value;
143 return;
144 }
145 for (let digit = 0; digit < 16; digit++) {
146 const child = node.children[digit]!;
147 if (child !== null) yield* walk.call(this, child, node.prefix + digit.toString(16));
148 }
149 };
150 yield* walk.call(this, 0, "");
151 }