@hviana/sema 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/AGENTS.md +6 -5
  2. package/CITATION.cff +49 -0
  3. package/HOW_IT_WORKS.md +11 -12
  4. package/README.md +7 -5
  5. package/dist/example/demo.js +25 -25
  6. package/dist/example/train_base.d.ts +19 -21
  7. package/dist/example/train_base.js +1687 -1952
  8. package/dist/src/alphabet.d.ts +3 -3
  9. package/dist/src/alphabet.js +24 -27
  10. package/dist/src/alu/src/alu.d.ts +169 -194
  11. package/dist/src/alu/src/alu.js +374 -414
  12. package/dist/src/alu/src/expr.d.ts +36 -43
  13. package/dist/src/alu/src/expr.js +252 -278
  14. package/dist/src/alu/src/index.d.ts +9 -98
  15. package/dist/src/alu/src/index.js +10 -64
  16. package/dist/src/alu/src/kernel-arith.d.ts +1 -5
  17. package/dist/src/alu/src/kernel-arith.js +195 -285
  18. package/dist/src/alu/src/kernel-bits.d.ts +1 -5
  19. package/dist/src/alu/src/kernel-bits.js +81 -115
  20. package/dist/src/alu/src/kernel-logic.js +33 -63
  21. package/dist/src/alu/src/kernel-nd.js +155 -195
  22. package/dist/src/alu/src/kernel-numeric.d.ts +16 -80
  23. package/dist/src/alu/src/kernel-numeric.js +259 -331
  24. package/dist/src/alu/src/operation.d.ts +112 -132
  25. package/dist/src/alu/src/operation.js +149 -163
  26. package/dist/src/alu/src/parser.d.ts +168 -175
  27. package/dist/src/alu/src/parser.js +382 -421
  28. package/dist/src/alu/src/resonance.d.ts +16 -25
  29. package/dist/src/alu/src/resonance.js +49 -56
  30. package/dist/src/alu/src/text.d.ts +3 -7
  31. package/dist/src/alu/src/text.js +31 -37
  32. package/dist/src/alu/src/value.d.ts +14 -14
  33. package/dist/src/alu/src/value.js +150 -160
  34. package/dist/src/alu/test/alu.test.js +543 -656
  35. package/dist/src/bytes.d.ts +1 -5
  36. package/dist/src/bytes.js +33 -40
  37. package/dist/src/config.d.ts +99 -102
  38. package/dist/src/config.js +78 -83
  39. package/dist/src/derive/src/deduction.d.ts +60 -62
  40. package/dist/src/derive/src/deduction.js +103 -109
  41. package/dist/src/derive/src/index.d.ts +1 -7
  42. package/dist/src/derive/src/priority-queue.d.ts +8 -8
  43. package/dist/src/derive/src/priority-queue.js +57 -61
  44. package/dist/src/derive/src/rewrite.d.ts +15 -18
  45. package/dist/src/derive/src/rewrite.js +59 -67
  46. package/dist/src/derive/src/trie.d.ts +56 -56
  47. package/dist/src/derive/src/trie.js +175 -179
  48. package/dist/src/derive/test/derive.test.js +96 -100
  49. package/dist/src/extension.d.ts +13 -16
  50. package/dist/src/geometry.d.ts +17 -42
  51. package/dist/src/geometry.js +235 -266
  52. package/dist/src/index.d.ts +2 -17
  53. package/dist/src/index.js +2 -12
  54. package/dist/src/ingest-cache.d.ts +25 -30
  55. package/dist/src/ingest-cache.js +108 -127
  56. package/dist/src/mind/articulation.d.ts +1 -5
  57. package/dist/src/mind/articulation.js +77 -112
  58. package/dist/src/mind/attention.d.ts +40 -108
  59. package/dist/src/mind/attention.js +749 -871
  60. package/dist/src/mind/canonical.d.ts +4 -19
  61. package/dist/src/mind/canonical.js +27 -31
  62. package/dist/src/mind/graph-search.d.ts +201 -225
  63. package/dist/src/mind/graph-search.js +742 -821
  64. package/dist/src/mind/index.d.ts +2 -10
  65. package/dist/src/mind/junction.d.ts +31 -58
  66. package/dist/src/mind/junction.js +172 -237
  67. package/dist/src/mind/learning.d.ts +16 -52
  68. package/dist/src/mind/learning.js +143 -165
  69. package/dist/src/mind/match.d.ts +20 -69
  70. package/dist/src/mind/match.js +259 -318
  71. package/dist/src/mind/mechanisms/alu.js +16 -16
  72. package/dist/src/mind/mechanisms/cast.d.ts +9 -13
  73. package/dist/src/mind/mechanisms/cast.js +363 -456
  74. package/dist/src/mind/mechanisms/confluence.d.ts +8 -12
  75. package/dist/src/mind/mechanisms/confluence.js +152 -183
  76. package/dist/src/mind/mechanisms/cover.d.ts +2 -8
  77. package/dist/src/mind/mechanisms/cover.js +148 -210
  78. package/dist/src/mind/mechanisms/extraction.d.ts +8 -34
  79. package/dist/src/mind/mechanisms/extraction.js +234 -288
  80. package/dist/src/mind/mechanisms/recall.d.ts +6 -10
  81. package/dist/src/mind/mechanisms/recall.js +126 -185
  82. package/dist/src/mind/mind.d.ts +129 -154
  83. package/dist/src/mind/mind.js +258 -288
  84. package/dist/src/mind/pipeline-mechanism.d.ts +112 -124
  85. package/dist/src/mind/pipeline-mechanism.js +161 -172
  86. package/dist/src/mind/pipeline.d.ts +4 -14
  87. package/dist/src/mind/pipeline.js +125 -189
  88. package/dist/src/mind/primitives.d.ts +8 -32
  89. package/dist/src/mind/primitives.js +99 -117
  90. package/dist/src/mind/rationale.d.ts +86 -98
  91. package/dist/src/mind/rationale.js +113 -121
  92. package/dist/src/mind/reasoning.d.ts +2 -13
  93. package/dist/src/mind/reasoning.js +129 -166
  94. package/dist/src/mind/recognition.d.ts +1 -4
  95. package/dist/src/mind/recognition.js +183 -208
  96. package/dist/src/mind/resonance.d.ts +5 -22
  97. package/dist/src/mind/resonance.js +0 -0
  98. package/dist/src/mind/trace.d.ts +6 -25
  99. package/dist/src/mind/trace.js +50 -58
  100. package/dist/src/mind/traverse.d.ts +16 -58
  101. package/dist/src/mind/traverse.js +304 -357
  102. package/dist/src/mind/types.d.ts +120 -127
  103. package/dist/src/mind/types.js +60 -69
  104. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  105. package/dist/src/rabitq-ivf/src/database.js +201 -0
  106. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  107. package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/index.js +1 -3
  108. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  109. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  110. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  111. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  112. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  113. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  114. package/dist/src/sema.d.ts +9 -13
  115. package/dist/src/sema.js +26 -40
  116. package/dist/src/store-sqlite.d.ts +169 -166
  117. package/dist/src/store-sqlite.js +762 -662
  118. package/dist/src/store.d.ts +586 -630
  119. package/dist/src/store.js +1423 -1581
  120. package/dist/src/vec.d.ts +5 -9
  121. package/dist/src/vec.js +61 -73
  122. package/example/train_base.ts +13 -10
  123. package/package.json +1 -1
  124. package/src/alu/README.md +1 -1
  125. package/src/alu/src/index.ts +1 -1
  126. package/src/config.ts +19 -27
  127. package/src/index.ts +6 -11
  128. package/src/rabitq-ivf/README.md +56 -0
  129. package/src/rabitq-ivf/src/database.ts +276 -0
  130. package/src/{rabitq-hnsw → rabitq-ivf}/src/index.ts +2 -5
  131. package/src/rabitq-ivf/src/ivf.ts +1330 -0
  132. package/src/{rabitq-hnsw → rabitq-ivf}/src/prng.ts +1 -1
  133. package/src/store-sqlite.ts +196 -9
  134. package/src/store.ts +8 -32
  135. package/test/08-storage.test.mjs +3 -3
  136. package/test/14-scaling.test.mjs +2 -2
  137. package/test/35-ivf.test.mjs +263 -0
  138. package/test/36-bloom.test.mjs +123 -0
  139. package/dist/src/rabitq-hnsw/src/database.d.ts +0 -202
  140. package/dist/src/rabitq-hnsw/src/database.js +0 -405
  141. package/dist/src/rabitq-hnsw/src/heap.d.ts +0 -22
  142. package/dist/src/rabitq-hnsw/src/heap.js +0 -94
  143. package/dist/src/rabitq-hnsw/src/hnsw.d.ts +0 -125
  144. package/dist/src/rabitq-hnsw/src/hnsw.js +0 -500
  145. package/dist/src/rabitq-hnsw/src/index.d.ts +0 -15
  146. package/dist/src/rabitq-hnsw/src/prng.d.ts +0 -19
  147. package/dist/src/rabitq-hnsw/src/prng.js +0 -38
  148. package/dist/src/rabitq-hnsw/src/rabitq.d.ts +0 -95
  149. package/dist/src/rabitq-hnsw/src/rabitq.js +0 -299
  150. package/dist/src/rabitq-hnsw/src/store.d.ts +0 -162
  151. package/dist/src/rabitq-hnsw/src/store.js +0 -916
  152. package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +0 -1
  153. package/dist/src/rabitq-hnsw/test/hnsw.test.js +0 -1197
  154. package/src/rabitq-hnsw/README.md +0 -303
  155. package/src/rabitq-hnsw/src/database.ts +0 -492
  156. package/src/rabitq-hnsw/src/heap.ts +0 -90
  157. package/src/rabitq-hnsw/src/hnsw.ts +0 -514
  158. package/src/rabitq-hnsw/src/store.ts +0 -994
  159. package/src/rabitq-hnsw/test/hnsw.test.ts +0 -1213
  160. /package/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.ts +0 -0
@@ -1,405 +0,0 @@
1
- import { HnswIndex } from "./hnsw.js";
2
- import { RaBitQuantizer } from "./rabitq.js";
3
- import { Store } from "./store.js";
4
- const DEFAULTS = {
5
- M: 16,
6
- efConstruction: 200,
7
- efSearch: 100,
8
- queryBits: 8,
9
- rotationRounds: 3,
10
- seed: 0x1234abcd,
11
- };
12
- /**
13
- * A persistent vector database: an HNSW graph over 1-bit RaBitQ codes (cosine),
14
- * stored entirely in SQLite at `dbPath`. The graph IS the database -- there is no
15
- * load/save step and no in-RAM copy of the data, so resident memory stays flat as
16
- * the collection grows and the store survives process restarts. Reopening the
17
- * same path restores the exact configuration (the rotation is regenerated from
18
- * the persisted seed), so the codes already on disk remain valid.
19
- *
20
- * External ids are integers. The original float vectors are never retained --
21
- * only the sign codes -- so a 256-d vector costs 32 bytes instead of 1024. `get`
22
- * returns the stored code, which can be fed straight back into
23
- * `insert`/`update`/`query`.
24
- */
25
- export class VectorDatabase {
26
- dim;
27
- store;
28
- quantizer;
29
- index;
30
- codeWords;
31
- constructor(options) {
32
- if (
33
- !options || typeof options.dbPath !== "string" ||
34
- options.dbPath.length === 0
35
- ) {
36
- throw new Error("DatabaseOptions.dbPath (string) is required");
37
- }
38
- this.store = new Store(options.dbPath, options.cacheSizeMb ?? 64);
39
- let cfg = this.store.loadConfig();
40
- if (cfg === null) {
41
- // Fresh database: derive the configuration from the options and persist it.
42
- if (!Number.isInteger(options.dim) || options.dim <= 0) {
43
- throw new Error(
44
- "DatabaseOptions.dim must be a positive integer for a new database",
45
- );
46
- }
47
- const dim = options.dim;
48
- const centroid = options.centroid
49
- ? Float64Array.from(options.centroid)
50
- : null;
51
- const probe = new RaBitQuantizer(dim, { rounds: 1, seed: 0 });
52
- cfg = {
53
- dim,
54
- m: options.M ?? DEFAULTS.M,
55
- efConstruction: options.efConstruction ?? DEFAULTS.efConstruction,
56
- efSearch: options.efSearch ?? DEFAULTS.efSearch,
57
- queryBits: options.queryBits ?? DEFAULTS.queryBits,
58
- rotationRounds: options.rotationRounds ?? DEFAULTS.rotationRounds,
59
- seed: (options.seed ?? DEFAULTS.seed) >>> 0,
60
- centroid,
61
- codeWords: probe.codeWords,
62
- paddedDim: probe.paddedDim,
63
- };
64
- this.store.initConfig(cfg);
65
- } else {
66
- // Reopened: keep the stored STRUCTURAL config, but allow tuning the two
67
- // query-side knobs — efSearch and queryBits shape only how a query is
68
- // executed, never what is stored, so honouring an explicit option here
69
- // is safe and lets an existing database adopt better query settings.
70
- if (options.efSearch !== undefined) {
71
- cfg.efSearch = options.efSearch;
72
- this.store.setEfSearch(options.efSearch);
73
- }
74
- if (
75
- options.queryBits !== undefined && options.queryBits !== cfg.queryBits
76
- ) {
77
- cfg.queryBits = options.queryBits;
78
- this.store.setQueryBits(options.queryBits);
79
- }
80
- }
81
- this.dim = cfg.dim;
82
- this.quantizer = new RaBitQuantizer(cfg.dim, {
83
- queryBits: cfg.queryBits,
84
- rounds: cfg.rotationRounds,
85
- seed: cfg.seed,
86
- centroid: cfg.centroid ?? undefined,
87
- });
88
- if (this.quantizer.codeWords !== cfg.codeWords) {
89
- throw new Error(
90
- "Stored code geometry does not match the quantizer (corrupt database?)",
91
- );
92
- }
93
- this.codeWords = this.quantizer.codeWords;
94
- this.index = new HnswIndex(this.quantizer, this.store, {
95
- M: cfg.m,
96
- efConstruction: cfg.efConstruction,
97
- efSearch: cfg.efSearch,
98
- seed: cfg.seed,
99
- });
100
- }
101
- /** Number of live (non-deleted) vectors. */
102
- get size() {
103
- return this.index.size;
104
- }
105
- /**
106
- * Physical node count including tombstones from deletes/updates. When it grows
107
- * well beyond `size`, call `compact()` to reclaim the space on disk.
108
- */
109
- get physicalSize() {
110
- return this.index.physicalSize;
111
- }
112
- get efSearch() {
113
- return this.index.efSearch;
114
- }
115
- set efSearch(value) {
116
- this.index.efSearch = value;
117
- }
118
- /** Distance computations performed during the most recent query. */
119
- get lastQueryDistanceComputations() {
120
- return this.index.lastQueryDistComps;
121
- }
122
- /**
123
- * Storage row reads issued by the most recent query. This is the honest,
124
- * cache-independent scalability metric: it counts every node/neighbour fetch
125
- * that hit the database, so disabling the cache cannot hide a bad access pattern.
126
- */
127
- get lastQueryStorageReads() {
128
- return this.index.lastQueryStorageReads;
129
- }
130
- /** Per-vector storage cost of the index versus a Float32 baseline. */
131
- get storage() {
132
- const f32 = this.dim * 4;
133
- const bpv = this.index.bytesPerVector;
134
- return {
135
- float32BytesPerVector: f32,
136
- codeBytesPerVector: bpv,
137
- bytesPerVector: bpv,
138
- compressionRatio: f32 / bpv,
139
- };
140
- }
141
- has(id) {
142
- return this.store.idByExt(this.checkId(id)) !== null;
143
- }
144
- /** Stream every live external id (bounded memory). */
145
- *keys() {
146
- yield* this.store.liveExts();
147
- }
148
- /**
149
- * Stream live entries whose INTERNAL id is > `after`, as
150
- * {ext, internal} pairs in internal-id order. Internal ids are assigned
151
- * monotonically at insert and preserved by {@link compact}, so the largest
152
- * internal id a caller has seen is a durable incremental watermark: a later
153
- * call with it yields exactly the entries added since.
154
- */
155
- *keysSince(after) {
156
- yield* this.store.liveExtsSince(after);
157
- }
158
- checkId(id) {
159
- if (!Number.isInteger(id)) {
160
- throw new Error(`External id must be an integer, got ${id}`);
161
- }
162
- return id;
163
- }
164
- /**
165
- * Convert a value to code bytes, selecting by length:
166
- * - `codeWords` elements -> an existing 1-bit code (e.g. from `get()`)
167
- * - otherwise -> a raw `dim`-vector, encoded first
168
- * `codeWords < dim` for any dim >= 2, so the two never collide.
169
- */
170
- toCodeBytes(value) {
171
- if (value.length === this.codeWords) {
172
- return this.quantizer.codeToBytes(value);
173
- }
174
- if (value.length !== this.dim) {
175
- throw new Error(
176
- `Vector dimension mismatch: expected ${this.dim}, got ${value.length}`,
177
- );
178
- }
179
- return this.quantizer.codeToBytes(this.quantizer.encode(value));
180
- }
181
- // ------------------------------- CRUD ------------------------------------
182
- /**
183
- * Create. Accepts a raw `dim`-vector or a 1-bit code (`codeWords` words),
184
- * detected by length. Throws if the id already exists (use `update`/`upsert`).
185
- */
186
- insert(id, value) {
187
- this.store.begin();
188
- try {
189
- this.insertCore(id, value);
190
- this.store.commit();
191
- } catch (e) {
192
- this.store.rollback();
193
- throw e;
194
- }
195
- }
196
- /** Insert with the caller owning the transaction (used by {@link upsertMany}).
197
- * `ef` optionally narrows the construction beam for this one vector (a
198
- * caller-declared cheap entry, e.g. a reach-only interior); omitted means
199
- * the index's configured efConstruction. */
200
- insertCore(id, value, ef) {
201
- this.checkId(id);
202
- if (this.store.idByExt(id) !== null) {
203
- throw new Error(`External id already exists: ${id} (use update())`);
204
- }
205
- this.index.insert(id, this.toCodeBytes(value), ef);
206
- }
207
- upsert(id, value) {
208
- const nodeId = this.store.idByExt(this.checkId(id));
209
- if (nodeId === null) {
210
- this.insert(id, value);
211
- return;
212
- }
213
- this.store.begin();
214
- try {
215
- this.updateAt(nodeId, id, value);
216
- this.store.commit();
217
- } catch (e) {
218
- this.store.rollback();
219
- throw e;
220
- }
221
- }
222
- /**
223
- * Upsert many vectors under ONE transaction. The HNSW build touches the store
224
- * on every wired edge, so a transaction per vector is one WAL commit per vector
225
- * — which dominates a bulk load on disk. Wrapping the whole batch in a single
226
- * transaction coalesces those commits into one while leaving the graph and its
227
- * result identical (reads on the connection still see the uncommitted rows).
228
- *
229
- * This is purely about commit batching; it changes nothing about the storage
230
- * model. Codes still live only in SQLite and are read on demand — the
231
- * cache-independent per-operation read count is unchanged — so a batched load
232
- * scales exactly as the per-item path does, just with far fewer fsyncs. A throw
233
- * rolls the whole batch back, so the caller treats it as the per-item path on
234
- * failure.
235
- */
236
- upsertMany(entries) {
237
- if (entries.length === 0) {
238
- return;
239
- }
240
- this.store.begin();
241
- try {
242
- for (const e of entries) {
243
- const nodeId = this.store.idByExt(this.checkId(e.id));
244
- if (nodeId !== null) {
245
- this.updateAt(nodeId, e.id, e.vector, e.ef);
246
- } else {
247
- this.insertCore(e.id, e.vector, e.ef);
248
- }
249
- }
250
- this.store.commit();
251
- } catch (e) {
252
- this.store.rollback();
253
- throw e;
254
- }
255
- }
256
- /**
257
- * Read the stored 1-bit code for an id (a copy as a Uint32Array), or null. The
258
- * original vector is not retained; the code round-trips into insert/update/query.
259
- */
260
- get(id) {
261
- const nodeId = this.store.idByExt(this.checkId(id));
262
- if (nodeId === null) {
263
- return null;
264
- }
265
- const rec = this.store.getNode(nodeId);
266
- return rec ? this.quantizer.bytesToCode(rec.code) : null;
267
- }
268
- /**
269
- * Update the vector bound to an id (raw vector or code, detected by length).
270
- * The previous node is tombstoned and a fresh one inserted. Throws if absent.
271
- */
272
- update(id, value) {
273
- this.store.begin();
274
- try {
275
- this.updateCore(id, value);
276
- this.store.commit();
277
- } catch (e) {
278
- this.store.rollback();
279
- throw e;
280
- }
281
- }
282
- /** Update with the caller owning the transaction (used by {@link upsertMany}). */
283
- updateCore(id, value) {
284
- const oldId = this.store.idByExt(this.checkId(id));
285
- if (oldId === null) {
286
- throw new Error(`Unknown external id: ${id}`);
287
- }
288
- this.updateAt(oldId, id, value);
289
- }
290
- /** Update when the live internal node id is already known.
291
- *
292
- * Skips the write entirely when the new code equals the stored one — the
293
- * update would tombstone the node and replay a full graph insert for a
294
- * byte-identical result. This is not a corner case: content-addressed
295
- * callers re-upsert unchanged vectors wholesale after a restart (the same
296
- * content always encodes to the same code), and each such no-op otherwise
297
- * costs a tombstone (permanent routing/disk overhead until compaction)
298
- * plus an O(ef·log N) reinsert. */
299
- updateAt(nodeId, ext, value, ef) {
300
- const bytes = this.toCodeBytes(value);
301
- const rec = this.store.getNode(nodeId);
302
- if (rec !== null && rec.code.length === bytes.length) {
303
- let same = true;
304
- for (let i = 0; i < bytes.length; i++) {
305
- if (rec.code[i] !== bytes[i]) {
306
- same = false;
307
- break;
308
- }
309
- }
310
- if (same) {
311
- return; // identical code — the update is a no-op
312
- }
313
- }
314
- this.index.remove(nodeId); // frees the ext id, then re-insert under it
315
- this.index.insert(ext, bytes, ef);
316
- }
317
- /**
318
- * Delete many ids under ONE transaction — same commit-coalescing rationale
319
- * as {@link upsertMany}: a tombstone per implicit transaction is one WAL
320
- * commit per id, which dominates a bulk prune. Absent ids are skipped.
321
- * Returns the number of vectors actually removed.
322
- */
323
- deleteMany(ids) {
324
- if (ids.length === 0) {
325
- return 0;
326
- }
327
- let removed = 0;
328
- this.store.begin();
329
- try {
330
- for (const id of ids) {
331
- const nodeId = this.store.idByExt(this.checkId(id));
332
- if (nodeId !== null && this.index.remove(nodeId)) {
333
- removed++;
334
- }
335
- }
336
- this.store.commit();
337
- } catch (e) {
338
- this.store.rollback();
339
- throw e;
340
- }
341
- return removed;
342
- }
343
- /** Delete the vector bound to an id. Returns false if absent. */
344
- delete(id) {
345
- const nodeId = this.store.idByExt(this.checkId(id));
346
- if (nodeId === null) {
347
- return false;
348
- }
349
- this.store.begin();
350
- try {
351
- this.index.remove(nodeId);
352
- this.store.commit();
353
- } catch (e) {
354
- this.store.rollback();
355
- throw e;
356
- }
357
- return true;
358
- }
359
- /**
360
- * Pre-fill the RAM caches (codes + neighbour lists) with sequential table
361
- * scans, up to their budget-derived caps. Optional and purely a latency
362
- * optimisation: a cold session otherwise pays the same warming through
363
- * random point reads over its first minutes. Call once after open on a
364
- * session that will do sustained inserts/queries. Returns rows warmed;
365
- * a 0-budget database returns 0 immediately.
366
- */
367
- warmCache() {
368
- return this.store.warmCache();
369
- }
370
- /**
371
- * Rebuild the graph from the live codes only, dropping tombstones and returning
372
- * the freed pages to the filesystem. Lossless -- equivalent to the original
373
- * build -- and needs no original vectors.
374
- */
375
- compact() {
376
- this.index.compact();
377
- }
378
- // ------------------------------ search -----------------------------------
379
- /**
380
- * k-NN search. The argument's length selects the mode:
381
- * - `dim` elements -> a raw vector (accurate 4-bit-query estimator)
382
- * - `codeWords` elements -> a 1-bit code (e.g. `get(id)`), by sign-bit Hamming
383
- * Detection is by length, so a code is recognised whether it is a Uint32Array
384
- * or a plain number[]. `codeWords < dim` for any dim >= 2, so they never collide.
385
- */
386
- query(query, k = 10, opts) {
387
- if (query.length === this.codeWords) {
388
- return this.index.searchKnnByCode(
389
- this.quantizer.codeToBytes(query),
390
- k,
391
- opts?.ef,
392
- );
393
- }
394
- if (query.length !== this.dim) {
395
- throw new Error(
396
- `Vector dimension mismatch: expected ${this.dim}, got ${query.length}`,
397
- );
398
- }
399
- return this.index.searchKnn(query, k, opts?.ef);
400
- }
401
- /** Close the underlying database. The instance must not be used afterwards. */
402
- close() {
403
- this.store.close();
404
- }
405
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Binary heap over two parallel numeric arrays storing (key, value) pairs.
3
- *
4
- * When `minHeap` is true the smallest key sits at the root, otherwise the
5
- * largest. Keys are distances, values are integer node ids. Parallel plain
6
- * arrays are used (rather than an array of objects) to avoid per-element
7
- * allocation in the search hot path.
8
- */
9
- export declare class Heap {
10
- readonly keys: number[];
11
- readonly vals: number[];
12
- private readonly minHeap;
13
- constructor(minHeap: boolean);
14
- get size(): number;
15
- clear(): void;
16
- topKey(): number;
17
- topVal(): number;
18
- /** true if `a` belongs closer to the root than `b`. */
19
- private higher;
20
- push(key: number, val: number): void;
21
- pop(): void;
22
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Binary heap over two parallel numeric arrays storing (key, value) pairs.
3
- *
4
- * When `minHeap` is true the smallest key sits at the root, otherwise the
5
- * largest. Keys are distances, values are integer node ids. Parallel plain
6
- * arrays are used (rather than an array of objects) to avoid per-element
7
- * allocation in the search hot path.
8
- */
9
- export class Heap {
10
- keys = [];
11
- vals = [];
12
- minHeap;
13
- constructor(minHeap) {
14
- this.minHeap = minHeap;
15
- }
16
- get size() {
17
- return this.keys.length;
18
- }
19
- clear() {
20
- this.keys.length = 0;
21
- this.vals.length = 0;
22
- }
23
- topKey() {
24
- return this.keys[0];
25
- }
26
- topVal() {
27
- return this.vals[0];
28
- }
29
- /** true if `a` belongs closer to the root than `b`. */
30
- higher(a, b) {
31
- return this.minHeap ? a < b : a > b;
32
- }
33
- push(key, val) {
34
- const keys = this.keys;
35
- const vals = this.vals;
36
- let i = keys.length;
37
- keys.push(key);
38
- vals.push(val);
39
- while (i > 0) {
40
- const parent = (i - 1) >> 1;
41
- if (this.higher(keys[i], keys[parent])) {
42
- const tk = keys[i];
43
- keys[i] = keys[parent];
44
- keys[parent] = tk;
45
- const tv = vals[i];
46
- vals[i] = vals[parent];
47
- vals[parent] = tv;
48
- i = parent;
49
- } else {
50
- break;
51
- }
52
- }
53
- }
54
- pop() {
55
- const keys = this.keys;
56
- const vals = this.vals;
57
- const n = keys.length;
58
- if (n === 0) {
59
- return;
60
- }
61
- const lastKey = keys[n - 1];
62
- const lastVal = vals[n - 1];
63
- keys.pop();
64
- vals.pop();
65
- const m = keys.length;
66
- if (m === 0) {
67
- return;
68
- }
69
- keys[0] = lastKey;
70
- vals[0] = lastVal;
71
- let i = 0;
72
- while (true) {
73
- const left = 2 * i + 1;
74
- const right = left + 1;
75
- let best = i;
76
- if (left < m && this.higher(keys[left], keys[best])) {
77
- best = left;
78
- }
79
- if (right < m && this.higher(keys[right], keys[best])) {
80
- best = right;
81
- }
82
- if (best === i) {
83
- break;
84
- }
85
- const tk = keys[i];
86
- keys[i] = keys[best];
87
- keys[best] = tk;
88
- const tv = vals[i];
89
- vals[i] = vals[best];
90
- vals[best] = tv;
91
- i = best;
92
- }
93
- }
94
- }
@@ -1,125 +0,0 @@
1
- import { RaBitQuantizer } from "./rabitq.js";
2
- import { Store } from "./store.js";
3
- export interface HnswParams {
4
- M: number;
5
- efConstruction: number;
6
- efSearch: number;
7
- seed: number;
8
- }
9
- export interface KnnHit {
10
- /** external (user) id */
11
- id: number;
12
- /** estimated cosine distance (1 - cosine) */
13
- distance: number;
14
- }
15
- /**
16
- * Hierarchical Navigable Small World graph (Malkov & Yashunin, 2018) backed by
17
- * 1-bit RaBitQ codes that live in SQLite (see Store) rather than in RAM. The
18
- * algorithm is the textbook one; the only difference is that codes and adjacency
19
- * lists are read and written through the store on demand, so the resident set is
20
- * the working set of the current operation -- never the whole graph.
21
- *
22
- * Distances use the codes throughout:
23
- * - searching with a full-precision query uses RaBitQ's accurate estimator;
24
- * - building the graph and searching by code compare two codes by sign-bit
25
- * Hamming distance.
26
- * Building on codes alone is what lets `compact` rebuild an honest index with no
27
- * access to the original vectors.
28
- */
29
- export declare class HnswIndex {
30
- readonly M: number;
31
- readonly Mmax0: number;
32
- readonly efConstruction: number;
33
- private readonly mL;
34
- private readonly quantizer;
35
- private readonly store;
36
- private readonly seed;
37
- private readonly levelRng;
38
- private entry;
39
- private maxLevel;
40
- private live;
41
- private total;
42
- private _efSearch;
43
- private readonly working;
44
- private readonly visited;
45
- private visitedTag;
46
- private visitedEpoch;
47
- private seenTag;
48
- private markVisited;
49
- private readonly candHeap;
50
- private readonly resHeap;
51
- private readonly singleEp;
52
- private readonly idxScratch;
53
- private readonly distScratch;
54
- private readonly freshScratch;
55
- private qCtx;
56
- private refBytes;
57
- private building;
58
- lastQueryDistComps: number;
59
- /** Storage row reads issued by the most recent query (cache-independent). */
60
- lastQueryStorageReads: number;
61
- constructor(quantizer: RaBitQuantizer, store: Store, params: HnswParams);
62
- get size(): number;
63
- get physicalSize(): number;
64
- get bytesPerVector(): number;
65
- get efSearch(): number;
66
- set efSearch(v: number);
67
- private persistState;
68
- private randomLevel;
69
- /**
70
- * Fetch a node record into the operation's working set. The first touch in an
71
- * op is a storage read; later touches in the same op reuse it. The set is
72
- * cleared per op and bounded by efConstruction / efSearch, so storage reads
73
- * per op equal the number of *distinct* nodes the op visits -- minimal, and
74
- * independent of any cache.
75
- */
76
- private node;
77
- /** Prefetch several nodes into the working set with ONE batched storage
78
- * read for the misses. Point queries per neighbour made statement
79
- * dispatch — not distance arithmetic — the dominant cost of a large
80
- * build; the batch keeps `reads` accounting identical per row. */
81
- private fetchNodes;
82
- /** Distance from the current source (query vector or reference code) to a node. */
83
- private distOf;
84
- /** Code-to-code distance between two stored nodes (graph wiring only). */
85
- private codeDist;
86
- /**
87
- * SEARCH-LAYER (Algorithm 2). Frontier in `candHeap`, bounded result set in
88
- * `resHeap` (non-deleted only). Deleted nodes are traversed for routing but
89
- * never returned. `visited` is a per-call set sized by the nodes seen here.
90
- */
91
- private searchLayer;
92
- /** Greedy single-best descent from `fromLayer` down to (but not into) `toLayer`. */
93
- private greedyDescend;
94
- /**
95
- * SELECT-NEIGHBORS-HEURISTIC (Algorithm 4) on codes. Picks up to `M` diverse
96
- * neighbours from `candIds`, preferring those closer to `base` than to any
97
- * already-chosen neighbour, then fills remaining slots with the closest
98
- * leftovers (keep-pruned connections). Appends to `out`.
99
- */
100
- private selectNeighbors;
101
- /**
102
- * Insert a vector's code under external id `ext`; returns the internal node id.
103
- * All graph reads/writes go through the store; the caller owns the transaction.
104
- */
105
- insert(ext: number, code: Uint8Array, efC?: number): number;
106
- /** k-NN with a full-precision query vector (accurate estimator). */
107
- searchKnn(vec: ArrayLike<number>, k: number, ef?: number): KnnHit[];
108
- /** k-NN with an already-quantized code (sign-bit Hamming / angular distance). */
109
- searchKnnByCode(codeBytes: Uint8Array, k: number, ef?: number): KnnHit[];
110
- private collectKnn;
111
- /** Tombstone a live node by internal id. Caller owns the transaction. */
112
- remove(id: number): boolean;
113
- /**
114
- * Reclaim tombstones with a graph-preserving splice (see
115
- * {@link Store.spliceCompact}): live nodes keep their internal ids and their
116
- * wiring; each dead neighbour is replaced by its own live neighbours. Codes
117
- * are untouched, so the index loses nothing beyond what deletion itself
118
- * removes. The previous implementation replayed every live code through a
119
- * full HNSW insert — O(live · ef · log N) storage reads, HOURS on a trained
120
- * multi-million-node store, inside one WAL-bloating transaction. The splice
121
- * is a streaming pass with batched commits, then a VACUUM to return the
122
- * freed pages.
123
- */
124
- compact(): void;
125
- }