@memberjunction/ai-vectors-memory 6.2.0-edge.1 → 6.2.0-edge.3

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 (38) hide show
  1. package/README.md +73 -12
  2. package/dist/index.d.ts +6 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +5 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/models/MetadataFilterEvaluator.d.ts +37 -0
  7. package/dist/models/MetadataFilterEvaluator.d.ts.map +1 -0
  8. package/dist/models/MetadataFilterEvaluator.js +233 -0
  9. package/dist/models/MetadataFilterEvaluator.js.map +1 -0
  10. package/dist/models/SimpleVectorDatabase.d.ts +55 -11
  11. package/dist/models/SimpleVectorDatabase.d.ts.map +1 -1
  12. package/dist/models/SimpleVectorDatabase.js +148 -35
  13. package/dist/models/SimpleVectorDatabase.js.map +1 -1
  14. package/dist/models/SimpleVectorService.d.ts +164 -12
  15. package/dist/models/SimpleVectorService.d.ts.map +1 -1
  16. package/dist/models/SimpleVectorService.js +612 -286
  17. package/dist/models/SimpleVectorService.js.map +1 -1
  18. package/dist/models/SimpleVectorServiceProvider.d.ts +151 -35
  19. package/dist/models/SimpleVectorServiceProvider.d.ts.map +1 -1
  20. package/dist/models/SimpleVectorServiceProvider.js +429 -106
  21. package/dist/models/SimpleVectorServiceProvider.js.map +1 -1
  22. package/dist/models/StoredVector.d.ts +35 -0
  23. package/dist/models/StoredVector.d.ts.map +1 -0
  24. package/dist/models/StoredVector.js +83 -0
  25. package/dist/models/StoredVector.js.map +1 -0
  26. package/dist/models/VectorAccelerator.d.ts +109 -0
  27. package/dist/models/VectorAccelerator.d.ts.map +1 -0
  28. package/dist/models/VectorAccelerator.js +97 -0
  29. package/dist/models/VectorAccelerator.js.map +1 -0
  30. package/dist/models/VectorKernels.d.ts +117 -0
  31. package/dist/models/VectorKernels.d.ts.map +1 -0
  32. package/dist/models/VectorKernels.js +338 -0
  33. package/dist/models/VectorKernels.js.map +1 -0
  34. package/dist/models/VectorStore.d.ts +157 -0
  35. package/dist/models/VectorStore.d.ts.map +1 -0
  36. package/dist/models/VectorStore.js +376 -0
  37. package/dist/models/VectorStore.js.map +1 -0
  38. package/package.json +4 -4
@@ -1,4 +1,7 @@
1
1
  import { LogError } from '@memberjunction/core';
2
+ import { CosineFromNorms, DotProductScore, EuclideanScore, HammingScore, IsKnownMetric, JaccardScore, ManhattanScore, MetricScore, SearchRows, SumOfSquares, } from './VectorKernels.js';
3
+ import { VectorStore } from './VectorStore.js';
4
+ import { BaseVectorAccelerator, VectorAcceleratorResolver, } from './VectorAccelerator.js';
2
5
  /**
3
6
  * SimpleVectorService provides in-memory vector similarity search capabilities.
4
7
  * This service is storage-agnostic and allows developers to manage their own vector persistence.
@@ -23,15 +26,65 @@ import { LogError } from '@memberjunction/core';
23
26
  * @public
24
27
  */
25
28
  export class SimpleVectorService {
26
- constructor() {
27
- this.vectors = new Map();
29
+ /**
30
+ * @param {SimpleVectorServiceOptions} [options] - Storage precision and an optional explicit accelerator
31
+ */
32
+ constructor(options) {
28
33
  this.expectedDimensions = null;
34
+ this.explicitAccelerator = options?.Accelerator;
35
+ // Resolve the allocator lazily: buffers are allocated on first write, by
36
+ // which time a server package may have registered a shared-memory accelerator.
37
+ this.store = new VectorStore(options?.Precision ?? 'float64', (bytes) => this.accelerator.AllocateBuffer(bytes));
38
+ }
39
+ /**
40
+ * Builds a read-only service over packed rows produced elsewhere — typically
41
+ * shared memory a worker thread received. Each row in `candidates` (or every
42
+ * live row) is keyed by `String(row)`, so results map straight back to rows.
43
+ */
44
+ static FromRowsView(view, precision, candidates) {
45
+ const service = new SimpleVectorService({ Precision: precision, Accelerator: new BaseVectorAccelerator() });
46
+ service.store = VectorStore.Adopt(view, precision, candidates);
47
+ service.expectedDimensions = view.Dims > 0 ? view.Dims : null;
48
+ return service;
49
+ }
50
+ /**
51
+ * Runs a clustering job in-process and returns it in rows. This is what a
52
+ * worker thread calls; it reuses the exact clustering code the service runs
53
+ * on the calling thread.
54
+ */
55
+ static RunClusterJob(job) {
56
+ const service = SimpleVectorService.FromRowsView(job.Snapshot, job.Snapshot.Precision, job.Candidates);
57
+ const result = job.Algorithm === 'kmeans'
58
+ ? service.KMeansCluster(job.K ?? 1, job.MaxIterations ?? 100, job.Metric, job.Tolerance ?? 0.0001)
59
+ : service.DBSCANCluster(job.Epsilon ?? 0.1, job.MinPoints ?? 1, job.Metric);
60
+ return SimpleVectorService.clusterResultToRows(result);
61
+ }
62
+ /** Process-unique identity of this service's storage, for diagnostics and accelerator caches. */
63
+ get StoreID() {
64
+ return this.store.StoreID;
65
+ }
66
+ /** The storage precision chosen at construction. */
67
+ get Precision() {
68
+ return this.store.Precision;
69
+ }
70
+ /**
71
+ * Pre-sizes storage for `additionalVectors` more vectors of `dimensions`
72
+ * each, so a loader adding rows one at a time allocates once instead of
73
+ * growing repeatedly. Optional; `LoadVectors` does this automatically.
74
+ *
75
+ * @throws {Error} If `dimensions` conflicts with vectors already loaded
76
+ */
77
+ ReserveCapacity(additionalVectors, dimensions) {
78
+ if (additionalVectors <= 0 || dimensions <= 0)
79
+ return;
80
+ this.validateAndSetDimensionCount(dimensions);
81
+ this.store.Reserve(additionalVectors, dimensions);
29
82
  }
30
83
  /**
31
84
  * Loads vectors into memory. Can accept either an array of VectorEntry objects
32
85
  * or a Map where keys are identifiers and values are vector arrays.
33
86
  *
34
- * @param {VectorEntry<TMetadata>[] | Map<string, number[]>} entries - The vectors to load
87
+ * @param {VectorInputEntry<TMetadata>[] | Map<string, VectorValues>} entries - The vectors to load; values may be `number[]` or a typed array
35
88
  * @throws {Error} If entries is null or undefined
36
89
  *
37
90
  * @example
@@ -56,16 +109,23 @@ export class SimpleVectorService {
56
109
  if (!entries) {
57
110
  throw new Error('Entries cannot be null or undefined');
58
111
  }
112
+ const incoming = entries instanceof Map ? entries.size : entries.length;
113
+ const firstVector = entries instanceof Map ? entries.values().next().value : entries[0]?.vector;
114
+ if (incoming > 0 && firstVector) {
115
+ // One allocation for the whole batch instead of repeated growth.
116
+ this.validateAndSetDimensions(firstVector);
117
+ this.store.Reserve(incoming, firstVector.length);
118
+ }
59
119
  if (entries instanceof Map) {
60
120
  entries.forEach((vector, key) => {
61
121
  this.validateAndSetDimensions(vector);
62
- this.vectors.set(key, { key, vector });
122
+ this.store.SetMetadata(this.store.Write(key, vector), undefined);
63
123
  });
64
124
  }
65
125
  else {
66
126
  entries.forEach(entry => {
67
127
  this.validateAndSetDimensions(entry.vector);
68
- this.vectors.set(entry.key, entry);
128
+ this.store.SetMetadata(this.store.Write(entry.key, entry.vector), entry.metadata);
69
129
  });
70
130
  }
71
131
  }
@@ -73,7 +133,7 @@ export class SimpleVectorService {
73
133
  * Adds or updates a single vector in the service
74
134
  *
75
135
  * @param {string} key - The unique identifier for the vector
76
- * @param {number[]} vector - The vector/embedding array
136
+ * @param {VectorValues} vector - The vector/embedding values (`number[]` or a typed array; copied)
77
137
  * @param {TMetadata} metadata - Optional metadata to associate with the vector
78
138
  * @throws {Error} If key is null/undefined, or if vector is invalid
79
139
  *
@@ -96,7 +156,7 @@ export class SimpleVectorService {
96
156
  throw new Error('Vector cannot be null, undefined, or empty');
97
157
  }
98
158
  this.validateAndSetDimensions(vector);
99
- this.vectors.set(key, { key, vector, metadata });
159
+ this.store.SetMetadata(this.store.Write(key, vector), metadata);
100
160
  }
101
161
  /**
102
162
  * Finds the K nearest neighbors to a query vector using the specified similarity metric
@@ -137,34 +197,188 @@ export class SimpleVectorService {
137
197
  * @method
138
198
  */
139
199
  FindNearest(queryVector, topK = 10, threshold, metric = 'cosine', filter) {
200
+ const plan = this.planSearch(queryVector, topK, threshold, metric, filter);
201
+ if (!plan)
202
+ return [];
203
+ if (plan.Mode === 'custom')
204
+ return this.searchWithCustomMetric(plan);
205
+ const fast = this.accelerator.TrySearchSync(plan.Job);
206
+ if (fast)
207
+ return this.finalizeSearch(plan, fast, true);
208
+ return this.finalizeSearch(plan, SearchRows(plan.Job.Snapshot, plan.Job), false);
209
+ }
210
+ /**
211
+ * Async form of {@link FindNearest} with identical arguments and results.
212
+ * Server hosts register an accelerator that runs large searches on a worker
213
+ * thread (and/or a native backend), so the calling thread — typically the
214
+ * one serving every other request — is not blocked by the scan. With no
215
+ * accelerator registered it runs in-process exactly like `FindNearest`.
216
+ *
217
+ * @public
218
+ * @method
219
+ */
220
+ async FindNearestAsync(queryVector, topK = 10, threshold, metric = 'cosine', filter) {
221
+ const plan = this.planSearch(queryVector, topK, threshold, metric, filter);
222
+ if (!plan)
223
+ return [];
224
+ if (plan.Mode === 'custom')
225
+ return this.searchWithCustomMetric(plan);
226
+ const rows = await this.accelerator.SearchAsync(plan.Job);
227
+ return this.finalizeSearch(plan, rows, true);
228
+ }
229
+ /**
230
+ * Validates a search and turns it into a job over the packed store.
231
+ * Returns null when the search can only produce an empty result.
232
+ */
233
+ planSearch(queryVector, topK, threshold, metric, filter) {
140
234
  if (!queryVector || queryVector.length === 0) {
141
235
  throw new Error('Query vector cannot be null, undefined, or empty');
142
236
  }
143
- // Pre-filter vectors by metadata BEFORE similarity calculation
144
- const candidateVectors = filter
145
- ? Array.from(this.vectors.values()).filter(entry => entry.metadata && filter(entry.metadata))
146
- : Array.from(this.vectors.values());
147
- // Calculate similarity ONLY for filtered candidates
148
- const results = candidateVectors
149
- .map(entry => {
237
+ const candidates = filter ? this.filterRows(filter) : null;
238
+ const candidateCount = candidates ? candidates.length : this.store.Size;
239
+ if (candidateCount === 0)
240
+ return null;
241
+ const custom = this.usesCustomMetric;
242
+ // A bad metric or dimension count fails every row identically. The service
243
+ // has always logged and returned no results rather than thrown; keep that,
244
+ // but log once instead of once per row.
245
+ if (!custom && !IsKnownMetric(metric)) {
246
+ LogError(`Error calculating ${metric} similarity: Unknown distance metric: ${metric}`);
247
+ return null;
248
+ }
249
+ if (!custom && this.store.Dims !== queryVector.length) {
250
+ LogError(`Error calculating ${metric} similarity: Vectors must have same dimensions. Got ${queryVector.length} and ${this.store.Dims}`);
251
+ return null;
252
+ }
253
+ const k = Math.trunc(topK);
254
+ const bounded = k >= 1 && k < candidateCount;
255
+ const plan = {
256
+ Mode: custom ? 'custom' : 'kernel',
257
+ QueryVector: queryVector,
258
+ TopK: topK,
259
+ Metric: metric,
260
+ Threshold: threshold == null ? null : threshold,
261
+ Filter: filter,
262
+ KeysAtDispatch: this.store.Keys,
263
+ VersionAtDispatch: this.store.Version,
264
+ Job: this.buildSearchJob(queryVector, bounded ? k : null, threshold, metric, candidates),
265
+ };
266
+ return plan;
267
+ }
268
+ buildSearchJob(queryVector, topK, threshold, metric, candidates) {
269
+ const query = this.store.ToStorePrecision(queryVector);
270
+ const spec = {
271
+ Query: query,
272
+ QueryNormSq: SumOfSquares(query, 0, query.length),
273
+ Candidates: candidates,
274
+ Metric: metric,
275
+ TopK: topK,
276
+ Threshold: threshold == null ? null : threshold,
277
+ };
278
+ return { ...spec, Snapshot: this.store.Snapshot(), Source: this.store };
279
+ }
280
+ /** Ascending live rows whose metadata passes the filter (rows without metadata never do). */
281
+ filterRows(filter) {
282
+ const rows = [];
283
+ const rowCount = this.store.RowCount;
284
+ for (let row = 0; row < rowCount; row++) {
285
+ if (!this.store.IsLive(row))
286
+ continue;
287
+ const metadata = this.store.MetadataAt(row);
288
+ if (metadata && filter(metadata))
289
+ rows.push(row);
290
+ }
291
+ return Int32Array.from(rows);
292
+ }
293
+ /**
294
+ * Turns ranked rows into results. When the rows came from somewhere other
295
+ * than an in-process scan of the current store (another thread, a native
296
+ * backend, an approximate index) they are re-scored against the live store,
297
+ * so a concurrent write or a lower-precision backend can never surface a
298
+ * wrong score. `topK` is applied with `Array.slice` semantics, as before.
299
+ */
300
+ finalizeSearch(plan, ranked, rescore) {
301
+ const exact = !rescore && plan.VersionAtDispatch === this.store.Version;
302
+ const hits = exact ? this.hitsFromRows(ranked) : this.rescoreRows(plan, ranked);
303
+ return hits.slice(0, plan.TopK).map(hit => ({
304
+ key: this.store.KeyAt(hit.Row),
305
+ score: hit.Score,
306
+ metadata: this.store.MetadataAt(hit.Row),
307
+ }));
308
+ }
309
+ hitsFromRows(ranked) {
310
+ const hits = new Array(ranked.Rows.length);
311
+ for (let i = 0; i < ranked.Rows.length; i++) {
312
+ hits[i] = { Row: ranked.Rows[i], Score: ranked.Scores[i] };
313
+ }
314
+ return hits;
315
+ }
316
+ /** Maps rows from the dispatch-time snapshot to current rows and scores them exactly. */
317
+ rescoreRows(plan, ranked) {
318
+ const job = plan.Job;
319
+ const view = this.store.View();
320
+ const seen = new Set();
321
+ const hits = [];
322
+ for (let i = 0; i < ranked.Rows.length; i++) {
323
+ const key = plan.KeysAtDispatch[ranked.Rows[i]];
324
+ const row = key == null ? undefined : this.store.RowOf(key);
325
+ if (row === undefined || seen.has(row))
326
+ continue;
327
+ seen.add(row);
328
+ if (plan.Filter) {
329
+ const metadata = this.store.MetadataAt(row);
330
+ if (!metadata || !plan.Filter(metadata))
331
+ continue;
332
+ }
333
+ const score = MetricScore(job.Metric, job.Query, 0, job.QueryNormSq, view.Data, row * view.Dims, view.Norms[row], view.Dims);
334
+ if (score !== score)
335
+ continue; // NaN
336
+ if (job.Threshold !== null && !(score >= job.Threshold))
337
+ continue;
338
+ hits.push({ Row: row, Score: score });
339
+ }
340
+ hits.sort((a, b) => (b.Score - a.Score) || (a.Row - b.Row));
341
+ return job.TopK === null ? hits : hits.slice(0, job.TopK);
342
+ }
343
+ /**
344
+ * Subclasses that override a metric method keep working: rank with their
345
+ * override, one row at a time, exactly as the service did before packing.
346
+ */
347
+ searchWithCustomMetric(plan) {
348
+ const rows = plan.Job.Candidates ?? this.store.LiveRows();
349
+ const results = [];
350
+ for (let i = 0; i < rows.length; i++) {
351
+ const row = rows[i];
352
+ const key = this.store.KeyAt(row);
150
353
  try {
151
- return {
152
- key: entry.key,
153
- score: this.CalculateDistance(queryVector, entry.vector, metric),
154
- metadata: entry.metadata
155
- };
354
+ const score = this.CalculateDistance(plan.QueryVector, this.store.ReadRow(row), plan.Metric);
355
+ if (plan.Threshold === null || score >= plan.Threshold) {
356
+ results.push({ key, score, metadata: this.store.MetadataAt(row) });
357
+ }
156
358
  }
157
359
  catch (error) {
158
- // Log error and skip this entry
159
- LogError(`Error calculating ${metric} similarity for key ${entry.key}: ${error}`);
160
- return null;
360
+ LogError(`Error calculating ${plan.Metric} similarity for key ${key}: ${error}`);
161
361
  }
162
- })
163
- .filter(result => result !== null)
164
- .filter(result => threshold == null || result.score >= threshold)
165
- .sort((a, b) => b.score - a.score)
166
- .slice(0, topK);
167
- return results;
362
+ }
363
+ return results.sort((a, b) => b.score - a.score).slice(0, plan.TopK);
364
+ }
365
+ /** The accelerator this service uses: the explicit one, else the process-wide registration. */
366
+ get accelerator() {
367
+ return this.explicitAccelerator ?? VectorAcceleratorResolver.Instance.Current;
368
+ }
369
+ /**
370
+ * True when a subclass overrides any metric method. The packed kernels
371
+ * cannot call an override, so such subclasses are scored row by row.
372
+ */
373
+ get usesCustomMetric() {
374
+ const base = SimpleVectorService.prototype;
375
+ return this.CalculateDistance !== base.CalculateDistance
376
+ || this.CosineSimilarity !== base.CosineSimilarity
377
+ || this.EuclideanDistance !== base.EuclideanDistance
378
+ || this.ManhattanDistance !== base.ManhattanDistance
379
+ || this.DotProduct !== base.DotProduct
380
+ || this.JaccardSimilarity !== base.JaccardSimilarity
381
+ || this.HammingDistance !== base.HammingDistance;
168
382
  }
169
383
  /**
170
384
  * Finds vectors similar to an existing vector identified by its key.
@@ -203,12 +417,12 @@ export class SimpleVectorService {
203
417
  * @method
204
418
  */
205
419
  FindSimilar(key, topK = 10, threshold, metric = 'cosine', filter) {
206
- const sourceVector = this.vectors.get(key);
207
- if (!sourceVector) {
420
+ const row = this.store.RowOf(key);
421
+ if (row === undefined) {
208
422
  throw new Error(`Vector with key "${key}" not found`);
209
423
  }
210
424
  // Get topK + 1 to account for excluding self
211
- return this.FindNearest(sourceVector.vector, topK + 1, threshold, metric, filter)
425
+ return this.FindNearest(this.store.ReadRow(row), topK + 1, threshold, metric, filter)
212
426
  .filter(result => result.key !== key) // Exclude self
213
427
  .slice(0, topK);
214
428
  }
@@ -230,15 +444,19 @@ export class SimpleVectorService {
230
444
  * @method
231
445
  */
232
446
  Similarity(key1, key2) {
233
- const v1 = this.vectors.get(key1);
234
- const v2 = this.vectors.get(key2);
235
- if (!v1) {
447
+ const row1 = this.store.RowOf(key1);
448
+ const row2 = this.store.RowOf(key2);
449
+ if (row1 === undefined) {
236
450
  throw new Error(`Vector with key "${key1}" not found`);
237
451
  }
238
- if (!v2) {
452
+ if (row2 === undefined) {
239
453
  throw new Error(`Vector with key "${key2}" not found`);
240
454
  }
241
- return this.CosineSimilarity(v1.vector, v2.vector);
455
+ if (this.usesCustomMetric) {
456
+ return this.CosineSimilarity(this.store.ReadRow(row1), this.store.ReadRow(row2));
457
+ }
458
+ const view = this.store.View();
459
+ return CosineFromNorms(view.Data, row1 * view.Dims, view.Norms[row1], view.Data, row2 * view.Dims, view.Norms[row2], view.Dims);
242
460
  }
243
461
  /**
244
462
  * Calculates cosine similarity between two vectors using the formula:
@@ -297,35 +515,8 @@ export class SimpleVectorService {
297
515
  if (a.length !== b.length) {
298
516
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
299
517
  }
300
- // Initialize our three accumulator variables:
301
- // - dotProduct: Sum of element-wise products (measures alignment)
302
- // - normA: Sum of squares for vector A (used to calculate magnitude)
303
- // - normB: Sum of squares for vector B (used to calculate magnitude)
304
- let dotProduct = 0;
305
- let normA = 0;
306
- let normB = 0;
307
- // Single pass through both vectors to calculate all needed values
308
- // This is more efficient than multiple loops
309
- for (let i = 0; i < a.length; i++) {
310
- // Dot product: Multiply corresponding elements and sum them
311
- // This measures how much the vectors "agree" at each dimension
312
- dotProduct += a[i] * b[i];
313
- // Calculate sum of squares for each vector
314
- // These will be used to normalize the dot product
315
- normA += a[i] * a[i]; // Same as Math.pow(a[i], 2) but faster
316
- normB += b[i] * b[i]; // Same as Math.pow(b[i], 2) but faster
317
- }
318
- // Handle edge case: Zero vectors (all elements are 0)
319
- // A zero vector has no direction, so similarity is undefined
320
- // We return 0 by convention (neither similar nor dissimilar)
321
- if (normA === 0 || normB === 0) {
322
- return 0;
323
- }
324
- // Final calculation: Normalize the dot product by the magnitudes
325
- // Math.sqrt(normA) = magnitude of vector A (||A||)
326
- // Math.sqrt(normB) = magnitude of vector B (||B||)
327
- // This gives us the cosine of the angle between the vectors
328
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
518
+ // Zero vectors have no direction, so the kernel returns 0 for them by convention
519
+ return CosineFromNorms(a, 0, SumOfSquares(a, 0, a.length), b, 0, SumOfSquares(b, 0, b.length), a.length);
329
520
  }
330
521
  /**
331
522
  * Calculates Euclidean distance between two vectors, normalized to 0-1 range.
@@ -371,14 +562,8 @@ export class SimpleVectorService {
371
562
  if (a.length !== b.length) {
372
563
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
373
564
  }
374
- let sumSquaredDiff = 0;
375
- for (let i = 0; i < a.length; i++) {
376
- const diff = a[i] - b[i];
377
- sumSquaredDiff += diff * diff;
378
- }
379
- const distance = Math.sqrt(sumSquaredDiff);
380
- // Normalize to 0-1 range: closer = higher score
381
- return 1 / (1 + distance);
565
+ // Normalized to 0-1: closer = higher score
566
+ return EuclideanScore(a, 0, b, 0, a.length);
382
567
  }
383
568
  /**
384
569
  * Calculates Manhattan distance between two vectors, normalized to 0-1 range.
@@ -426,12 +611,7 @@ export class SimpleVectorService {
426
611
  if (a.length !== b.length) {
427
612
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
428
613
  }
429
- let sumAbsDiff = 0;
430
- for (let i = 0; i < a.length; i++) {
431
- sumAbsDiff += Math.abs(a[i] - b[i]);
432
- }
433
- // Normalize to 0-1 range
434
- return 1 / (1 + sumAbsDiff);
614
+ return ManhattanScore(a, 0, b, 0, a.length);
435
615
  }
436
616
  /**
437
617
  * Calculates dot product similarity between two vectors, normalized to 0-1 range.
@@ -478,16 +658,7 @@ export class SimpleVectorService {
478
658
  if (a.length !== b.length) {
479
659
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
480
660
  }
481
- let dotProduct = 0;
482
- for (let i = 0; i < a.length; i++) {
483
- dotProduct += a[i] * b[i];
484
- }
485
- // Normalize using tanh for bounded output
486
- // Scale factor based on expected vector dimensions
487
- const scale = Math.sqrt(a.length);
488
- const normalized = Math.tanh(dotProduct / scale);
489
- // Convert from [-1, 1] to [0, 1]
490
- return (normalized + 1) / 2;
661
+ return DotProductScore(a, 0, b, 0, a.length);
491
662
  }
492
663
  /**
493
664
  * Calculates Jaccard similarity between two vectors treated as sets.
@@ -539,23 +710,7 @@ export class SimpleVectorService {
539
710
  if (a.length !== b.length) {
540
711
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
541
712
  }
542
- let intersection = 0;
543
- let union = 0;
544
- for (let i = 0; i < a.length; i++) {
545
- const aPresent = a[i] !== 0;
546
- const bPresent = b[i] !== 0;
547
- if (aPresent && bPresent) {
548
- intersection++;
549
- }
550
- if (aPresent || bPresent) {
551
- union++;
552
- }
553
- }
554
- // Handle edge case: both vectors are all zeros
555
- if (union === 0) {
556
- return 1; // Consider empty sets as identical
557
- }
558
- return intersection / union;
713
+ return JaccardScore(a, 0, b, 0, a.length);
559
714
  }
560
715
  /**
561
716
  * Calculates Hamming distance between two vectors, normalized to similarity score.
@@ -607,14 +762,7 @@ export class SimpleVectorService {
607
762
  if (a.length !== b.length) {
608
763
  throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
609
764
  }
610
- let differences = 0;
611
- for (let i = 0; i < a.length; i++) {
612
- if (a[i] !== b[i]) {
613
- differences++;
614
- }
615
- }
616
- // Normalize to similarity score (1 = identical, 0 = all different)
617
- return 1 - (differences / a.length);
765
+ return HammingScore(a, 0, b, 0, a.length);
618
766
  }
619
767
  /**
620
768
  * Calculates distance/similarity between two vectors using the specified metric.
@@ -662,7 +810,7 @@ export class SimpleVectorService {
662
810
  * @readonly
663
811
  */
664
812
  get Size() {
665
- return this.vectors.size;
813
+ return this.store.Size;
666
814
  }
667
815
  /**
668
816
  * Clears all vectors from memory
@@ -677,7 +825,7 @@ export class SimpleVectorService {
677
825
  * @method
678
826
  */
679
827
  Clear() {
680
- this.vectors.clear();
828
+ this.store.Clear();
681
829
  }
682
830
  /**
683
831
  * Checks if a vector with the given key exists
@@ -696,13 +844,13 @@ export class SimpleVectorService {
696
844
  * @method
697
845
  */
698
846
  Has(key) {
699
- return this.vectors.has(key);
847
+ return this.store.Has(key);
700
848
  }
701
849
  /**
702
850
  * Retrieves a specific vector by its key
703
851
  *
704
852
  * @param {string} key - The key of the vector to retrieve
705
- * @returns {number[] | undefined} The vector array, or undefined if not found
853
+ * @returns {number[] | undefined} A copy of the vector, or undefined if not found
706
854
  *
707
855
  * @example
708
856
  * ```typescript
@@ -716,7 +864,8 @@ export class SimpleVectorService {
716
864
  * @method
717
865
  */
718
866
  GetVector(key) {
719
- return this.vectors.get(key)?.vector;
867
+ const row = this.store.RowOf(key);
868
+ return row === undefined ? undefined : this.store.ReadRow(row);
720
869
  }
721
870
  /**
722
871
  * Retrieves the metadata associated with a specific vector
@@ -736,7 +885,8 @@ export class SimpleVectorService {
736
885
  * @method
737
886
  */
738
887
  GetMetadata(key) {
739
- return this.vectors.get(key)?.metadata;
888
+ const row = this.store.RowOf(key);
889
+ return row === undefined ? undefined : this.store.MetadataAt(row);
740
890
  }
741
891
  /**
742
892
  * Updates an existing vector entry in-place, allowing partial updates to the vector data,
@@ -777,8 +927,8 @@ export class SimpleVectorService {
777
927
  * @method
778
928
  */
779
929
  UpdateVector(key, updates) {
780
- const existing = this.vectors.get(key);
781
- if (!existing) {
930
+ const row = this.store.RowOf(key);
931
+ if (row === undefined) {
782
932
  throw new Error(`Vector with key "${key}" not found. Use AddVector to create new entries.`);
783
933
  }
784
934
  if (updates.vector == null && updates.metadata == null) {
@@ -789,10 +939,10 @@ export class SimpleVectorService {
789
939
  throw new Error('Vector cannot be empty');
790
940
  }
791
941
  this.validateAndSetDimensions(updates.vector);
792
- existing.vector = updates.vector;
942
+ this.store.Write(key, updates.vector);
793
943
  }
794
944
  if (updates.metadata != null) {
795
- existing.metadata = updates.metadata;
945
+ this.store.SetMetadata(row, updates.metadata);
796
946
  }
797
947
  return true;
798
948
  }
@@ -828,7 +978,7 @@ export class SimpleVectorService {
828
978
  if (!vector || vector.length === 0) {
829
979
  throw new Error('Vector cannot be null, undefined, or empty');
830
980
  }
831
- const exists = this.vectors.has(key);
981
+ const exists = this.store.Has(key);
832
982
  if (exists) {
833
983
  this.UpdateVector(key, { vector, metadata });
834
984
  }
@@ -854,7 +1004,7 @@ export class SimpleVectorService {
854
1004
  * @method
855
1005
  */
856
1006
  RemoveVector(key) {
857
- return this.vectors.delete(key);
1007
+ return this.store.Remove(key);
858
1008
  }
859
1009
  /**
860
1010
  * Gets all keys currently stored in the service
@@ -871,13 +1021,13 @@ export class SimpleVectorService {
871
1021
  * @method
872
1022
  */
873
1023
  GetAllKeys() {
874
- return Array.from(this.vectors.keys());
1024
+ return Array.from(this.store.LiveRows(), row => this.store.KeyAt(row));
875
1025
  }
876
1026
  /**
877
1027
  * Exports all vectors as an array of VectorEntry objects.
878
1028
  * Useful for persistence or transferring data.
879
1029
  *
880
- * @returns {VectorEntry<TMetadata>[]} Array of all vector entries
1030
+ * @returns {VectorEntry<TMetadata>[]} Array of all vector entries (vectors are copies)
881
1031
  *
882
1032
  * @example
883
1033
  * ```typescript
@@ -890,7 +1040,11 @@ export class SimpleVectorService {
890
1040
  * @method
891
1041
  */
892
1042
  ExportVectors() {
893
- return Array.from(this.vectors.values());
1043
+ return Array.from(this.store.LiveRows(), row => ({
1044
+ key: this.store.KeyAt(row),
1045
+ vector: this.store.ReadRow(row),
1046
+ metadata: this.store.MetadataAt(row),
1047
+ }));
894
1048
  }
895
1049
  /**
896
1050
  * Validates vector dimensions and sets expected dimensions if not yet set.
@@ -903,12 +1057,15 @@ export class SimpleVectorService {
903
1057
  * @method
904
1058
  */
905
1059
  validateAndSetDimensions(vector) {
1060
+ this.validateAndSetDimensionCount(vector.length);
1061
+ }
1062
+ validateAndSetDimensionCount(dimensions) {
906
1063
  if (this.expectedDimensions === null) {
907
1064
  // First vector sets the expected dimensions
908
- this.expectedDimensions = vector.length;
1065
+ this.expectedDimensions = dimensions;
909
1066
  }
910
- else if (vector.length !== this.expectedDimensions) {
911
- throw new Error(`Vector dimension mismatch. Expected ${this.expectedDimensions} dimensions, got ${vector.length}. ` +
1067
+ else if (dimensions !== this.expectedDimensions) {
1068
+ throw new Error(`Vector dimension mismatch. Expected ${this.expectedDimensions} dimensions, got ${dimensions}. ` +
912
1069
  `All vectors must have the same number of dimensions for similarity calculations to work.`);
913
1070
  }
914
1071
  }
@@ -953,7 +1110,7 @@ export class SimpleVectorService {
953
1110
  * @method
954
1111
  */
955
1112
  FindAboveThreshold(queryVector, threshold, metric = 'cosine', filter) {
956
- return this.FindNearest(queryVector, this.vectors.size, threshold, metric, filter);
1113
+ return this.FindNearest(queryVector, this.store.Size, threshold, metric, filter);
957
1114
  }
958
1115
  // ============================================================================
959
1116
  // PHASE 2: CLUSTERING ALGORITHMS
@@ -1000,57 +1157,28 @@ export class SimpleVectorService {
1000
1157
  * @method
1001
1158
  */
1002
1159
  KMeansCluster(k, maxIterations = 100, metric = 'euclidean', tolerance = 0.0001) {
1003
- if (k <= 0 || k > this.vectors.size) {
1004
- throw new Error(`Invalid k: ${k}. Must be between 1 and ${this.vectors.size}`);
1005
- }
1006
- const entries = Array.from(this.vectors.values());
1007
- if (entries.length === 0) {
1008
- throw new Error('No vectors loaded for clustering');
1160
+ if (k <= 0 || k > this.store.Size) {
1161
+ throw new Error(`Invalid k: ${k}. Must be between 1 and ${this.store.Size}`);
1009
1162
  }
1163
+ // Non-empty: the k check above rejects an empty store.
1164
+ const rows = this.store.LiveRows();
1165
+ const scorer = this.createScorer(metric);
1010
1166
  // Initialize centroids using K-Means++
1011
- const centroids = this.initializeKMeansPlusPlus(entries, k, metric);
1012
- let assignments = new Map();
1167
+ const centroids = this.initializeKMeansPlusPlus(rows, k, scorer);
1168
+ let assignments = null;
1013
1169
  let iterations = 0;
1014
1170
  let converged = false;
1015
1171
  while (iterations < maxIterations && !converged) {
1016
1172
  // Assignment step: assign each point to nearest centroid
1017
- const newAssignments = new Map();
1018
- entries.forEach(entry => {
1019
- let minDistance = Infinity;
1020
- let assignedCluster = 0;
1021
- centroids.forEach((centroid, clusterId) => {
1022
- const distance = 1 - this.CalculateDistance(entry.vector, centroid, metric);
1023
- if (distance < minDistance) {
1024
- minDistance = distance;
1025
- assignedCluster = clusterId;
1026
- }
1027
- });
1028
- newAssignments.set(entry.key, assignedCluster);
1029
- });
1173
+ const newAssignments = this.assignToNearestCentroid(rows, centroids, scorer);
1030
1174
  // Check for convergence
1031
- converged = this.checkConvergence(assignments, newAssignments);
1175
+ converged = assignments !== null && this.sameAssignments(assignments, newAssignments);
1032
1176
  assignments = newAssignments;
1033
1177
  if (!converged) {
1034
- // Update step: recalculate centroids
1035
- const newCentroids = new Map();
1036
- for (let clusterId = 0; clusterId < k; clusterId++) {
1037
- const clusterMembers = entries.filter(e => assignments.get(e.key) === clusterId);
1038
- if (clusterMembers.length > 0) {
1039
- newCentroids.set(clusterId, this.FindCentroid(clusterMembers.map(m => m.vector)));
1040
- }
1041
- else {
1042
- // Empty cluster - keep old centroid
1043
- newCentroids.set(clusterId, centroids.get(clusterId));
1044
- }
1045
- }
1046
- // Check if centroids moved significantly
1047
- let maxCentroidMovement = 0;
1048
- newCentroids.forEach((newCentroid, clusterId) => {
1049
- const oldCentroid = centroids.get(clusterId);
1050
- const movement = 1 - this.CalculateDistance(oldCentroid, newCentroid, 'euclidean');
1051
- maxCentroidMovement = Math.max(maxCentroidMovement, movement);
1052
- });
1053
- if (maxCentroidMovement < tolerance) {
1178
+ // Update step: recalculate centroids, keeping the old one for an empty cluster
1179
+ const newCentroids = this.recomputeCentroids(rows, assignments, k, centroids);
1180
+ // Stop when no centroid moved significantly
1181
+ if (this.maxCentroidMovement(centroids, newCentroids, scorer) < tolerance) {
1054
1182
  converged = true;
1055
1183
  }
1056
1184
  centroids.clear();
@@ -1058,30 +1186,33 @@ export class SimpleVectorService {
1058
1186
  }
1059
1187
  iterations++;
1060
1188
  }
1061
- // Build result
1189
+ return this.buildKMeansResult(rows, assignments ?? this.assignToNearestCentroid(rows, centroids, scorer), centroids, k, metric, iterations, scorer);
1190
+ }
1191
+ /** Assembles the K-Means result: members per cluster in insertion order, inertia, silhouette. */
1192
+ buildKMeansResult(rows, assignments, centroids, k, metric, iterations, scorer) {
1062
1193
  const clusters = new Map();
1063
1194
  for (let i = 0; i < k; i++) {
1064
1195
  clusters.set(i, []);
1065
1196
  }
1066
- assignments.forEach((clusterId, key) => {
1067
- clusters.get(clusterId).push(key);
1068
- });
1197
+ for (let i = 0; i < rows.length; i++) {
1198
+ clusters.get(assignments[i]).push(this.store.KeyAt(rows[i]));
1199
+ }
1069
1200
  // Calculate inertia (sum of squared distances to centroids)
1070
1201
  let inertia = 0;
1071
- entries.forEach(entry => {
1072
- const clusterId = assignments.get(entry.key);
1073
- const centroid = centroids.get(clusterId);
1074
- const distance = 1 - this.CalculateDistance(entry.vector, centroid, metric);
1202
+ for (let i = 0; i < rows.length; i++) {
1203
+ const distance = 1 - scorer.RowVsCentroid(rows[i], centroids.get(assignments[i]));
1075
1204
  inertia += distance * distance;
1076
- });
1205
+ }
1206
+ const publicCentroids = new Map();
1207
+ centroids.forEach((centroid, id) => publicCentroids.set(id, Array.from(centroid.Values)));
1077
1208
  return {
1078
1209
  clusters,
1079
- centroids,
1210
+ centroids: publicCentroids,
1080
1211
  metadata: {
1081
1212
  metric,
1082
1213
  iterations,
1083
1214
  inertia,
1084
- silhouetteScore: this.SilhouetteScore({ clusters, centroids }, metric)
1215
+ silhouetteScore: this.SilhouetteScore({ clusters, centroids: publicCentroids }, metric)
1085
1216
  }
1086
1217
  };
1087
1218
  }
@@ -1091,49 +1222,129 @@ export class SimpleVectorService {
1091
1222
  *
1092
1223
  * @private
1093
1224
  */
1094
- initializeKMeansPlusPlus(entries, k, metric) {
1225
+ initializeKMeansPlusPlus(rows, k, scorer) {
1095
1226
  const centroids = new Map();
1096
1227
  // Choose first centroid randomly
1097
- const firstIdx = Math.floor(Math.random() * entries.length);
1098
- centroids.set(0, [...entries[firstIdx].vector]);
1228
+ const firstIdx = Math.floor(Math.random() * rows.length);
1229
+ centroids.set(0, this.centroidFromRow(rows[firstIdx]));
1099
1230
  // Choose remaining centroids
1100
1231
  for (let i = 1; i < k; i++) {
1101
- const distances = entries.map(entry => {
1232
+ const distances = new Float64Array(rows.length);
1233
+ for (let j = 0; j < rows.length; j++) {
1102
1234
  let minDist = Infinity;
1103
1235
  centroids.forEach(centroid => {
1104
- const dist = 1 - this.CalculateDistance(entry.vector, centroid, metric);
1105
- minDist = Math.min(minDist, dist);
1236
+ minDist = Math.min(minDist, 1 - scorer.RowVsCentroid(rows[j], centroid));
1106
1237
  });
1107
- return minDist;
1108
- });
1238
+ distances[j] = minDist;
1239
+ }
1109
1240
  // Choose next centroid with probability proportional to squared distance
1110
- const sumSquaredDist = distances.reduce((sum, d) => sum + d * d, 0);
1111
- let threshold = Math.random() * sumSquaredDist;
1241
+ let sumSquaredDist = 0;
1242
+ for (let j = 0; j < distances.length; j++) {
1243
+ sumSquaredDist += distances[j] * distances[j];
1244
+ }
1245
+ const threshold = Math.random() * sumSquaredDist;
1112
1246
  let cumSum = 0;
1113
- for (let j = 0; j < entries.length; j++) {
1247
+ for (let j = 0; j < rows.length; j++) {
1114
1248
  cumSum += distances[j] * distances[j];
1115
1249
  if (cumSum >= threshold) {
1116
- centroids.set(i, [...entries[j].vector]);
1250
+ centroids.set(i, this.centroidFromRow(rows[j]));
1117
1251
  break;
1118
1252
  }
1119
1253
  }
1120
1254
  }
1121
1255
  return centroids;
1122
1256
  }
1257
+ /** Index of the nearest centroid for each row (first centroid wins a tie). */
1258
+ assignToNearestCentroid(rows, centroids, scorer) {
1259
+ const assignments = new Int32Array(rows.length);
1260
+ for (let i = 0; i < rows.length; i++) {
1261
+ let minDistance = Infinity;
1262
+ let assignedCluster = 0;
1263
+ centroids.forEach((centroid, clusterId) => {
1264
+ const distance = 1 - scorer.RowVsCentroid(rows[i], centroid);
1265
+ if (distance < minDistance) {
1266
+ minDistance = distance;
1267
+ assignedCluster = clusterId;
1268
+ }
1269
+ });
1270
+ assignments[i] = assignedCluster;
1271
+ }
1272
+ return assignments;
1273
+ }
1274
+ /** Mean of each cluster's members, summed in insertion order like {@link FindCentroid}. */
1275
+ recomputeCentroids(rows, assignments, k, previous) {
1276
+ const dims = this.store.Dims;
1277
+ const view = this.store.View();
1278
+ const sums = [];
1279
+ const counts = new Int32Array(k);
1280
+ for (let c = 0; c < k; c++)
1281
+ sums.push(new Float64Array(dims));
1282
+ for (let i = 0; i < rows.length; i++) {
1283
+ const sum = sums[assignments[i]];
1284
+ const offset = rows[i] * dims;
1285
+ for (let d = 0; d < dims; d++)
1286
+ sum[d] += view.Data[offset + d];
1287
+ counts[assignments[i]]++;
1288
+ }
1289
+ const next = new Map();
1290
+ for (let c = 0; c < k; c++) {
1291
+ if (counts[c] === 0) {
1292
+ // Empty cluster - keep old centroid
1293
+ next.set(c, previous.get(c));
1294
+ continue;
1295
+ }
1296
+ const values = sums[c];
1297
+ for (let d = 0; d < dims; d++)
1298
+ values[d] /= counts[c];
1299
+ next.set(c, { Values: values, NormSq: SumOfSquares(values, 0, dims) });
1300
+ }
1301
+ return next;
1302
+ }
1303
+ /** Largest euclidean distance (1 - similarity) any centroid moved. */
1304
+ maxCentroidMovement(oldCentroids, newCentroids, scorer) {
1305
+ let maxMovement = 0;
1306
+ newCentroids.forEach((newCentroid, clusterId) => {
1307
+ const movement = 1 - scorer.EuclideanBetween(oldCentroids.get(clusterId), newCentroid);
1308
+ maxMovement = Math.max(maxMovement, movement);
1309
+ });
1310
+ return maxMovement;
1311
+ }
1312
+ centroidFromRow(row) {
1313
+ const values = Float64Array.from(this.store.CopyRow(row));
1314
+ return { Values: values, NormSq: SumOfSquares(values, 0, values.length) };
1315
+ }
1123
1316
  /**
1124
1317
  * Check if cluster assignments have converged
1125
1318
  * @private
1126
1319
  */
1127
- checkConvergence(oldAssignments, newAssignments) {
1128
- if (oldAssignments.size !== newAssignments.size)
1129
- return false;
1130
- for (const [key, clusterId] of newAssignments) {
1131
- if (oldAssignments.get(key) !== clusterId) {
1320
+ sameAssignments(oldAssignments, newAssignments) {
1321
+ // Both cover the same rows, so they always have the same length.
1322
+ for (let i = 0; i < newAssignments.length; i++) {
1323
+ if (oldAssignments[i] !== newAssignments[i])
1132
1324
  return false;
1133
- }
1134
1325
  }
1135
1326
  return true;
1136
1327
  }
1328
+ /**
1329
+ * Scores rows and centroids with the clustering metric. Subclasses that
1330
+ * override a metric method get it honoured here too, row by row.
1331
+ */
1332
+ createScorer(metric) {
1333
+ const view = this.store.View();
1334
+ const dims = view.Dims;
1335
+ if (this.usesCustomMetric) {
1336
+ return {
1337
+ RowVsCentroid: (row, centroid) => this.CalculateDistance(this.store.ReadRow(row), Array.from(centroid.Values), metric),
1338
+ RowVsRow: (a, b) => this.CalculateDistance(this.store.ReadRow(a), this.store.ReadRow(b), metric),
1339
+ EuclideanBetween: (a, b) => this.CalculateDistance(Array.from(a.Values), Array.from(b.Values), 'euclidean'),
1340
+ };
1341
+ }
1342
+ return {
1343
+ RowVsCentroid: (row, centroid) => MetricScore(metric, view.Data, row * dims, view.Norms[row], centroid.Values, 0, centroid.NormSq, dims),
1344
+ RowVsRow: (a, b) => MetricScore(metric, view.Data, a * dims, view.Norms[a], view.Data, b * dims, view.Norms[b], dims),
1345
+ EuclideanBetween: (a, b) => EuclideanScore(a.Values, 0, b.Values, 0, dims),
1346
+ };
1347
+ }
1137
1348
  /**
1138
1349
  * Performs DBSCAN (Density-Based Spatial Clustering of Applications with Noise) clustering.
1139
1350
  *
@@ -1191,43 +1402,35 @@ export class SimpleVectorService {
1191
1402
  throw new Error('MinPoints must be positive');
1192
1403
  }
1193
1404
  // Pre-filter vectors if filter provided
1194
- const entries = filter
1195
- ? Array.from(this.vectors.values()).filter(entry => entry.metadata && filter(entry.metadata))
1196
- : Array.from(this.vectors.values());
1197
- const visited = new Set();
1198
- const clustered = new Set();
1405
+ const rows = filter ? this.filterRows(filter) : this.store.LiveRows();
1406
+ // Build neighborhood map for efficiency (using filtered rows)
1407
+ const neighborhoods = this.buildNeighborhoods(rows, 1 - epsilon, metric, filter);
1408
+ const visited = new Uint8Array(this.store.RowCount);
1409
+ const clustered = new Uint8Array(this.store.RowCount);
1199
1410
  const clusters = new Map();
1200
1411
  const outliers = [];
1201
1412
  let clusterId = 0;
1202
- // Build neighborhood map for efficiency (using filtered entries)
1203
- const neighborhoods = new Map();
1204
- entries.forEach(entry => {
1205
- const neighbors = this.FindNearest(entry.vector, entries.length, // Search within filtered space
1206
- 1 - epsilon, // Convert epsilon to similarity threshold
1207
- metric, filter // Apply same filter to neighborhood search
1208
- ).map(r => r.key);
1209
- neighborhoods.set(entry.key, neighbors);
1210
- });
1211
1413
  // DBSCAN algorithm
1212
- entries.forEach(entry => {
1213
- if (visited.has(entry.key))
1214
- return;
1215
- visited.add(entry.key);
1216
- const neighbors = neighborhoods.get(entry.key);
1414
+ for (let i = 0; i < rows.length; i++) {
1415
+ const row = rows[i];
1416
+ if (visited[row])
1417
+ continue;
1418
+ visited[row] = 1;
1419
+ const neighbors = neighborhoods[row];
1217
1420
  if (neighbors.length < minPoints) {
1218
1421
  // Mark as noise (may later be added to a cluster)
1219
- outliers.push(entry.key);
1422
+ outliers.push(row);
1220
1423
  }
1221
1424
  else {
1222
1425
  // Start a new cluster
1223
1426
  const cluster = [];
1224
1427
  clusters.set(clusterId, cluster);
1225
- this.expandCluster(entry.key, neighbors, cluster, visited, clustered, neighborhoods, minPoints, outliers);
1428
+ this.expandCluster(row, neighbors, cluster, visited, clustered, neighborhoods, minPoints);
1226
1429
  clusterId++;
1227
1430
  }
1228
- });
1431
+ }
1229
1432
  // Remove outliers that were later added to clusters
1230
- const finalOutliers = outliers.filter(key => !clustered.has(key));
1433
+ const finalOutliers = outliers.filter(row => !clustered[row]).map(row => this.store.KeyAt(row));
1231
1434
  return {
1232
1435
  clusters,
1233
1436
  outliers: finalOutliers,
@@ -1239,36 +1442,60 @@ export class SimpleVectorService {
1239
1442
  }
1240
1443
  };
1241
1444
  }
1445
+ /**
1446
+ * Each row's neighbours — every row in `rows` scoring at least
1447
+ * `similarityThreshold` (itself included) — ranked highest first, ties in
1448
+ * insertion order. Indexed by row.
1449
+ */
1450
+ buildNeighborhoods(rows, similarityThreshold, metric, filter) {
1451
+ const neighborhoods = new Array(this.store.RowCount);
1452
+ if (this.usesCustomMetric) {
1453
+ for (let i = 0; i < rows.length; i++) {
1454
+ const neighbors = this.FindNearest(this.store.ReadRow(rows[i]), rows.length, similarityThreshold, metric, filter);
1455
+ neighborhoods[rows[i]] = Int32Array.from(neighbors, n => this.store.RowOf(n.key));
1456
+ }
1457
+ return neighborhoods;
1458
+ }
1459
+ const view = this.store.View();
1460
+ for (let i = 0; i < rows.length; i++) {
1461
+ const row = rows[i];
1462
+ const ranked = SearchRows(view, {
1463
+ Query: Float64Array.from(view.Data.subarray(row * view.Dims, (row + 1) * view.Dims)),
1464
+ QueryNormSq: view.Norms[row],
1465
+ Candidates: rows,
1466
+ Metric: metric,
1467
+ TopK: null,
1468
+ Threshold: similarityThreshold,
1469
+ });
1470
+ neighborhoods[row] = ranked.Rows;
1471
+ }
1472
+ return neighborhoods;
1473
+ }
1242
1474
  /**
1243
1475
  * Expand a cluster in DBSCAN
1244
1476
  * @private
1245
1477
  */
1246
- expandCluster(key, neighbors, cluster, visited, clustered, neighborhoods, minPoints, outliers) {
1247
- cluster.push(key);
1248
- clustered.add(key);
1249
- const queue = [...neighbors];
1250
- while (queue.length > 0) {
1251
- const neighborKey = queue.shift();
1252
- if (!visited.has(neighborKey)) {
1253
- visited.add(neighborKey);
1254
- const neighborNeighbors = neighborhoods.get(neighborKey);
1478
+ expandCluster(row, neighbors, cluster, visited, clustered, neighborhoods, minPoints) {
1479
+ cluster.push(this.store.KeyAt(row));
1480
+ clustered[row] = 1;
1481
+ const queue = Array.from(neighbors);
1482
+ for (let head = 0; head < queue.length; head++) {
1483
+ const neighborRow = queue[head];
1484
+ if (!visited[neighborRow]) {
1485
+ visited[neighborRow] = 1;
1486
+ const neighborNeighbors = neighborhoods[neighborRow];
1255
1487
  if (neighborNeighbors.length >= minPoints) {
1256
1488
  // Add unprocessed neighbors to queue
1257
- neighborNeighbors.forEach(nn => {
1258
- if (!visited.has(nn)) {
1259
- queue.push(nn);
1489
+ for (let j = 0; j < neighborNeighbors.length; j++) {
1490
+ if (!visited[neighborNeighbors[j]]) {
1491
+ queue.push(neighborNeighbors[j]);
1260
1492
  }
1261
- });
1493
+ }
1262
1494
  }
1263
1495
  }
1264
- if (!clustered.has(neighborKey)) {
1265
- cluster.push(neighborKey);
1266
- clustered.add(neighborKey);
1267
- // Remove from outliers if it was there
1268
- const outlierIdx = outliers.indexOf(neighborKey);
1269
- if (outlierIdx !== -1) {
1270
- outliers.splice(outlierIdx, 1);
1271
- }
1496
+ if (!clustered[neighborRow]) {
1497
+ cluster.push(this.store.KeyAt(neighborRow));
1498
+ clustered[neighborRow] = 1;
1272
1499
  }
1273
1500
  }
1274
1501
  }
@@ -1350,15 +1577,15 @@ export class SimpleVectorService {
1350
1577
  WithinClusterDistance(clusterResult, metric = 'euclidean') {
1351
1578
  let totalDistance = 0;
1352
1579
  let totalPairs = 0;
1580
+ const scorer = this.createScorer(metric);
1353
1581
  clusterResult.clusters.forEach((members) => {
1582
+ const rows = this.rowsForKeys(members);
1354
1583
  // Calculate pairwise distances within cluster
1355
- for (let i = 0; i < members.length; i++) {
1356
- for (let j = i + 1; j < members.length; j++) {
1357
- const vec1 = this.vectors.get(members[i])?.vector;
1358
- const vec2 = this.vectors.get(members[j])?.vector;
1359
- if (vec1 && vec2) {
1584
+ for (let i = 0; i < rows.length; i++) {
1585
+ for (let j = i + 1; j < rows.length; j++) {
1586
+ if (rows[i] >= 0 && rows[j] >= 0) {
1360
1587
  // Convert similarity to distance
1361
- totalDistance += 1 - this.CalculateDistance(vec1, vec2, metric);
1588
+ totalDistance += 1 - scorer.RowVsRow(rows[i], rows[j]);
1362
1589
  totalPairs++;
1363
1590
  }
1364
1591
  }
@@ -1399,22 +1626,21 @@ export class SimpleVectorService {
1399
1626
  }
1400
1627
  let totalDistance = 0;
1401
1628
  let totalPairs = 0;
1629
+ const scorer = this.createScorer(metric);
1402
1630
  // Calculate distances between all pairs of clusters
1403
1631
  for (let i = 0; i < clusterIds.length; i++) {
1404
1632
  for (let j = i + 1; j < clusterIds.length; j++) {
1405
- const cluster1 = clusterResult.clusters.get(clusterIds[i]);
1406
- const cluster2 = clusterResult.clusters.get(clusterIds[j]);
1633
+ const rows1 = this.rowsForKeys(clusterResult.clusters.get(clusterIds[i]));
1634
+ const rows2 = this.rowsForKeys(clusterResult.clusters.get(clusterIds[j]));
1407
1635
  // Calculate average distance between all pairs across clusters
1408
- cluster1.forEach(key1 => {
1409
- cluster2.forEach(key2 => {
1410
- const vec1 = this.vectors.get(key1)?.vector;
1411
- const vec2 = this.vectors.get(key2)?.vector;
1412
- if (vec1 && vec2) {
1413
- totalDistance += 1 - this.CalculateDistance(vec1, vec2, metric);
1636
+ for (let a = 0; a < rows1.length; a++) {
1637
+ for (let b = 0; b < rows2.length; b++) {
1638
+ if (rows1[a] >= 0 && rows2[b] >= 0) {
1639
+ totalDistance += 1 - scorer.RowVsRow(rows1[a], rows2[b]);
1414
1640
  totalPairs++;
1415
1641
  }
1416
- });
1417
- });
1642
+ }
1643
+ }
1418
1644
  }
1419
1645
  }
1420
1646
  return totalPairs > 0 ? totalDistance / totalPairs : 0;
@@ -1454,42 +1680,45 @@ export class SimpleVectorService {
1454
1680
  */
1455
1681
  SilhouetteScore(clusterResult, metric = 'euclidean') {
1456
1682
  const scores = [];
1683
+ const scorer = this.createScorer(metric);
1684
+ const rowsByCluster = new Map();
1685
+ clusterResult.clusters.forEach((members, clusterId) => rowsByCluster.set(clusterId, this.rowsForKeys(members)));
1457
1686
  clusterResult.clusters.forEach((members, clusterId) => {
1458
- members.forEach(key => {
1459
- const vector = this.vectors.get(key)?.vector;
1460
- if (!vector)
1461
- return;
1687
+ const memberRows = rowsByCluster.get(clusterId);
1688
+ for (let m = 0; m < members.length; m++) {
1689
+ const row = memberRows[m];
1690
+ if (row < 0)
1691
+ continue;
1462
1692
  // Calculate a(i): average distance to other points in same cluster
1463
1693
  let a = 0;
1464
1694
  if (members.length > 1) {
1465
- const sameClusterDistances = members
1466
- .filter(k => k !== key)
1467
- .map(k => {
1468
- const otherVec = this.vectors.get(k)?.vector;
1469
- return otherVec ? 1 - this.CalculateDistance(vector, otherVec, metric) : 0;
1470
- });
1471
- a = sameClusterDistances.reduce((sum, d) => sum + d, 0) / sameClusterDistances.length;
1695
+ let sum = 0;
1696
+ let count = 0;
1697
+ for (let o = 0; o < members.length; o++) {
1698
+ if (members[o] === members[m])
1699
+ continue;
1700
+ sum += memberRows[o] >= 0 ? 1 - scorer.RowVsRow(row, memberRows[o]) : 0;
1701
+ count++;
1702
+ }
1703
+ a = sum / count;
1472
1704
  }
1473
1705
  // Calculate b(i): minimum average distance to points in other clusters
1474
1706
  let b = Infinity;
1475
- clusterResult.clusters.forEach((otherMembers, otherClusterId) => {
1476
- if (otherClusterId === clusterId)
1707
+ rowsByCluster.forEach((otherRows, otherClusterId) => {
1708
+ if (otherClusterId === clusterId || otherRows.length === 0)
1477
1709
  return;
1478
- const otherClusterDistances = otherMembers.map(k => {
1479
- const otherVec = this.vectors.get(k)?.vector;
1480
- return otherVec ? 1 - this.CalculateDistance(vector, otherVec, metric) : 0;
1481
- });
1482
- if (otherClusterDistances.length > 0) {
1483
- const avgDist = otherClusterDistances.reduce((sum, d) => sum + d, 0) / otherClusterDistances.length;
1484
- b = Math.min(b, avgDist);
1710
+ let sum = 0;
1711
+ for (let o = 0; o < otherRows.length; o++) {
1712
+ sum += otherRows[o] >= 0 ? 1 - scorer.RowVsRow(row, otherRows[o]) : 0;
1485
1713
  }
1714
+ b = Math.min(b, sum / otherRows.length);
1486
1715
  });
1487
1716
  // Calculate silhouette coefficient for this point
1488
1717
  if (b !== Infinity) {
1489
1718
  const s = (b - a) / Math.max(a, b);
1490
1719
  scores.push(s);
1491
1720
  }
1492
- });
1721
+ }
1493
1722
  });
1494
1723
  // Return average silhouette score
1495
1724
  return scores.length > 0 ?
@@ -1528,7 +1757,7 @@ export class SimpleVectorService {
1528
1757
  * @method
1529
1758
  */
1530
1759
  ElbowMethod(minK, maxK, metric = 'euclidean') {
1531
- if (minK < 1 || maxK > this.vectors.size || minK > maxK) {
1760
+ if (minK < 1 || maxK > this.store.Size || minK > maxK) {
1532
1761
  throw new Error('Invalid k range');
1533
1762
  }
1534
1763
  const results = new Map();
@@ -1538,5 +1767,102 @@ export class SimpleVectorService {
1538
1767
  }
1539
1768
  return results;
1540
1769
  }
1770
+ /**
1771
+ * Async form of {@link KMeansCluster} with identical arguments and results.
1772
+ * On a server host with a worker-pool accelerator the whole run — including
1773
+ * the O(n²) silhouette score — happens on a worker thread, so a large
1774
+ * clustering request does not stall every other request on the process.
1775
+ *
1776
+ * @public
1777
+ * @method
1778
+ */
1779
+ async KMeansClusterAsync(k, maxIterations = 100, metric = 'euclidean', tolerance = 0.0001) {
1780
+ if (k <= 0 || k > this.store.Size) {
1781
+ throw new Error(`Invalid k: ${k}. Must be between 1 and ${this.store.Size}`);
1782
+ }
1783
+ if (this.usesCustomMetric)
1784
+ return this.KMeansCluster(k, maxIterations, metric, tolerance);
1785
+ const keys = this.store.Keys;
1786
+ const offloaded = await this.accelerator.ClusterAsync({
1787
+ Snapshot: this.store.Snapshot(), Candidates: null, Algorithm: 'kmeans',
1788
+ Metric: metric, K: k, MaxIterations: maxIterations, Tolerance: tolerance,
1789
+ });
1790
+ return offloaded ? this.clusterResultFromRows(offloaded, keys, metric) : this.KMeansCluster(k, maxIterations, metric, tolerance);
1791
+ }
1792
+ /**
1793
+ * Async form of {@link DBSCANCluster} with identical arguments and results.
1794
+ * The metadata filter runs on the calling thread; the O(n²) neighbourhood
1795
+ * scan and the silhouette score run on a worker when one is available.
1796
+ *
1797
+ * @public
1798
+ * @method
1799
+ */
1800
+ async DBSCANClusterAsync(epsilon, minPoints, metric = 'euclidean', filter) {
1801
+ if (epsilon <= 0 || epsilon >= 1) {
1802
+ throw new Error('Epsilon must be between 0 and 1 (exclusive)');
1803
+ }
1804
+ if (minPoints <= 0) {
1805
+ throw new Error('MinPoints must be positive');
1806
+ }
1807
+ if (this.usesCustomMetric)
1808
+ return this.DBSCANCluster(epsilon, minPoints, metric, filter);
1809
+ const keys = this.store.Keys;
1810
+ const offloaded = await this.accelerator.ClusterAsync({
1811
+ Snapshot: this.store.Snapshot(), Candidates: filter ? this.filterRows(filter) : null, Algorithm: 'dbscan',
1812
+ Metric: metric, Epsilon: epsilon, MinPoints: minPoints,
1813
+ });
1814
+ return offloaded ? this.clusterResultFromRows(offloaded, keys, metric) : this.DBSCANCluster(epsilon, minPoints, metric, filter);
1815
+ }
1816
+ /** Converts a key-based result whose keys are `String(row)` (see {@link FromRowsView}) into rows. */
1817
+ static clusterResultToRows(result) {
1818
+ const toRows = (keys) => Int32Array.from(keys, key => Number(key));
1819
+ const clusters = new Map();
1820
+ result.clusters.forEach((keys, id) => clusters.set(id, toRows(keys)));
1821
+ return {
1822
+ Clusters: clusters,
1823
+ Centroids: result.centroids ?? null,
1824
+ Outliers: result.outliers ? toRows(result.outliers) : null,
1825
+ Iterations: result.metadata?.iterations,
1826
+ Inertia: result.metadata?.inertia,
1827
+ SilhouetteScore: result.metadata?.silhouetteScore,
1828
+ };
1829
+ }
1830
+ /** Maps an off-thread result back to keys using the row→key array captured at dispatch. */
1831
+ clusterResultFromRows(result, keysAtDispatch, metric) {
1832
+ // A row removed while the job ran off-thread has a null key here: VectorStore.Remove nulls the
1833
+ // dispatch-time key array in place. Drop it, as the search path does when it re-scores.
1834
+ const toKeys = (rows) => {
1835
+ const keys = [];
1836
+ for (let i = 0; i < rows.length; i++) {
1837
+ const key = keysAtDispatch[rows[i]];
1838
+ if (key !== null && key !== undefined)
1839
+ keys.push(key);
1840
+ }
1841
+ return keys;
1842
+ };
1843
+ const clusters = new Map();
1844
+ result.Clusters.forEach((rows, id) => clusters.set(id, toKeys(rows)));
1845
+ const mapped = {
1846
+ clusters,
1847
+ metadata: { metric, silhouetteScore: result.SilhouetteScore },
1848
+ };
1849
+ if (result.Centroids)
1850
+ mapped.centroids = result.Centroids;
1851
+ if (result.Outliers)
1852
+ mapped.outliers = toKeys(result.Outliers);
1853
+ if (result.Iterations !== undefined)
1854
+ mapped.metadata.iterations = result.Iterations;
1855
+ if (result.Inertia !== undefined)
1856
+ mapped.metadata.inertia = result.Inertia;
1857
+ return mapped;
1858
+ }
1859
+ /** Current rows for `keys`, -1 where a key is not stored. */
1860
+ rowsForKeys(keys) {
1861
+ const rows = new Int32Array(keys.length);
1862
+ for (let i = 0; i < keys.length; i++) {
1863
+ rows[i] = this.store.RowOf(keys[i]) ?? -1;
1864
+ }
1865
+ return rows;
1866
+ }
1541
1867
  }
1542
1868
  //# sourceMappingURL=SimpleVectorService.js.map