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,282 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // HNSW engine
7
+ //
8
+ // layer 0 neighbors: Int32Array, Mmax0 slots per node
9
+ // upper layers: only ~1/M of nodes have them; per-node Int32Arrays
10
+ // ===========================
11
+
12
+ import { createRng } from '../math.js';
13
+ import { createHeap } from '../heap.js';
14
+ import { pruneNeighbors } from './prune.js';
15
+ import { liveStats, makeStore, toResults, filteredScan, filterPlan } from './engine-common.js';
16
+
17
+ function createHNSWEngine(config) {
18
+ const d = config.dimensions;
19
+ const M = config.M;
20
+ const Mmax0 = M * 2; // more neighbors at layer 0
21
+ const efConstruction = config.efConstruction;
22
+ const efSearch = config.efSearch;
23
+ const mL = 1 / Math.log(M); // level generation factor
24
+
25
+ const rng = createRng(config.seed);
26
+ const store = makeStore(config);
27
+
28
+ let level = new Int8Array(store.capacity);
29
+ let nbr0 = new Int32Array(store.capacity * Mmax0);
30
+ let deg0 = new Int32Array(store.capacity);
31
+ const upNbr = []; // upNbr[s] = Int32Array(level * M): layers 1..level
32
+ const upDeg = []; // upDeg[s] = Int32Array(level)
33
+ store.onGrow((cap) => {
34
+ const l = new Int8Array(cap); l.set(level); level = l;
35
+ const n = new Int32Array(cap * Mmax0); n.set(nbr0); nbr0 = n;
36
+ const g = new Int32Array(cap); g.set(deg0); deg0 = g;
37
+ });
38
+
39
+ let entry = -1;
40
+ let maxLayer = -1;
41
+
42
+ // reused across calls — searches are synchronous and never nest
43
+ const cand = createHeap(false, 256); // min: next to explore
44
+ const res = createHeap(true, 256); // max: worst result on top
45
+
46
+ function randomLevel() {
47
+ // 1 - rng() is in (0, 1], so log never sees 0; capped to fit Int8Array
48
+ return Math.min(32, Math.floor(-Math.log(1 - rng()) * mL));
49
+ }
50
+
51
+ function degree(s, layer) {
52
+ return layer === 0 ? deg0[s] : upDeg[s][layer - 1];
53
+ }
54
+
55
+ function neighborAt(s, layer, i) {
56
+ return layer === 0 ? nbr0[s * Mmax0 + i] : upNbr[s][(layer - 1) * M + i];
57
+ }
58
+
59
+ function setNeighbors(s, layer, slots, n) {
60
+ if (layer === 0) {
61
+ const base = s * Mmax0;
62
+ for (let i = 0; i < n; i++) nbr0[base + i] = slots[i];
63
+ deg0[s] = n;
64
+ } else {
65
+ const arr = upNbr[s];
66
+ const base = (layer - 1) * M;
67
+ for (let i = 0; i < n; i++) arr[base + i] = slots[i];
68
+ upDeg[s][layer - 1] = n;
69
+ }
70
+ }
71
+
72
+ // ===========================
73
+ // beam search on one layer
74
+ //
75
+ // soft-deleted nodes are ALWAYS traversed (they are still bridges). with
76
+ // excludeDeleted they are kept out of the result set (search); during
77
+ // construction they may be returned so a new node can attach through them.
78
+ // returns { dist, slot } sorted closest first.
79
+ // ===========================
80
+ // excludeDeleted: false (construction), true (search), or a predicate on
81
+ // the slot (filtered search): nodes failing it are traversed, not returned
82
+ function searchLayer(h, entrySlots, ef, layer, excludeDeleted) {
83
+ const skip = excludeDeleted === true ? (s) => store.isDeleted(s)
84
+ : excludeDeleted ? (s) => !excludeDeleted(s)
85
+ : null;
86
+ store.newTraversal();
87
+ cand.clear();
88
+ res.clear();
89
+
90
+ for (const ep of entrySlots) {
91
+ if (!store.mark(ep)) continue;
92
+ const dd = 1 - store.sim(h, ep);
93
+ cand.push(dd, ep);
94
+ if (!(skip && skip(ep))) res.push(dd, ep);
95
+ }
96
+
97
+ while (cand.size() > 0) {
98
+ const cd = cand.topDist();
99
+ const cs = cand.topSlot();
100
+ cand.pop();
101
+ // the closest unexplored is farther than the worst result: done
102
+ if (res.size() >= ef && cd > res.topDist()) break;
103
+
104
+ const n = degree(cs, layer);
105
+ for (let i = 0; i < n; i++) {
106
+ const t = neighborAt(cs, layer, i);
107
+ if (!store.mark(t)) continue;
108
+ const dd = 1 - store.sim(h, t);
109
+ if (res.size() < ef || dd < res.topDist()) {
110
+ cand.push(dd, t);
111
+ if (!(skip && skip(t))) {
112
+ res.push(dd, t);
113
+ if (res.size() > ef) res.pop();
114
+ }
115
+ }
116
+ }
117
+ }
118
+ return res.drainSorted();
119
+ }
120
+
121
+ // greedy walk on one upper layer: move to a closer neighbor until stuck
122
+ function greedyDescend(h, start, startDist, layer) {
123
+ let cur = start, curDist = startDist;
124
+ let changed = true;
125
+ while (changed) {
126
+ changed = false;
127
+ const n = degree(cur, layer);
128
+ for (let i = 0; i < n; i++) {
129
+ const t = neighborAt(cur, layer, i);
130
+ const dd = 1 - store.sim(h, t);
131
+ if (dd < curDist) {
132
+ cur = t;
133
+ curDist = dd;
134
+ changed = true;
135
+ }
136
+ }
137
+ }
138
+ return { cur, curDist };
139
+ }
140
+
141
+ // heuristic neighbor selection (Malkov 2016): keep a candidate only if it
142
+ // is closer to the target than to every neighbor already kept — spreads
143
+ // connections across directions. with topUp, fills the remaining room with
144
+ // the closest rejected candidates. candidates: closest first.
145
+ const slotDist = (a, b) => 1 - store.simSlots(a, b);
146
+
147
+ // dist/slots: candidates closest first
148
+ function selectNeighbors(dist, slots, n, max, topUp) {
149
+ const cands = slots.length === n ? slots : slots.subarray(0, n);
150
+ return pruneNeighbors(cands, dist, slotDist, max, 1, true, topUp, true);
151
+ }
152
+
153
+ // edge n → s on a layer; when n is full, re-select among its neighbors + s.
154
+ // only n's own out-edges change (dropped neighbors keep their edge to n).
155
+ //
156
+ // the re-selection does NOT top the list back up to max (same as hnswlib):
157
+ // the list shrinks a little, so the next few edges are plain appends. with
158
+ // top-up the list stays full forever and every new edge pays an O(max²)
159
+ // re-selection — that was ~70% of build time.
160
+ function addEdge(n, s, layer) {
161
+ const max = layer === 0 ? Mmax0 : M;
162
+ const g = degree(n, layer);
163
+ if (g < max) {
164
+ if (layer === 0) nbr0[n * Mmax0 + deg0[n]++] = s;
165
+ else upNbr[n][(layer - 1) * M + upDeg[n][layer - 1]++] = s;
166
+ return;
167
+ }
168
+ const cs = new Int32Array(g + 1);
169
+ for (let i = 0; i < g; i++) cs[i] = neighborAt(n, layer, i);
170
+ cs[g] = s;
171
+ const ds = new Float64Array(g + 1);
172
+ for (let i = 0; i <= g; i++) ds[i] = 1 - store.simSlots(n, cs[i]);
173
+ const kept = pruneNeighbors(cs, ds, slotDist, max, 1, true, false, false);
174
+ setNeighbors(n, layer, kept, kept.length);
175
+ }
176
+
177
+ function add(id, vector, bytes) {
178
+ const slot = store.add(id, vector, bytes);
179
+ const lvl = randomLevel();
180
+ level[slot] = lvl;
181
+ deg0[slot] = 0;
182
+ if (lvl > 0) {
183
+ upNbr[slot] = new Int32Array(lvl * M);
184
+ upDeg[slot] = new Int32Array(lvl);
185
+ }
186
+
187
+ if (entry === -1) {
188
+ entry = slot;
189
+ maxLayer = lvl;
190
+ return;
191
+ }
192
+
193
+ const q = store.nodeQuery(slot, vector);
194
+ let cur = entry;
195
+ let curDist = 1 - store.sim(q, cur);
196
+
197
+ // greedy descent through layers above the node's level
198
+ // (works even if the entry point is soft-deleted — it's still a bridge)
199
+ for (let layer = maxLayer; layer > lvl; layer--) {
200
+ ({ cur, curDist } = greedyDescend(q, cur, curDist, layer));
201
+ }
202
+
203
+ let eps = [cur];
204
+ for (let layer = Math.min(lvl, maxLayer); layer >= 0; layer--) {
205
+ // construction keeps deleted nodes as candidates: it guarantees the new
206
+ // node attaches even if the entry point's neighborhood was deleted
207
+ const found = searchLayer(q, eps, efConstruction, layer, false);
208
+ const max = layer === 0 ? Mmax0 : M;
209
+ const selected = selectNeighbors(found.dist, found.slot, found.slot.length, max, true);
210
+ setNeighbors(slot, layer, selected, selected.length);
211
+ for (const n of selected) addEdge(n, slot, layer);
212
+ eps = Array.from(found.slot);
213
+ }
214
+
215
+ if (lvl > maxLayer) {
216
+ maxLayer = lvl;
217
+ entry = slot;
218
+ }
219
+ }
220
+
221
+ function del(id) {
222
+ store.remove(id);
223
+ }
224
+
225
+ function search(query, k, accept) {
226
+ if (entry === -1 || store.live === 0) return [];
227
+ const q = store.query(query);
228
+ let ef = Math.max(efSearch, k);
229
+ if (accept) {
230
+ const plan = filterPlan(store, accept);
231
+ if (plan.scan) return filteredScan(store, q, k, accept);
232
+ ef = Math.min(store.count, Math.ceil(ef * Math.sqrt(plan.widen)));
233
+ }
234
+
235
+ // start from the entry point even if it's soft-deleted — traversal
236
+ // passes through deleted nodes, they're only excluded from results
237
+ let cur = entry;
238
+ let curDist = 1 - store.sim(q, cur);
239
+ for (let layer = maxLayer; layer > 0; layer--) {
240
+ ({ cur, curDist } = greedyDescend(q, cur, curDist, layer));
241
+ }
242
+
243
+ const eps = [cur];
244
+ if (!accept) {
245
+ const found = searchLayer(q, eps, Math.max(efSearch, k), 0, true);
246
+ return toResults(store, q, found.dist, found.slot, found.slot.length, k);
247
+ }
248
+ // filtered: only matching live nodes take result slots
249
+ const ok = (s) => !store.isDeleted(s) && accept(store.idOf(s));
250
+ const found = searchLayer(q, eps, ef, 0, ok);
251
+ const out = toResults(store, q, found.dist, found.slot, found.slot.length, k);
252
+ if (out.length < k) return filteredScan(store, q, k, accept);
253
+ return out;
254
+ }
255
+
256
+ function stats() {
257
+ const layerCounts = [];
258
+ for (let s = 0; s < store.count; s++) {
259
+ if (store.isDeleted(s)) continue;
260
+ for (let l = 0; l <= level[s]; l++) layerCounts[l] = (layerCounts[l] || 0) + 1;
261
+ }
262
+ return {
263
+ ...liveStats(store),
264
+ maxLayer,
265
+ layerCounts
266
+ };
267
+ }
268
+
269
+ return {
270
+ add,
271
+ delete: del,
272
+ search,
273
+ stats,
274
+ liveEntries: store.liveEntries,
275
+ cloneEmpty: () => createHNSWEngine(config),
276
+ // debug helpers
277
+ size: () => store.live,
278
+ getMaxLayer: () => maxLayer
279
+ };
280
+ }
281
+
282
+ export { createHNSWEngine };
@@ -0,0 +1,232 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // IVF engine — Inverted File Index
7
+ // clusters vectors, searches only nearby clusters
8
+ // requires train() before add()
9
+ //
10
+ // clustering is e-means in the index's own geometry, the same one search
11
+ // uses: spherical for 'cosine' (normalized vectors and centroids, highest
12
+ // dot product), euclidean for 'l2' (nearest centroid by ‖v − c‖²).
13
+ // ===========================
14
+
15
+ import { createRng, dotAt, normalizeAt } from '../math.js';
16
+ import { ERR, createError } from '../errors.js';
17
+ import { emeans } from '../clustering.js';
18
+ import { liveStats, makeStore, topKBySimilarity, filteredScan, filterPlan } from './engine-common.js';
19
+
20
+ // index of the closest centroid (module-level: hot loop).
21
+ // halfNorms: null for cosine (highest dot product); for l2, |c|²/2 per
22
+ // centroid — argmin ‖v − c‖² = argmax (v·c − |c|²/2)
23
+ function nearestCentroid(vecs, off, cents, nlist, d, halfNorms) {
24
+ let best = 0;
25
+ let bestSim = -Infinity;
26
+ for (let c = 0; c < nlist; c++) {
27
+ let sim = dotAt(vecs, off, cents, c * d, d);
28
+ if (halfNorms) sim -= halfNorms[c];
29
+ if (sim > bestSim) {
30
+ bestSim = sim;
31
+ best = c;
32
+ }
33
+ }
34
+ return best;
35
+ }
36
+
37
+ // |c|²/2 per centroid (l2, dot: assignment is euclidean), or null (cosine)
38
+ function centroidHalfNorms(cents, nlist, d, metric) {
39
+ if (metric === 'cosine') return null;
40
+ const h = new Float64Array(nlist);
41
+ for (let c = 0; c < nlist; c++) h[c] = dotAt(cents, c * d, cents, c * d, d) / 2;
42
+ return h;
43
+ }
44
+
45
+ function createIVFEngine(config) {
46
+ const d = config.dimensions;
47
+ const nlist = config.nlist;
48
+ const nprobe = config.nprobe;
49
+
50
+ if (nprobe > nlist) {
51
+ throw createError(ERR.INVALID_ARGUMENT, 'nprobe cannot be greater than nlist');
52
+ }
53
+
54
+ const rng = createRng(config.seed);
55
+ const emit = config.emit || (() => {});
56
+ const store = makeStore(config);
57
+
58
+ const metric = store.metric;
59
+ let centroids = null; // Float32Array(nlist * d), normalized for cosine
60
+ let halfNorms = null; // l2: |c|²/2 per centroid
61
+ let lists = null; // nlist arrays of slots (tombstones stay until compact)
62
+ let trained = false;
63
+
64
+ // ===========================
65
+ // train — e-means (k-means family), as a generator (time-sliced by the wrapper)
66
+ //
67
+ // the new centroids and inverted lists are built on the side and
68
+ // committed together at the end: a search between two slices always sees
69
+ // a consistent index. vectors already in the index are re-assigned to the
70
+ // new clusters, not dropped.
71
+ // ===========================
72
+ function* trainJob(vectors) {
73
+ const n = vectors.length;
74
+ if (n < nlist) {
75
+ throw createError(ERR.INVALID_ARGUMENT, 'need at least nlist=' + nlist + ' training vectors, got ' + n);
76
+ }
77
+
78
+ const flat = new Float32Array(n * d);
79
+ for (let i = 0; i < n; i++) {
80
+ flat.set(vectors[i], i * d);
81
+ if (metric === 'cosine') normalizeAt(flat, i * d, d);
82
+ }
83
+
84
+ // e-means (clustering.js): ~3 passes instead of Lloyd's 20, same or
85
+ // lower k-means loss. spherical (cosine): unit vectors, normalized
86
+ // centroids; euclidean (l2, dot): the vectors as given.
87
+ const cents = yield* emeans(flat, n, d, nlist, {
88
+ spherical: metric === 'cosine',
89
+ rng,
90
+ onEpoch(epoch, epochs) {
91
+ emit('progress', {
92
+ phase: 'kmeans',
93
+ iteration: epoch,
94
+ totalIterations: epochs,
95
+ percent: Math.round(epoch / epochs * 100)
96
+ });
97
+ }
98
+ });
99
+
100
+ // re-assign the live vectors already in the index
101
+ const newLists = [];
102
+ for (let c = 0; c < nlist; c++) newLists.push([]);
103
+ const hn = centroidHalfNorms(cents, nlist, d, metric);
104
+ const deleted = store.deletedFlags;
105
+ for (let s = 0; s < store.count; s++) {
106
+ if (deleted[s]) continue;
107
+ newLists[nearestCentroid(store.vectorOf(s), 0, cents, nlist, d, hn)].push(s);
108
+ yield;
109
+ }
110
+
111
+ adopt(cents, newLists);
112
+ }
113
+
114
+ function adopt(cents, newLists) {
115
+ centroids = cents;
116
+ halfNorms = centroidHalfNorms(cents, nlist, d, metric);
117
+ lists = newLists;
118
+ trained = true;
119
+ }
120
+
121
+ function add(id, vector, bytes) {
122
+ if (!trained) throw createError(ERR.NOT_TRAINED, 'IVF must be trained before add() — call train() first');
123
+ const list = nearestCentroid(store.input(vector), 0, centroids, nlist, d, halfNorms);
124
+ const slot = store.add(id, vector, bytes);
125
+ lists[list].push(slot);
126
+ }
127
+
128
+ function del(id) {
129
+ store.remove(id);
130
+ }
131
+
132
+ function search(query, k, accept) {
133
+ if (!trained) throw createError(ERR.NOT_TRAINED, 'IVF must be trained before search() — call train() first');
134
+ const q = store.input(query); // for picking clusters
135
+ const h = store.query(query); // for scoring vectors
136
+
137
+ // nprobe closest clusters (nlist is small: a sort is fine)
138
+ const order = new Array(nlist);
139
+ const sims = new Float64Array(nlist);
140
+ for (let c = 0; c < nlist; c++) {
141
+ order[c] = c;
142
+ // l2: nearest centroid; dot: largest ⟨q, c⟩ (as FAISS does); cosine: largest cos
143
+ sims[c] = dotAt(q, 0, centroids, c * d, d) - (metric === 'l2' ? halfNorms[c] : 0);
144
+ }
145
+ order.sort((a, b) => sims[b] - sims[a]);
146
+
147
+ const deleted = store.deletedFlags;
148
+ if (!accept) {
149
+ // the nprobe closest lists — and further ones while fewer than k live
150
+ // vectors were seen (lists emptied by deletes)
151
+ return topKBySimilarity(store, h, k, (visit) => {
152
+ let found = 0;
153
+ for (let p = 0; p < nlist && (p < nprobe || found < k); p++) {
154
+ const list = lists[order[p]];
155
+ for (let i = 0; i < list.length; i++) {
156
+ const s = list[i];
157
+ if (!deleted[s]) {
158
+ found++;
159
+ visit(s);
160
+ }
161
+ }
162
+ }
163
+ });
164
+ }
165
+ // filtered: a filter passing a fraction r of the vectors leaves r of
166
+ // every list, so probe nprobe / r lists to see as many candidates as an
167
+ // unfiltered search — and further ones (closest first) until k matching
168
+ // vectors were seen. very selective filters: exact scan of the matches
169
+ const plan = filterPlan(store, accept);
170
+ if (plan.scan) return filteredScan(store, h, k, accept);
171
+ const probes = Math.min(nlist, Math.ceil(nprobe * plan.widen));
172
+ return topKBySimilarity(store, h, k, (visit) => {
173
+ let found = 0;
174
+ for (let p = 0; p < nlist && (p < probes || found < k); p++) {
175
+ const list = lists[order[p]];
176
+ for (let i = 0; i < list.length; i++) {
177
+ const s = list[i];
178
+ if (!deleted[s] && accept(store.idOf(s))) {
179
+ found++;
180
+ visit(s);
181
+ }
182
+ }
183
+ }
184
+ });
185
+ }
186
+
187
+ function stats() {
188
+ const listSizes = new Array(nlist).fill(0);
189
+ if (trained) {
190
+ const deleted = store.deletedFlags;
191
+ for (let c = 0; c < nlist; c++) {
192
+ for (const s of lists[c]) if (!deleted[s]) listSizes[c]++;
193
+ }
194
+ }
195
+ const nonEmpty = listSizes.filter(x => x > 0);
196
+ return {
197
+ ...liveStats(store),
198
+ trained,
199
+ nlist,
200
+ nprobe,
201
+ emptyLists: nlist - nonEmpty.length,
202
+ avgListSize: nonEmpty.length > 0 ? parseFloat((store.live / nonEmpty.length).toFixed(1)) : 0,
203
+ maxListSize: nonEmpty.length > 0 ? Math.max(...nonEmpty) : 0,
204
+ minListSize: nonEmpty.length > 0 ? Math.min(...nonEmpty) : 0
205
+ };
206
+ }
207
+
208
+ // same configuration and same trained centroids, no vectors
209
+ function cloneEmpty() {
210
+ const clone = createIVFEngine(config);
211
+ if (trained) {
212
+ const empty = [];
213
+ for (let c = 0; c < nlist; c++) empty.push([]);
214
+ clone._adopt(centroids, empty);
215
+ }
216
+ return clone;
217
+ }
218
+
219
+ return {
220
+ add,
221
+ delete: del,
222
+ search,
223
+ stats,
224
+ trainJob,
225
+ liveEntries: store.liveEntries,
226
+ cloneEmpty,
227
+ _adopt: adopt,
228
+ size: () => store.live
229
+ };
230
+ }
231
+
232
+ export { createIVFEngine };
@@ -0,0 +1,70 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // pruneNeighbors — the neighbor-selection rule shared by every graph
7
+ //
8
+ // candidates are visited closest first; a candidate is kept unless an
9
+ // already kept one "occludes" it — sits between it and the center:
10
+ //
11
+ // α · d(kept, candidate) ≤ d(center, candidate)
12
+ //
13
+ // DiskANN's RobustPrune (Subramanya et al. 2019, Algorithm 2) with α ≥ 1:
14
+ // α > 1 keeps some longer edges, which make greedy search converge in fewer
15
+ // hops. HNSW's neighbor heuristic (Malkov & Yashunin 2018, Algorithm 4) is
16
+ // the same rule with α = 1 and a strict comparison, plus an optional top-up
17
+ // with the pruned candidates (keepPruned).
18
+ //
19
+ // cands the candidates (slots, or objects — whatever pairDist takes)
20
+ // dist distance of each candidate to the center (same order)
21
+ // pairDist (a, b) → distance between two candidates — create it once per
22
+ // engine, not per call: this runs hundreds of thousands of
23
+ // times during a build
24
+ // max keep at most this many
25
+ // alpha ≥ 1 (1 for HNSW)
26
+ // strict occluded only if strictly closer (HNSW)
27
+ // keepPruned top up with pruned candidates until max (HNSW construction)
28
+ // sorted cands/dist are already closest first (skip the sort)
29
+ // returns the kept candidates, closest first.
30
+ // ===========================
31
+
32
+ function pruneNeighbors(cands, dist, pairDist, max, alpha, strict, keepPruned, sorted) {
33
+ const n = cands.length;
34
+ let order = null;
35
+ if (!sorted) {
36
+ order = new Array(n);
37
+ for (let i = 0; i < n; i++) order[i] = i;
38
+ order.sort((a, b) => dist[a] - dist[b]);
39
+ }
40
+
41
+ const kept = [];
42
+ const keptAt = []; // their positions, for the top-up
43
+ for (let oi = 0; oi < n && kept.length < max; oi++) {
44
+ const i = order ? order[oi] : oi;
45
+ const c = cands[i], di = dist[i];
46
+ let occluded = false;
47
+ for (let s = 0; s < kept.length; s++) {
48
+ const d = alpha * pairDist(kept[s], c);
49
+ if (strict ? d < di : d <= di) {
50
+ occluded = true;
51
+ break;
52
+ }
53
+ }
54
+ if (!occluded) {
55
+ kept.push(c);
56
+ if (keepPruned) keptAt.push(i);
57
+ }
58
+ }
59
+ if (keepPruned && kept.length < max) {
60
+ const taken = new Uint8Array(n);
61
+ for (const i of keptAt) taken[i] = 1;
62
+ for (let oi = 0; oi < n && kept.length < max; oi++) {
63
+ const i = order ? order[oi] : oi;
64
+ if (!taken[i]) kept.push(cands[i]);
65
+ }
66
+ }
67
+ return kept;
68
+ }
69
+
70
+ export { pruneNeighbors };