vector-index 0.0.0-stage → 0.1.0

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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1456 -2
  3. package/build-browser.js +67 -0
  4. package/index.js +39 -0
  5. package/package.json +72 -4
  6. package/src/async.js +458 -0
  7. package/src/clustering.js +226 -0
  8. package/src/embeddings/als.js +211 -0
  9. package/src/embeddings/bpr.js +149 -0
  10. package/src/embeddings/embeddings.js +222 -0
  11. package/src/embeddings/evaluate.js +193 -0
  12. package/src/embeddings/graph.js +376 -0
  13. package/src/embeddings/idmap.js +120 -0
  14. package/src/embeddings/interactions.js +123 -0
  15. package/src/embeddings/memory.js +52 -0
  16. package/src/embeddings/node2vec.js +142 -0
  17. package/src/embeddings/sgns.js +191 -0
  18. package/src/embeddings/skipgram.js +128 -0
  19. package/src/embeddings/trainer.js +147 -0
  20. package/src/embeddings/walker.js +208 -0
  21. package/src/errors.js +41 -0
  22. package/src/heap.js +82 -0
  23. package/src/index/block-codec.js +191 -0
  24. package/src/index/diskann-block-engine.js +891 -0
  25. package/src/index/diskann.js +331 -0
  26. package/src/index/engine-common.js +159 -0
  27. package/src/index/flat.js +49 -0
  28. package/src/index/hnsw.js +282 -0
  29. package/src/index/ivf.js +232 -0
  30. package/src/index/prune.js +70 -0
  31. package/src/index/vector-index.js +391 -0
  32. package/src/lru.js +32 -0
  33. package/src/math.js +666 -0
  34. package/src/metric.js +62 -0
  35. package/src/quant/bq.js +172 -0
  36. package/src/quant/pq.js +418 -0
  37. package/src/quant/scan.js +52 -0
  38. package/src/quant/sq.js +274 -0
  39. package/src/quant/turboquant.js +527 -0
  40. package/src/reduce/pca.js +253 -0
  41. package/src/results.js +86 -0
  42. package/src/search.js +52 -0
  43. package/src/sparse/sparse-index.js +349 -0
  44. package/src/store.js +476 -0
  45. package/src/typed.js +23 -0
  46. package/src/validate.js +130 -0
@@ -0,0 +1,891 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // DiskANN Block Engine — LM-DiskANN
7
+ //
8
+ // the Vamana graph of the in-memory DiskANN, with nodes living in external
9
+ // storage (IndexedDB, filesystem, S3, ...) reached through handlers the
10
+ // caller registers for storage events.
11
+ //
12
+ // LM-DiskANN ("low memory" DiskANN): every node's block carries, next to the
13
+ // ids of its neighbors, a compressed copy of each neighbor's vector
14
+ // (a TurboQuant code — data-oblivious, no training). reading ONE block is
15
+ // therefore enough to estimate how close every neighbor is to the query,
16
+ // without reading the neighbors' own blocks:
17
+ //
18
+ // - search reads one block per node it expands (instead of one per
19
+ // neighbor of every expanded node) and ranks the final results by the
20
+ // exact vectors of the expanded nodes
21
+ // - pruning a full neighbor list uses the codes already in the block
22
+ // instead of reading every neighbor
23
+ //
24
+ // nothing is kept only in memory except an LRU cache of recently used
25
+ // blocks, so memory use is independent of the index size.
26
+ //
27
+ // persistent state:
28
+ // - one block per node, keyed by the node's numeric id
29
+ // (block:read / block:write): normalized vector, out-edges with their
30
+ // codes, deleted flag
31
+ // - one metadata record (meta:read / meta:write): counts, entry point,
32
+ // running sum of live vectors (for the medoid), code configuration.
33
+ // written when the write queue drains, and at least every
34
+ // metaWriteInterval operations while it doesn't.
35
+ // ===========================
36
+
37
+ import { vectorInput, vectorDistance, resultOf } from '../metric.js';
38
+ import { dotAt } from '../math.js';
39
+ import { pruneNeighbors } from './prune.js';
40
+ import { createBlockCodec, MAX_NEIGHBORS } from './block-codec.js';
41
+ import { createLRU } from '../lru.js';
42
+ import { ERR, createError } from '../errors.js';
43
+ import { createEmitter, createTaskQueue, requireCallback, onceAsync, defer } from '../async.js';
44
+ import { checkVector, checkId, checkPositiveInt } from '../validate.js';
45
+
46
+ import { createTurboQuant } from '../quant/turboquant.js';
47
+
48
+ const CODE_SEED = 0x5eed; // fixed: the rotation must be identical across sessions
49
+
50
+ // ===========================
51
+ // the engine itself
52
+ // ===========================
53
+ function createDiskANNBlockEngine(config) {
54
+ config = config || {};
55
+ const dimensions = checkPositiveInt(config.dimensions, 'dimensions');
56
+ const d = dimensions;
57
+ const R = config.R || 64;
58
+ const L = config.L || 100;
59
+ const alpha = config.alpha || 1.2;
60
+ const cacheSize = config.cacheSize || 1000;
61
+ const codeBits = config.codeBits == null ? 4 : config.codeBits;
62
+ const beamWidth = config.beamWidth == null ? 4 : config.beamWidth;
63
+ const metaWriteInterval = config.metaWriteInterval == null ? 64 : config.metaWriteInterval;
64
+ const metric = config.metric || 'cosine';
65
+ const l2 = metric === 'l2';
66
+
67
+ if (!Number.isInteger(codeBits) || codeBits < 1 || codeBits > 8) {
68
+ throw createError(ERR.INVALID_ARGUMENT, 'codeBits must be an integer between 1 and 8');
69
+ }
70
+ checkPositiveInt(beamWidth, 'beamWidth');
71
+ checkPositiveInt(metaWriteInterval, 'metaWriteInterval');
72
+
73
+ // a neighbor list may grow to RMAX = 1.3·R before it is pruned back to R
74
+ // (DiskANN's slack factor) — most back edges are then a plain append
75
+ const RMAX = Math.min(MAX_NEIGHBORS, Math.ceil(R * 1.3));
76
+
77
+ // compressed neighbor vectors: fixed seed, so the rotation is the same in
78
+ // every session that opens the index
79
+ const quant = createTurboQuant({ dimensions, bits: codeBits, seed: CODE_SEED });
80
+ const codeSize = quant.codeSize;
81
+
82
+ const codec = createBlockCodec(dimensions, codeBits, codeSize, metric);
83
+ const cache = createLRU(cacheSize);
84
+ // block:* and meta:* are request events (exactly one storage handler each);
85
+ // root:change is a notification (any number of listeners)
86
+ const emitter = createEmitter(['block:read', 'block:write', 'block:delete', 'block:keys', 'meta:read', 'meta:write']);
87
+
88
+ // persisted state (mirrored to the metadata record)
89
+ let total = 0; // nodes ever written, including tombstones
90
+ let deletedCount = 0; // tombstones
91
+ const liveSum = new Float64Array(d); // Σ live vectors (as stored) → centroid
92
+ let entryPointId = null;
93
+
94
+ let insertsSinceMedoid = 0;
95
+ let opsSinceMeta = 0;
96
+
97
+ function aliveCount() {
98
+ return total - deletedCount;
99
+ }
100
+
101
+ // a private copy of a vector as the index keeps it (metric.js)
102
+ const normalize = vectorInput(metric);
103
+
104
+ // ===========================
105
+ // geometry — the only place that knows the metric. the graph code below
106
+ // works with handles and distances (lower = closer):
107
+ // query(v) handle of a query
108
+ // node(v) handle of a stored node (graph construction)
109
+ // exact(h, x) distance from a handle to a stored vector
110
+ // estimate(h, p, c, o) distance from a handle to a neighbor code
111
+ // (p = quant._prepare of the handle's vector)
112
+ // pair(x, y) distance between two vectors (pruning)
113
+ // result(id, h, x, d) the search result
114
+ //
115
+ // cosine / l2: a handle is the vector itself; distance 1 − cos or ‖q − x‖².
116
+ // dot: the reduction to l2 of the in-memory index (store.js) — every
117
+ // stored x has one more coordinate e(x) = √(M² − ‖x‖²), a query has 0.
118
+ // here e is computed from ‖x‖, which the block's vector and every
119
+ // TurboQuant neighbor code already carry, so a growing M (the largest
120
+ // norm, kept in the metadata) needs no rewrite of any block.
121
+ // ===========================
122
+ let maxNorm2 = 0; // dot: M²
123
+ const norm2 = (x) => dotAt(x, 0, x, 0, d);
124
+ const ext = (n2) => Math.sqrt(Math.max(0, maxNorm2 - n2));
125
+ const plainDist = vectorDistance(metric === 'dot' ? 'l2' : metric);
126
+ const geo = metric === 'dot'
127
+ ? {
128
+ query: (v) => ({ v, e: 0 }),
129
+ node: (v) => ({ v, e: ext(norm2(v)) }),
130
+ vec: (h) => h.v,
131
+ exact(h, x) {
132
+ const de = h.e - ext(norm2(x));
133
+ return plainDist(h.v, x) + de * de;
134
+ },
135
+ estimate(h, prep, codes, off) {
136
+ const n = quant._normAt(codes, off);
137
+ const de = h.e - ext(n * n);
138
+ return quant._distanceAt(prep, codes, off) + de * de;
139
+ },
140
+ pair(x, y) {
141
+ const de = ext(norm2(x)) - ext(norm2(y));
142
+ return plainDist(x, y) + de * de;
143
+ },
144
+ result: (id, h, x) => ({ id, score: dotAt(h.v, 0, x, 0, d) })
145
+ }
146
+ : {
147
+ query: (v) => v,
148
+ node: (v) => v,
149
+ vec: (h) => h,
150
+ exact: plainDist,
151
+ estimate: l2
152
+ ? (h, prep, codes, off) => quant._distanceAt(prep, codes, off)
153
+ : (h, prep, codes, off) => 1 - quant._innerProductAt(prep, codes, off),
154
+ pair: plainDist,
155
+ result: (id, h, x, dist) => resultOf(metric, id, dist)
156
+ };
157
+ const itemDist = (a, b) => geo.pair(a.vector, b.vector); // for pruneNeighbors
158
+ function observe(v) { // dot: track M²
159
+ if (metric === 'dot') maxNorm2 = Math.max(maxNorm2, norm2(v));
160
+ }
161
+
162
+ // ===========================
163
+ // metadata persistence
164
+ // ===========================
165
+ function writeMeta(cb) {
166
+ let bytes;
167
+ try {
168
+ bytes = codec.encodeMeta({ total, deleted: deletedCount, entryPointId, sum: liveSum, maxNorm2 });
169
+ } catch (err) {
170
+ return cb(err);
171
+ }
172
+ opsSinceMeta = 0;
173
+ emitter.request('meta:write', bytes, cb);
174
+ }
175
+
176
+ // after a write operation: persist the metadata when nothing else is
177
+ // queued (so an idle index always has current metadata), or every
178
+ // metaWriteInterval operations during a long stream of writes
179
+ function maybeWriteMeta(cb) {
180
+ opsSinceMeta++;
181
+ if (queue.size() <= 1 || opsSinceMeta >= metaWriteInterval) return writeMeta(cb);
182
+ cb(null);
183
+ }
184
+
185
+ function setEntryPoint(id) {
186
+ if (id === entryPointId) return;
187
+ entryPointId = id;
188
+ if (id !== null) emitter.emit('root:change', id);
189
+ }
190
+
191
+ // ===========================
192
+ // medoid refresh — the centroid of live vectors is kept incrementally,
193
+ // so finding (approximately) the medoid is one greedy search
194
+ // ===========================
195
+ function refreshMedoid(cb) {
196
+ const alive = aliveCount();
197
+ if (alive === 0 || entryPointId === null) return cb(null);
198
+ const centroid = new Float32Array(d);
199
+ for (let i = 0; i < d; i++) centroid[i] = liveSum[i] / alive;
200
+ greedySearch(geo.query(normalize(centroid)), entryPointId, L, (err, expanded) => {
201
+ if (err) return cb(err);
202
+ const best = expanded.find(e => !e.node.deleted);
203
+ if (best) setEntryPoint(best.node.id);
204
+ insertsSinceMedoid = 0;
205
+ cb(null);
206
+ });
207
+ }
208
+
209
+ function shouldRefreshMedoid() {
210
+ return insertsSinceMedoid >= Math.max(10, aliveCount() / 4);
211
+ }
212
+
213
+ // ===========================
214
+ // block I/O — always through events, LRU cache in front.
215
+ // tombstones are returned too (node.deleted): they stay traversable.
216
+ // ===========================
217
+ function readBlock(id, cb) {
218
+ const cached = cache.get(id);
219
+ if (cached) return cb(null, cached);
220
+
221
+ emitter.request('block:read', id, (err, bytes) => {
222
+ if (err) return cb(err);
223
+ if (!bytes) return cb(null, null);
224
+ let node;
225
+ try {
226
+ node = codec.decode(bytes);
227
+ } catch (decodeErr) {
228
+ return cb(decodeErr);
229
+ }
230
+ if (node.id !== id) return cb(createError(ERR.CORRUPT_DATA, 'block ' + id + ' contains node ' + node.id));
231
+ cache.set(id, node);
232
+ cb(null, node);
233
+ });
234
+ }
235
+
236
+ function writeBlock(node, cb) {
237
+ let bytes;
238
+ try {
239
+ bytes = codec.encode(node);
240
+ } catch (err) {
241
+ return cb(err);
242
+ }
243
+ cache.set(node.id, node);
244
+ emitter.request('block:write', node.id, bytes, cb);
245
+ }
246
+
247
+ function readBlocks(ids, cb) {
248
+ if (ids.length === 0) return cb(null, []);
249
+ const results = new Array(ids.length);
250
+ let remaining = ids.length;
251
+ let firstErr = null;
252
+ ids.forEach((id, i) => {
253
+ readBlock(id, (err, node) => {
254
+ if (err && !firstErr) firstErr = err;
255
+ results[i] = node;
256
+ if (--remaining === 0) cb(firstErr, results);
257
+ });
258
+ });
259
+ }
260
+
261
+ // ===========================
262
+ // Greedy Search (async, beam) — DiskANN Algorithm 1 with LM-DiskANN
263
+ // distance estimates
264
+ //
265
+ // the candidate list is ordered by ESTIMATED distance (from the codes in
266
+ // the expanding node's block). each step expands up to beamWidth of the
267
+ // best unexpanded candidates, reading their blocks in parallel; reading a
268
+ // block gives that node's EXACT distance. the result is every expanded
269
+ // node, sorted by exact distance.
270
+ //
271
+ // trampolined: when storage answers synchronously (cache hits, an
272
+ // in-memory handler) the loop continues without recursing.
273
+ // tombstones are traversed and returned; callers filter them.
274
+ // ===========================
275
+ function greedySearch(q, startId, ef, cb) {
276
+ const prep = quant._prepare(geo.vec(q)); // the query, rotated once
277
+ const lId = new Float64Array(ef + 1);
278
+ const lDist = new Float64Array(ef + 1);
279
+ const lDone = new Uint8Array(ef + 1);
280
+ let size = 0;
281
+ const seen = new Set([startId]);
282
+ const expanded = []; // { node, distance } with exact distances
283
+
284
+ function insert(dist, id) {
285
+ if (size === ef && dist >= lDist[size - 1]) return;
286
+ let lo = 0, hi = size;
287
+ while (lo < hi) {
288
+ const mid = (lo + hi) >> 1;
289
+ if (lDist[mid] <= dist) lo = mid + 1;
290
+ else hi = mid;
291
+ }
292
+ const last = size < ef ? size : ef - 1;
293
+ for (let i = last; i > lo; i--) {
294
+ lId[i] = lId[i - 1];
295
+ lDist[i] = lDist[i - 1];
296
+ lDone[i] = lDone[i - 1];
297
+ }
298
+ lId[lo] = id;
299
+ lDist[lo] = dist;
300
+ lDone[lo] = 0;
301
+ if (size < ef) size++;
302
+ }
303
+
304
+ // a block arrived: exact distance for it, estimates for its neighbors
305
+ function absorb(node) {
306
+ if (!node) return;
307
+ expanded.push({ node, distance: geo.exact(q, node.vector) });
308
+ const nbrs = node.neighbors;
309
+ for (let i = 0; i < nbrs.length; i++) {
310
+ const nid = nbrs[i];
311
+ if (seen.has(nid)) continue;
312
+ seen.add(nid);
313
+ insert(geo.estimate(q, prep, node.codes, i * codeSize), nid);
314
+ }
315
+ }
316
+
317
+ function finish() {
318
+ expanded.sort((a, b) => a.distance - b.distance);
319
+ cb(null, expanded);
320
+ }
321
+
322
+ insert(0, startId); // the start node's real distance arrives with its block
323
+
324
+ function step() {
325
+ while (true) {
326
+ const batch = [];
327
+ for (let i = 0; i < size && batch.length < beamWidth; i++) {
328
+ if (!lDone[i]) {
329
+ lDone[i] = 1;
330
+ batch.push(lId[i]);
331
+ }
332
+ }
333
+ if (batch.length === 0) return finish();
334
+
335
+ let sync = true;
336
+ let syncResult = null;
337
+ readBlocks(batch, (err, nodes) => {
338
+ if (sync) {
339
+ syncResult = { err, nodes };
340
+ return;
341
+ }
342
+ if (err) return cb(err);
343
+ for (const n of nodes) absorb(n);
344
+ step();
345
+ });
346
+ sync = false;
347
+ if (!syncResult) return; // async: the callback resumes the loop
348
+ if (syncResult.err) return cb(syncResult.err);
349
+ for (const n of syncResult.nodes) absorb(n);
350
+ }
351
+ }
352
+
353
+ step();
354
+ }
355
+
356
+ // ===========================
357
+ // Robust Prune — DiskANN Algorithm 2
358
+ // items: [{ id, vector, code? }] (vector exact or approximate, normalized
359
+ // or nearly so). picks at most R diverse ones for the node at `center`.
360
+ // ===========================
361
+ function robustPrune(center, centerId, items, alphaParam) {
362
+ const uniq = [];
363
+ const seen = new Set([centerId]);
364
+ for (const it of items) {
365
+ if (seen.has(it.id)) continue;
366
+ seen.add(it.id);
367
+ uniq.push(it);
368
+ }
369
+ const n = uniq.length;
370
+ const dd = new Float64Array(n);
371
+ for (let i = 0; i < n; i++) dd[i] = geo.exact(center, uniq[i].vector);
372
+ return pruneNeighbors(uniq, dd, itemDist, R, alphaParam, false, false, false);
373
+ }
374
+
375
+ // write a node's neighbor list from items carrying a code
376
+ function setNeighbors(node, items) {
377
+ node.neighbors = items.map(it => it.id);
378
+ const codes = new Uint8Array(items.length * codeSize);
379
+ items.forEach((it, i) => codes.set(it.code, i * codeSize));
380
+ node.codes = codes;
381
+ }
382
+
383
+ // ===========================
384
+ // write serialization queue — Vamana updates must be sequential.
385
+ // same FIFO queue as the in-memory indexes (async.js createTaskQueue).
386
+ // reads (search, stats) don't queue.
387
+ // ===========================
388
+ const queue = createTaskQueue();
389
+
390
+ function enqueueWrite(job) {
391
+ queue.push(job);
392
+ }
393
+
394
+ // ===========================
395
+ // add
396
+ // ===========================
397
+ function add(id, vector, cb) {
398
+ requireCallback(cb, 'add');
399
+ const finish = onceAsync(cb);
400
+ let vec;
401
+ try {
402
+ checkId(id);
403
+ checkVector(vector, dimensions);
404
+ vec = normalize(vector); // private, normalized copy
405
+ } catch (err) {
406
+ return finish(err);
407
+ }
408
+ enqueueWrite((done) => {
409
+ addImpl(id, vec, (err) => {
410
+ finish(err);
411
+ done();
412
+ });
413
+ });
414
+ }
415
+
416
+ function addImpl(id, vector, cb) {
417
+ // the block itself is the source of truth for existence — the same
418
+ // before and after restore()
419
+ readBlock(id, (err, existing) => {
420
+ if (err) return cb(err);
421
+ if (existing && !existing.deleted) {
422
+ return cb(createError(ERR.DUPLICATE_ID, 'id already exists: ' + id));
423
+ }
424
+ const reusingTombstone = !!existing;
425
+ observe(vector);
426
+ const newCode = quant.encodeSync(vector);
427
+ const self = geo.node(vector);
428
+ const newNode = { id, vector, neighbors: [], codes: new Uint8Array(0), deleted: false };
429
+
430
+ function finish(err) {
431
+ if (err) return cb(err);
432
+ if (reusingTombstone) deletedCount--;
433
+ else total++;
434
+ for (let i = 0; i < d; i++) liveSum[i] += vector[i];
435
+ insertsSinceMedoid++;
436
+ const after = (refreshErr) => {
437
+ if (refreshErr) return cb(refreshErr);
438
+ maybeWriteMeta(cb);
439
+ };
440
+ if (shouldRefreshMedoid()) refreshMedoid(after);
441
+ else after(null);
442
+ }
443
+
444
+ if (entryPointId === null) {
445
+ return writeBlock(newNode, (err) => {
446
+ if (err) return cb(err);
447
+ setEntryPoint(id);
448
+ finish(null);
449
+ });
450
+ }
451
+
452
+ greedySearch(self, entryPointId, L, (err, expanded) => {
453
+ if (err) return cb(err);
454
+
455
+ // candidates: expanded live nodes, with their exact vectors
456
+ const items = [];
457
+ for (const e of expanded) {
458
+ if (!e.node.deleted) items.push({ id: e.node.id, vector: e.node.vector, node: e.node });
459
+ }
460
+ const selected = robustPrune(self, id, items, alpha);
461
+ for (const s of selected) s.code = quant.encodeSync(s.vector);
462
+ setNeighbors(newNode, selected);
463
+
464
+ writeBlock(newNode, (err) => {
465
+ if (err) return cb(err);
466
+
467
+ // no live node reachable (only tombstones left): become the entry
468
+ // point so later inserts attach here instead of ending up isolated
469
+ if (selected.length === 0) {
470
+ setEntryPoint(id);
471
+ return finish(null);
472
+ }
473
+
474
+ let remaining = selected.length;
475
+ let firstErr = null;
476
+ const oneDone = (err) => {
477
+ if (err && !firstErr) firstErr = err;
478
+ if (--remaining === 0) finish(firstErr);
479
+ };
480
+ for (const s of selected) addBackEdge(s.node, id, vector, newCode, oneDone);
481
+ });
482
+ });
483
+ });
484
+ }
485
+
486
+ // edge n → (id); once n holds RMAX edges, prune back to R using the codes
487
+ // in n's own block as approximate neighbor vectors — no extra reads
488
+ function addBackEdge(n, id, vector, code, cb) {
489
+ const count = n.neighbors.length;
490
+ if (count < RMAX) {
491
+ const codes = new Uint8Array((count + 1) * codeSize);
492
+ codes.set(n.codes.subarray(0, count * codeSize));
493
+ codes.set(code, count * codeSize);
494
+ n.neighbors = n.neighbors.concat([id]);
495
+ n.codes = codes;
496
+ return writeBlock(n, cb);
497
+ }
498
+ const items = [];
499
+ for (let i = 0; i < count; i++) {
500
+ const c = n.codes.slice(i * codeSize, (i + 1) * codeSize);
501
+ items.push({ id: n.neighbors[i], vector: quant.decodeSync(c), code: c });
502
+ }
503
+ items.push({ id, vector, code });
504
+ setNeighbors(n, robustPrune(geo.node(n.vector), n.id, items, alpha));
505
+ writeBlock(n, cb);
506
+ }
507
+
508
+ // ===========================
509
+ // delete — soft: the block is rewritten with the deleted flag. the node
510
+ // keeps its vector and edges, so search still routes through it; it is
511
+ // never returned and never picked as a new neighbor.
512
+ // ===========================
513
+ function del(id, cb) {
514
+ requireCallback(cb, 'delete');
515
+ const finish = onceAsync(cb);
516
+ try {
517
+ checkId(id);
518
+ } catch (err) {
519
+ return finish(err);
520
+ }
521
+ enqueueWrite((done) => {
522
+ delImpl(id, (err) => {
523
+ finish(err);
524
+ done();
525
+ });
526
+ });
527
+ }
528
+
529
+ function delImpl(id, cb) {
530
+ readBlock(id, (err, node) => {
531
+ if (err) return cb(err);
532
+ if (!node) return cb(createError(ERR.NOT_FOUND, 'id not found: ' + id));
533
+ if (node.deleted) return cb(createError(ERR.ALREADY_DELETED, 'id already deleted: ' + id));
534
+
535
+ node.deleted = true;
536
+ writeBlock(node, (err) => {
537
+ if (err) {
538
+ node.deleted = false;
539
+ return cb(err);
540
+ }
541
+ deletedCount++;
542
+ for (let i = 0; i < d; i++) liveSum[i] -= node.vector[i];
543
+
544
+ // a deleted entry point still works for traversal; move it to a
545
+ // live node when it's cheap to do so
546
+ if (id === entryPointId && aliveCount() > 0) {
547
+ return refreshMedoid((refreshErr) => {
548
+ if (refreshErr) return cb(refreshErr);
549
+ maybeWriteMeta(cb);
550
+ });
551
+ }
552
+ maybeWriteMeta(cb);
553
+ });
554
+ });
555
+ }
556
+
557
+ // ===========================
558
+ // search — top-k live results by exact distance
559
+ // ===========================
560
+ // accept: the index's wrapped options.filter (id → boolean), or undefined.
561
+ // there is no in-memory list of nodes to scan, so when a filter or a
562
+ // deleted region leaves fewer than k results in the beam, it is widened
563
+ // (×4, up to 3 times)
564
+ function search(query, k, cb, accept) {
565
+ requireCallback(cb, 'search');
566
+ cb = onceAsync(cb);
567
+ let q;
568
+ try {
569
+ checkVector(query, dimensions, 'query');
570
+ checkPositiveInt(k, 'k');
571
+ q = geo.query(normalize(query));
572
+ } catch (err) {
573
+ return cb(err);
574
+ }
575
+
576
+ if (entryPointId === null || aliveCount() === 0) return cb(null, []);
577
+
578
+ // widen the beam by the deleted ratio so k live results survive filtering
579
+ const base = Math.max(L, k);
580
+ const ef = base + Math.ceil(base * deletedCount / Math.max(1, total));
581
+
582
+ const run = (ef, tries) => greedySearch(q, entryPointId, ef, (err, expanded) => {
583
+ if (err) return cb(err);
584
+ const results = [];
585
+ try {
586
+ for (const e of expanded) {
587
+ if (e.node.deleted) continue;
588
+ if (accept && !accept(e.node.id)) continue;
589
+ results.push(geo.result(e.node.id, q, e.node.vector, e.distance));
590
+ if (results.length === k) break;
591
+ }
592
+ } catch (filterErr) {
593
+ return cb(filterErr);
594
+ }
595
+ // fewer than k although more live nodes exist: the beam saw mostly
596
+ // tombstones (a deleted region) or filtered-out nodes — widen it
597
+ const reachable = accept ? true : results.length < aliveCount();
598
+ if (results.length < k && reachable && tries < 3 && ef < total) return run(ef * 4, tries + 1);
599
+ cb(null, results);
600
+ });
601
+ run(ef, 0);
602
+ }
603
+
604
+ // ===========================
605
+ // stats — from the persisted counters (valid after restore too)
606
+ // ===========================
607
+ function stats(cb) {
608
+ requireCallback(cb, 'stats');
609
+ onceAsync(cb)(null, {
610
+ total,
611
+ alive: aliveCount(),
612
+ deleted: deletedCount,
613
+ ratio: total === 0 ? 0 : deletedCount / total,
614
+ R,
615
+ L,
616
+ alpha,
617
+ codeBits,
618
+ beamWidth,
619
+ cacheSize: cache.size(),
620
+ cacheCapacity: cacheSize,
621
+ entryPoint: entryPointId
622
+ });
623
+ }
624
+
625
+ // ===========================
626
+ // restore — reopen an existing index from storage
627
+ //
628
+ // reads the metadata record (counts, centroid sum, entry point), then
629
+ // checks that the root block exists. rootId is optional: when omitted,
630
+ // the entry point stored in the metadata is used.
631
+ // ===========================
632
+ function restore(rootId, cb) {
633
+ if (typeof rootId === 'function' && cb === undefined) {
634
+ cb = rootId;
635
+ rootId = null;
636
+ }
637
+ requireCallback(cb, 'restore');
638
+ const finish = onceAsync(cb);
639
+ if (rootId != null) {
640
+ try {
641
+ checkId(rootId, 'rootId');
642
+ } catch (err) {
643
+ return finish(err);
644
+ }
645
+ }
646
+ // restore replaces the engine state, so it runs in the write queue:
647
+ // queued adds/deletes finish first, later ones see the restored state
648
+ enqueueWrite((done) => {
649
+ restoreImpl(rootId, (err) => {
650
+ finish(err);
651
+ done();
652
+ });
653
+ });
654
+ }
655
+
656
+ function restoreImpl(rootId, cb) {
657
+ emitter.request('meta:read', (err, bytes) => {
658
+ if (err) return cb(err);
659
+ if (!bytes) {
660
+ return cb(createError(ERR.NOT_FOUND,
661
+ 'no index metadata found (meta:read answered null) — nothing to restore'));
662
+ }
663
+
664
+ let meta;
665
+ try {
666
+ meta = codec.decodeMeta(bytes);
667
+ } catch (decodeErr) {
668
+ return cb(decodeErr);
669
+ }
670
+
671
+ // ids are numbers and 0 is a valid id — compare with null, never truthiness
672
+ const root = rootId != null ? rootId : meta.entryPointId;
673
+ const adopt = () => {
674
+ total = meta.total;
675
+ deletedCount = meta.deleted;
676
+ liveSum.set(meta.sum);
677
+ maxNorm2 = meta.maxNorm2;
678
+ entryPointId = root;
679
+ insertsSinceMedoid = 0;
680
+ opsSinceMeta = 0;
681
+ cache.clear();
682
+ };
683
+ if (root === null) {
684
+ adopt();
685
+ return cb(null);
686
+ }
687
+ readBlock(root, (err, node) => {
688
+ if (err) return cb(err);
689
+ if (!node) return cb(createError(ERR.NOT_FOUND, 'root block not found: ' + root));
690
+ adopt();
691
+ cb(null);
692
+ });
693
+ });
694
+ }
695
+
696
+ function getRootId() {
697
+ return entryPointId;
698
+ }
699
+
700
+ // not implemented for block storage yet — present so this engine has the
701
+ // same method set as every index, and fails the same way
702
+ // ===========================
703
+ // compact — removes deleted nodes for good (FreshDiskANN's delete
704
+ // consolidation, Singh et al. 2021, Algorithm 4)
705
+ //
706
+ // 1. block:keys → every id in storage; read every block, collect the
707
+ // deleted set D with their neighbor lists
708
+ // 2. every live node p with an edge into D gets a new neighbor list:
709
+ // robustPrune over p's live neighbors ∪ the live neighbors of each
710
+ // deleted neighbor — it bridges over the gap. distances come from the
711
+ // codes already in those blocks, so no extra reads
712
+ // 3. metadata: entry point moved off D, counts recomputed from what was
713
+ // read (so an interrupted compact heals on the next one)
714
+ // 4. block:delete for every node of D
715
+ //
716
+ // the graph is valid at every step: until 4, deleted nodes still exist and
717
+ // still route; after 2, no live node points to them. searches keep running
718
+ // during compact; writes wait in the queue. reads go in batches, with a
719
+ // pause for the event loop between them.
720
+ // ===========================
721
+ const COMPACT_BATCH = 16;
722
+
723
+ function compact(cb) {
724
+ requireCallback(cb, 'compact');
725
+ const finish = onceAsync(cb);
726
+ enqueueWrite((done) => {
727
+ compactImpl((err) => {
728
+ finish(err);
729
+ done();
730
+ });
731
+ });
732
+ }
733
+
734
+ function compactImpl(cb) {
735
+ emitter.request('block:keys', (err, keys) => {
736
+ if (err) return cb(err);
737
+ if (!Array.isArray(keys)) {
738
+ return cb(createError(ERR.STORAGE, 'block:keys must answer with an array of ids'));
739
+ }
740
+ const ids = [...new Set(keys)];
741
+ const deleted = new Map(); // id → node (its neighbors + codes)
742
+ const live = [];
743
+ let liveCount = 0;
744
+ const report = (phase, processed, of) => emitter.emit('progress', {
745
+ phase, processed, total: of, percent: of === 0 ? 100 : Math.round(processed / of * 100)
746
+ });
747
+
748
+ // pass 1: who is deleted
749
+ eachBatch(ids, (node) => {
750
+ if (!node) return;
751
+ if (node.deleted) deleted.set(node.id, node);
752
+ else { liveCount++; live.push(node.id); }
753
+ }, (n) => report('compact:scan', n, ids.length), (err) => {
754
+ if (err) return cb(err);
755
+ if (deleted.size === 0) {
756
+ total = liveCount;
757
+ deletedCount = 0;
758
+ return writeMeta(cb);
759
+ }
760
+ repair();
761
+ });
762
+
763
+ // pass 2: re-link the live nodes that point into D
764
+ function repair() {
765
+ eachBatch(live, (node, next) => {
766
+ if (!node) return next();
767
+ let touches = false;
768
+ for (const nid of node.neighbors) if (deleted.has(nid)) { touches = true; break; }
769
+ if (!touches) return next();
770
+ const items = [];
771
+ const add = (owner, i) => {
772
+ const nid = owner.neighbors[i];
773
+ if (nid === node.id || deleted.has(nid)) return;
774
+ const code = owner.codes.slice(i * codeSize, (i + 1) * codeSize);
775
+ items.push({ id: nid, vector: quant.decodeSync(code), code });
776
+ };
777
+ for (let i = 0; i < node.neighbors.length; i++) {
778
+ const v = deleted.get(node.neighbors[i]);
779
+ if (!v) add(node, i);
780
+ else for (let j = 0; j < v.neighbors.length; j++) add(v, j);
781
+ }
782
+ setNeighbors(node, robustPrune(geo.node(node.vector), node.id, items, alpha));
783
+ writeBlock(node, next);
784
+ }, (n) => report('compact:repair', n, live.length), (err) => {
785
+ if (err) return cb(err);
786
+ relocate();
787
+ }, true);
788
+ }
789
+
790
+ // 3: entry point off D, recomputed counts, metadata
791
+ function relocate() {
792
+ total = liveCount;
793
+ deletedCount = 0;
794
+ if (liveCount === 0) {
795
+ setEntryPoint(null);
796
+ return writeMeta((err) => err ? cb(err) : remove());
797
+ }
798
+ if (entryPointId === null || deleted.has(entryPointId)) setEntryPoint(live[0]);
799
+ refreshMedoid((err) => {
800
+ if (err) return cb(err);
801
+ writeMeta((err2) => err2 ? cb(err2) : remove());
802
+ });
803
+ }
804
+
805
+ // 4: the blocks of D
806
+ function remove() {
807
+ const gone = [...deleted.keys()];
808
+ let i = 0;
809
+ (function next(err) {
810
+ if (err) return cb(err);
811
+ if (i === gone.length) return cb(null);
812
+ const id = gone[i++];
813
+ cache.delete(id);
814
+ emitter.request('block:delete', id, (e) => {
815
+ if (i % COMPACT_BATCH === 0) defer(() => next(e));
816
+ else next(e);
817
+ });
818
+ })();
819
+ }
820
+ });
821
+ }
822
+
823
+ // read ids in batches of COMPACT_BATCH; visit(node[, next]) per block.
824
+ // withNext: visit is asynchronous and calls next() when done (a block
825
+ // write); the batch waits for all of them. a pause between batches keeps
826
+ // the event loop free and the stack flat with synchronous storage.
827
+ function eachBatch(ids, visit, progress, cb, withNext) {
828
+ let at = 0;
829
+ batch();
830
+ function batch() {
831
+ if (at >= ids.length) {
832
+ progress(ids.length);
833
+ return cb(null);
834
+ }
835
+ const slice = ids.slice(at, at + COMPACT_BATCH);
836
+ at += slice.length;
837
+ readBlocks(slice, (err, nodes) => {
838
+ if (err) return cb(err);
839
+ if (!withNext) {
840
+ for (const n of nodes) visit(n);
841
+ return afterBatch();
842
+ }
843
+ let remaining = nodes.length;
844
+ let firstErr = null;
845
+ const one = (e) => {
846
+ if (e && !firstErr) firstErr = e;
847
+ if (--remaining === 0) {
848
+ if (firstErr) return cb(firstErr);
849
+ afterBatch();
850
+ }
851
+ };
852
+ for (const n of nodes) visit(n, one);
853
+ });
854
+ }
855
+ function afterBatch() {
856
+ if (at % (COMPACT_BATCH * 16) === 0) progress(at);
857
+ defer(batch);
858
+ }
859
+ }
860
+
861
+ function notSupported(method) {
862
+ return function (...args) {
863
+ const cb = args[args.length - 1];
864
+ requireCallback(cb, method);
865
+ onceAsync(cb)(createError(ERR.NOT_SUPPORTED, method + '() is not supported by diskann-blocks yet'));
866
+ };
867
+ }
868
+
869
+ return {
870
+ isAsync: true,
871
+ add,
872
+ delete: del,
873
+ search,
874
+ stats,
875
+ compact,
876
+ train: notSupported('train'),
877
+ build: notSupported('build'),
878
+ restore,
879
+ getRootId,
880
+ on: emitter.on,
881
+ off: emitter.off,
882
+ // config
883
+ algorithm: 'diskann-blocks',
884
+ dimensions,
885
+ requiresTraining: false
886
+ };
887
+ }
888
+
889
+ export {
890
+ createDiskANNBlockEngine
891
+ };