@memberjunction/ai-vectors-memory 6.2.0-edge.2 → 6.2.0-edge.4

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
@@ -5,7 +5,8 @@
5
5
  * configured to point at any entity, **this** driver is purpose-built for
6
6
  * `EntityDocument`-backed search: each "index" corresponds to one
7
7
  * `MJ: Entity Documents` row, vectors are loaded from
8
- * `MJ: Entity Record Documents.VectorJSON` filtered by `EntityDocumentID`,
8
+ * `MJ: Entity Record Documents` (`VectorBinary`, falling back to `VectorJSON`)
9
+ * filtered by `EntityDocumentID`,
9
10
  * and matches surface the **underlying entity record's RecordID** in their
10
11
  * metadata (not the EntityRecordDocument PK).
11
12
  *
@@ -18,19 +19,30 @@
18
19
  * bundler-duplicated copy of this module — shares one Map of loaded indexes.
19
20
  * The cache:
20
21
  *
21
- * - Dedupes concurrent cold loads (the first caller installs an in-flight
22
+ * - Dedupes concurrent loads (the first caller installs an in-flight
22
23
  * Promise; later callers await the same one — no duplicate DB reads or
23
24
  * vector-pool builds).
24
- * - Subscribes once to `BaseEntity` save/delete events for
25
- * `MJ: Entity Record Documents` and invalidates the affected
26
- * EntityDocumentID automatically — manual fixes, ad-hoc imports, and
27
- * anything that goes through `BaseEntity.Save()` invalidates without the
28
- * sync pipeline needing to remember to call `InvalidateIndex`.
29
- * - Honors a TTL as a safety net for non-BaseEntity writes.
25
+ * - **Maintains loaded indexes incrementally.** It subscribes once to
26
+ * `BaseEntity` events for `MJ: Entity Record Documents` and applies each
27
+ * change to the one row it affects — an upsert on save, a removal on
28
+ * delete — instead of discarding the index. A sync run that saves
29
+ * thousands of rows therefore never forces a full reload. Changes made on
30
+ * another server (`remote-invalidate`) are applied from the broadcast
31
+ * record when present, otherwise by re-reading just the changed rows.
32
+ * - Serves a stale index while it reloads it in the background
33
+ * (stale-while-revalidate) once the TTL passes, so no user request waits
34
+ * on the safety-net reload. An explicit {@link SimpleVectorServiceProvider.InvalidateIndex}
35
+ * still drops the index outright, because a caller that wrote raw SQL
36
+ * needs the next query to see it.
37
+ * - Honors a TTL as a safety net for writes that bypass `BaseEntity`.
30
38
  *
31
- * **When NOT to use this driver:** > a few thousand `EntityRecordDocument`
32
- * rows per `EntityDocument`, multi-process deployments, scenarios that need
33
- * a real ANN index.
39
+ * Vectors are held at float32 precision — the precision embedding models
40
+ * produce — which halves memory versus float64.
41
+ *
42
+ * **When NOT to use this driver:** many hundreds of thousands of
43
+ * `EntityRecordDocument` rows per `EntityDocument`, or scenarios that need a
44
+ * persistent ANN index — use a colocated (pgvector / SQL Server) or remote
45
+ * vector provider instead.
34
46
  *
35
47
  * @module @memberjunction/ai-vectors-memory
36
48
  */
@@ -44,23 +56,43 @@ var __metadata = (this && this.__metadata) || function (k, v) {
44
56
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
45
57
  };
46
58
  var SimpleVectorServiceProvider_1;
47
- import { BaseSingleton, MJEventType, MJGlobal, RegisterClass } from '@memberjunction/global';
59
+ import { BaseSingleton, EscapeSQLString, MJEventType, MJGlobal, RegisterClass } from '@memberjunction/global';
48
60
  import { BaseEntity, LogError, RunView } from '@memberjunction/core';
49
61
  import { VectorDBBase } from '@memberjunction/ai-vectordb';
50
62
  import { SimpleVectorService } from './SimpleVectorService.js';
63
+ import { ReadStoredVector } from './StoredVector.js';
64
+ const ENTITY_RECORD_DOCUMENTS = 'MJ: Entity Record Documents';
65
+ /** One running load of an EntityDocument's index. */
66
+ class LoadInProgress {
67
+ constructor(
68
+ /** The EntityDocument's invalidation epoch when the load started; a later epoch supersedes it */
69
+ Epoch,
70
+ /** The user the load reads as */
71
+ ContextUser) {
72
+ this.Epoch = Epoch;
73
+ this.ContextUser = ContextUser;
74
+ /** Changes that arrived while loading; replayed onto the result so the load can't resurrect old state */
75
+ this.Pending = [];
76
+ /** Set when something changed that the load may have read too early; its result is cached as stale */
77
+ this.StaleOnArrival = false;
78
+ this.Promise = Promise.resolve(null);
79
+ }
80
+ }
51
81
  /**
52
- * Default TTL (ms) before a cached index is considered stale and reloaded
53
- * on the next query. The BaseEntity event subscription invalidates affected
54
- * indexes the moment an `EntityRecordDocument` row is saved/deleted; TTL is
55
- * just the safety net for writes that bypass BaseEntity (raw SQL, external
56
- * tools).
82
+ * Default TTL (ms) before a cached index is refreshed in the background.
83
+ * Row-level events keep indexes current; the TTL is just the safety net for
84
+ * writes that bypass BaseEntity (raw SQL, external tools).
57
85
  */
58
86
  const DEFAULT_TTL_MS = 15 * 60 * 1000; // 15 minutes
87
+ /** How long remote changes without record data are batched before the changed rows are re-read. */
88
+ const REMOTE_REFRESH_DEBOUNCE_MS = 250;
89
+ /** Maximum IDs per re-read query. */
90
+ const REMOTE_REFRESH_BATCH_SIZE = 500;
59
91
  /**
60
92
  * BaseSingleton-backed cache for `SimpleVectorServiceProvider`. Holds the
61
93
  * per-EntityDocument index pool plus the in-flight Promise map used to dedupe
62
- * cold loads, and subscribes once to BaseEntity events so cache entries
63
- * invalidate automatically when underlying EntityRecordDocument rows change.
94
+ * loads, and subscribes once to BaseEntity events so loaded indexes track
95
+ * EntityRecordDocument changes row by row.
64
96
  *
65
97
  * The provider class itself (`SimpleVectorServiceProvider`) remains a
66
98
  * non-singleton — callers can `new` one freely and they all delegate to this
@@ -71,7 +103,12 @@ export class SimpleVectorIndexCache extends BaseSingleton {
71
103
  constructor() {
72
104
  super();
73
105
  this.indexCache = new Map();
106
+ /** The current load per EntityDocument; a superseded load is dropped from here but finishes for its own callers */
74
107
  this.inFlightLoads = new Map();
108
+ /** Bumped by an explicit invalidate, so a load that started before it is never cached */
109
+ this.loadEpochs = new Map();
110
+ this.remoteRefreshIDs = new Set();
111
+ this.remoteRefreshTimer = null;
75
112
  this.ttlMs = DEFAULT_TTL_MS;
76
113
  this.subscribedToBaseEntityEvents = false;
77
114
  // Wire BaseEntity event subscription exactly once per process.
@@ -84,52 +121,167 @@ export class SimpleVectorIndexCache extends BaseSingleton {
84
121
  set TtlMs(value) { this.ttlMs = value; }
85
122
  get Size() { return this.indexCache.size; }
86
123
  /**
87
- * Get the cached index (or load it). Concurrent callers asking for the
88
- * same EntityDocumentID before the first load completes share the same
89
- * Promise — only one DB read and vector-pool build happens.
124
+ * Get the cached index, or load it. Concurrent callers asking for the same
125
+ * EntityDocumentID before a load completes share one Promise — only one DB
126
+ * read and vector-pool build happens. An index past its TTL (or marked
127
+ * stale) is returned immediately while a background reload replaces it.
90
128
  */
91
129
  async GetOrLoad(entityDocumentId, contextUser, loader) {
92
- const now = Date.now();
93
130
  const cached = this.indexCache.get(entityDocumentId);
94
- if (cached && (now - cached.loadedAt) < this.ttlMs) {
131
+ if (cached) {
132
+ if (cached.stale || (Date.now() - cached.loadedAt) >= this.ttlMs) {
133
+ void this.startLoad(entityDocumentId, contextUser, loader);
134
+ }
95
135
  return cached;
96
136
  }
97
- // Dedupe: if another caller is already loading, return their Promise.
137
+ return this.startLoad(entityDocumentId, contextUser, loader);
138
+ }
139
+ /**
140
+ * Starts (or joins) the current load for an EntityDocument. A load that
141
+ * started before an explicit invalidate is not joined: it may have read the
142
+ * rows the invalidate is about.
143
+ */
144
+ startLoad(entityDocumentId, contextUser, loader) {
145
+ const epoch = this.epochOf(entityDocumentId);
98
146
  const existing = this.inFlightLoads.get(entityDocumentId);
99
- if (existing)
100
- return existing;
101
- const p = (async () => {
102
- try {
103
- const loaded = await loader();
104
- if (loaded) {
105
- this.indexCache.set(entityDocumentId, loaded);
106
- }
107
- return loaded;
147
+ if (existing && existing.Epoch === epoch)
148
+ return existing.Promise;
149
+ const load = new LoadInProgress(epoch, contextUser);
150
+ load.Promise = this.runLoad(entityDocumentId, load, loader);
151
+ this.inFlightLoads.set(entityDocumentId, load);
152
+ // A background refresh has no awaiter; log its failure rather than leave it unhandled.
153
+ load.Promise.catch((e) => {
154
+ LogError(`SimpleVectorIndexCache: load failed for EntityDocumentID="${entityDocumentId}": ${e instanceof Error ? e.message : String(e)}`);
155
+ });
156
+ return load.Promise;
157
+ }
158
+ async runLoad(entityDocumentId, load, loader) {
159
+ try {
160
+ // Through a microtask, so even a loader that throws synchronously fails
161
+ // only after this load is registered — and is then cleared below.
162
+ const loaded = await Promise.resolve().then(loader);
163
+ if (loaded && load.Epoch === this.epochOf(entityDocumentId)) {
164
+ this.replayPendingChanges(load, loaded);
165
+ if (load.StaleOnArrival)
166
+ loaded.stale = true;
167
+ this.indexCache.set(entityDocumentId, loaded);
108
168
  }
109
- finally {
110
- // Always clear in-flight slot, success or failure, so the next
111
- // caller can retry on failure instead of being stuck with a
112
- // resolved-null Promise forever.
169
+ return loaded;
170
+ }
171
+ finally {
172
+ // Clear the slot, success or failure, so the next caller can retry —
173
+ // unless a newer load has already taken it.
174
+ if (this.inFlightLoads.get(entityDocumentId) === load)
113
175
  this.inFlightLoads.delete(entityDocumentId);
114
- }
115
- })();
116
- this.inFlightLoads.set(entityDocumentId, p);
117
- // Suppress unhandled rejection warning if no awaiter exists at throw time.
118
- p.catch(() => { });
119
- return p;
176
+ }
120
177
  }
178
+ epochOf(entityDocumentId) {
179
+ return this.loadEpochs.get(entityDocumentId) ?? 0;
180
+ }
181
+ /** Supersedes any load in flight for the EntityDocument. */
182
+ bumpEpoch(entityDocumentId) {
183
+ this.loadEpochs.set(entityDocumentId, this.epochOf(entityDocumentId) + 1);
184
+ }
185
+ /**
186
+ * Drop a cached index so the next query reloads it before answering. A load
187
+ * already in flight is superseded: it still answers the callers waiting on
188
+ * it, but its result is not cached and the next query starts a fresh load.
189
+ */
121
190
  Invalidate(entityDocumentId) {
122
191
  this.indexCache.delete(entityDocumentId);
123
- // Don't drop in-flight loads — let any in-progress caller complete and
124
- // we'll just discard their result on the next read (TTL handles it).
125
- // Aggressively cancelling would race with concurrent QueryIndex calls.
192
+ this.bumpEpoch(entityDocumentId);
126
193
  }
127
194
  InvalidateAll() {
128
195
  this.indexCache.clear();
196
+ this.inFlightLoads.forEach((_, entityDocumentId) => this.bumpEpoch(entityDocumentId));
197
+ }
198
+ /**
199
+ * Keep serving every cached index, but reload each in the background on its
200
+ * next query. A load already in flight may have read too early, so its
201
+ * result arrives stale too.
202
+ */
203
+ MarkAllStale() {
204
+ this.indexCache.forEach(index => { index.stale = true; });
205
+ this.inFlightLoads.forEach(load => { load.StaleOnArrival = true; });
129
206
  }
130
207
  /**
131
- * Subscribe to BaseEntity save/delete events and invalidate the affected
132
- * EntityDocument index when an `MJ: Entity Record Documents` row changes.
208
+ * Applies one EntityRecordDocument's current state to the loaded indexes:
209
+ * an upsert when it carries a usable vector, a removal when it doesn't.
210
+ * Safe to call for indexes that are not loaded (no-op) or still loading
211
+ * (the change is replayed onto the load's result).
212
+ */
213
+ ApplyRowChange(row) {
214
+ this.applyRowChangeWhere(row, () => true);
215
+ }
216
+ /** Removes an EntityRecordDocument from every loaded (or loading) index. */
217
+ ApplyRowRemoval(id) {
218
+ this.applyRowRemovalWhere(id, () => true);
219
+ }
220
+ /** {@link ApplyRowChange}, limited to the indexes (and loads) whose user passes `includeUser`. */
221
+ applyRowChangeWhere(row, includeUser) {
222
+ if (!row.ID)
223
+ return;
224
+ const targetDoc = row.EntityDocumentID || null;
225
+ // A row that moved to another EntityDocument must leave its old index — loaded or still loading.
226
+ this.indexCache.forEach((index, docId) => {
227
+ if (docId !== targetDoc && includeUser(index.contextUser))
228
+ index.service.RemoveVector(row.ID);
229
+ });
230
+ this.inFlightLoads.forEach((load, docId) => {
231
+ if (!includeUser(load.ContextUser))
232
+ return;
233
+ load.Pending.push(docId === targetDoc ? { Kind: 'upsert', Row: row } : { Kind: 'remove', ID: row.ID });
234
+ });
235
+ if (!targetDoc)
236
+ return;
237
+ const target = this.indexCache.get(targetDoc);
238
+ if (target && includeUser(target.contextUser) && !this.applyRowToIndex(target, row)) {
239
+ // The new vector's dimensions don't match the index (the embedding
240
+ // model changed). Only a full reload yields a consistent index.
241
+ this.Invalidate(targetDoc);
242
+ }
243
+ }
244
+ applyRowRemovalWhere(id, includeUser) {
245
+ this.indexCache.forEach(index => {
246
+ if (includeUser(index.contextUser))
247
+ index.service.RemoveVector(id);
248
+ });
249
+ this.inFlightLoads.forEach(load => {
250
+ if (includeUser(load.ContextUser))
251
+ load.Pending.push({ Kind: 'remove', ID: id });
252
+ });
253
+ }
254
+ /**
255
+ * Writes one row into an index. Returns false only when the vector's
256
+ * dimensions conflict with the index; a row without a usable vector is
257
+ * removed and counts as applied.
258
+ */
259
+ applyRowToIndex(index, row) {
260
+ const vector = ReadStoredVector(row.VectorBinary, row.VectorJSON);
261
+ if (!vector || !row.RecordID) {
262
+ index.service.RemoveVector(row.ID);
263
+ return true;
264
+ }
265
+ const dims = index.service.ExpectedDimensions;
266
+ if (dims !== null && dims !== vector.length)
267
+ return false;
268
+ index.service.AddOrUpdateVector(row.ID, vector, { RecordID: row.RecordID });
269
+ return true;
270
+ }
271
+ /** Replays changes that arrived while an index was loading, so the load can't resurrect old state. */
272
+ replayPendingChanges(load, loaded) {
273
+ for (const change of load.Pending) {
274
+ if (change.Kind === 'remove') {
275
+ loaded.service.RemoveVector(change.ID);
276
+ }
277
+ else if (!this.applyRowToIndex(loaded, change.Row)) {
278
+ loaded.stale = true; // dimensions changed mid-load; refresh on next query
279
+ }
280
+ }
281
+ }
282
+ /**
283
+ * Subscribe to BaseEntity save/delete/remote-invalidate events for
284
+ * `MJ: Entity Record Documents` and apply each to the loaded indexes.
133
285
  * Idempotent — only subscribes once per singleton instance.
134
286
  */
135
287
  subscribeToBaseEntityEvents() {
@@ -143,27 +295,8 @@ export class SimpleVectorIndexCache extends BaseSingleton {
143
295
  if (mjEvent.eventCode !== BaseEntity.BaseEventCode)
144
296
  return;
145
297
  const ev = mjEvent.args;
146
- if (!ev)
147
- return;
148
- if (ev.type !== 'save' && ev.type !== 'delete' && ev.type !== 'remote-invalidate')
149
- return;
150
- const entityName = ev.baseEntity?.EntityInfo?.Name ?? ev.entityName;
151
- if (entityName !== 'MJ: Entity Record Documents')
152
- return;
153
- // Pull EntityDocumentID off the affected row. On save/delete the
154
- // BaseEntity is hydrated; on remote-invalidate we may have only
155
- // the entity name, in which case we conservatively drop ALL
156
- // cached indexes (small price for correctness — TTL would have
157
- // expired them within 15 min anyway).
158
- if (ev.baseEntity) {
159
- const docId = ev.baseEntity.Get('EntityDocumentID');
160
- if (typeof docId === 'string' && docId.length > 0) {
161
- this.Invalidate(docId);
162
- }
163
- }
164
- else {
165
- this.InvalidateAll();
166
- }
298
+ if (ev)
299
+ this.HandleEntityEvent(ev);
167
300
  });
168
301
  }
169
302
  catch (e) {
@@ -171,10 +304,181 @@ export class SimpleVectorIndexCache extends BaseSingleton {
171
304
  LogError(`SimpleVectorIndexCache: failed to subscribe to BaseEntity events: ${e instanceof Error ? e.message : String(e)}`);
172
305
  }
173
306
  }
307
+ /**
308
+ * Routes one BaseEntity event. Public so hosts that relay events by other
309
+ * means (and tests) can feed them in directly.
310
+ */
311
+ HandleEntityEvent(ev) {
312
+ if (ev.type !== 'save' && ev.type !== 'delete' && ev.type !== 'remote-invalidate')
313
+ return;
314
+ const entityName = ev.baseEntity?.EntityInfo?.Name ?? ev.entityName;
315
+ if (entityName !== ENTITY_RECORD_DOCUMENTS)
316
+ return;
317
+ if (ev.type === 'remote-invalidate') {
318
+ this.handleRemoteInvalidate(ev.payload);
319
+ return;
320
+ }
321
+ if (!ev.baseEntity) {
322
+ this.MarkAllStale();
323
+ return;
324
+ }
325
+ // The event's entity is an `MJ: Entity Record Documents` instance; its generated getters match the row shape.
326
+ const record = ev.baseEntity;
327
+ if (ev.type === 'delete') {
328
+ this.ApplyRowRemoval(record.ID);
329
+ }
330
+ else {
331
+ this.ApplyRowChange({
332
+ ID: record.ID,
333
+ EntityDocumentID: record.EntityDocumentID,
334
+ RecordID: record.RecordID,
335
+ VectorJSON: record.VectorJSON,
336
+ VectorBinary: record.VectorBinary,
337
+ });
338
+ }
339
+ }
340
+ /**
341
+ * A change made by another server. Uses the broadcast record when the host
342
+ * opted this entity into record-data broadcast; otherwise re-reads just the
343
+ * changed rows (batched), and as a last resort refreshes in the background.
344
+ */
345
+ handleRemoteInvalidate(payload) {
346
+ const id = payload?.primaryKeyValues ? parsePrimaryKeyID(payload.primaryKeyValues) : null;
347
+ if (payload?.action === 'delete' && id) {
348
+ this.ApplyRowRemoval(id);
349
+ return;
350
+ }
351
+ if (payload?.action === 'save') {
352
+ const row = payload.recordData ? parseRecordData(payload.recordData) : null;
353
+ if (row) {
354
+ this.ApplyRowChange(row);
355
+ return;
356
+ }
357
+ if (id) {
358
+ this.queueRemoteRefresh(id);
359
+ return;
360
+ }
361
+ }
362
+ this.MarkAllStale();
363
+ }
364
+ queueRemoteRefresh(id) {
365
+ if (this.indexCache.size === 0 && this.inFlightLoads.size === 0)
366
+ return; // nothing loaded to keep current
367
+ this.remoteRefreshIDs.add(id);
368
+ if (this.remoteRefreshTimer)
369
+ return;
370
+ this.remoteRefreshTimer = setTimeout(() => {
371
+ this.remoteRefreshTimer = null;
372
+ // Nothing awaits this timer-driven refresh. Without the catch a throw would be an
373
+ // unhandled rejection, and the IDs already taken off the queue would be lost until the
374
+ // TTL reload. Same contract as a failed load: log, and serve stale until a reload.
375
+ this.refreshQueuedRows().catch((e) => {
376
+ LogError(`SimpleVectorIndexCache: re-reading changed EntityRecordDocument rows failed: ${e instanceof Error ? e.message : String(e)}`);
377
+ this.MarkAllStale();
378
+ });
379
+ }, REMOTE_REFRESH_DEBOUNCE_MS);
380
+ }
381
+ /**
382
+ * Re-reads the queued rows once per user an index was loaded as, and
383
+ * applies each read only to that user's indexes: a row one user cannot see
384
+ * must not be removed from an index another user loaded.
385
+ */
386
+ async refreshQueuedRows() {
387
+ const ids = Array.from(this.remoteRefreshIDs);
388
+ this.remoteRefreshIDs.clear();
389
+ for (const [userKey, contextUser] of this.loadedUsers()) {
390
+ const includeUser = (user) => userKeyOf(user) === userKey;
391
+ for (let start = 0; start < ids.length; start += REMOTE_REFRESH_BATCH_SIZE) {
392
+ const batch = ids.slice(start, start + REMOTE_REFRESH_BATCH_SIZE);
393
+ if (!await this.refreshRows(batch, contextUser, includeUser)) {
394
+ this.MarkAllStale();
395
+ return;
396
+ }
397
+ }
398
+ }
399
+ }
400
+ async refreshRows(ids, contextUser, includeUser) {
401
+ const inList = ids.map(id => `'${EscapeSQLString(id)}'`).join(',');
402
+ let result;
403
+ try {
404
+ result = await new RunView().RunView({
405
+ EntityName: ENTITY_RECORD_DOCUMENTS,
406
+ ExtraFilter: `ID IN (${inList})`,
407
+ // Naming the binary column requests it (RunView omits binary columns otherwise).
408
+ Fields: ['ID', 'EntityDocumentID', 'RecordID', 'VectorJSON', 'VectorBinary'],
409
+ ResultType: 'simple',
410
+ BypassCache: true,
411
+ }, contextUser);
412
+ }
413
+ catch (e) {
414
+ // A provider that throws (connection lost, transport error) is handled like one that
415
+ // reports failure: the caller marks every index stale and stops this batch run.
416
+ LogError(`SimpleVectorIndexCache: re-reading ${ids.length} changed EntityRecordDocument row(s) threw: ${e instanceof Error ? e.message : String(e)}`);
417
+ return false;
418
+ }
419
+ if (!result.Success) {
420
+ LogError(`SimpleVectorIndexCache: re-reading ${ids.length} changed EntityRecordDocument row(s) failed: ${result.ErrorMessage}`);
421
+ return false;
422
+ }
423
+ const found = new Set();
424
+ for (const row of result.Results ?? []) {
425
+ found.add(row.ID);
426
+ this.applyRowChangeWhere(row, includeUser);
427
+ }
428
+ // A changed row this user can no longer read was deleted (or hidden from them) after the change.
429
+ for (const id of ids) {
430
+ if (!found.has(id))
431
+ this.applyRowRemovalWhere(id, includeUser);
432
+ }
433
+ return true;
434
+ }
435
+ /** Each distinct user a loaded or loading index reads as, keyed by user ID ('' for none). */
436
+ loadedUsers() {
437
+ const users = new Map();
438
+ this.indexCache.forEach(index => users.set(userKeyOf(index.contextUser), index.contextUser));
439
+ this.inFlightLoads.forEach(load => users.set(userKeyOf(load.ContextUser), load.ContextUser));
440
+ return users;
441
+ }
442
+ }
443
+ /** Groups indexes by the user they were loaded as. */
444
+ function userKeyOf(user) {
445
+ return user?.ID ?? '';
446
+ }
447
+ /** Reads the `ID` value out of a remote-invalidate `primaryKeyValues` payload. */
448
+ function parsePrimaryKeyID(primaryKeyValues) {
449
+ try {
450
+ const pairs = JSON.parse(primaryKeyValues);
451
+ const idPair = Array.isArray(pairs) ? pairs.find(p => p?.FieldName === 'ID') : undefined;
452
+ return idPair?.Value ? String(idPair.Value) : null;
453
+ }
454
+ catch {
455
+ return null;
456
+ }
457
+ }
458
+ /** Reads the vector columns out of a remote-invalidate `recordData` payload, or null if they are absent. */
459
+ function parseRecordData(recordData) {
460
+ try {
461
+ const data = JSON.parse(recordData);
462
+ if (!data || typeof data.ID !== 'string' || typeof data.EntityDocumentID !== 'string')
463
+ return null;
464
+ // A partial broadcast that carries neither vector column can't tell us the vector.
465
+ if (!('VectorJSON' in data) && !('VectorBinary' in data))
466
+ return null;
467
+ return {
468
+ ID: data.ID,
469
+ EntityDocumentID: data.EntityDocumentID,
470
+ RecordID: typeof data.RecordID === 'string' ? data.RecordID : '',
471
+ VectorJSON: typeof data.VectorJSON === 'string' ? data.VectorJSON : null,
472
+ VectorBinary: typeof data.VectorBinary === 'string' ? data.VectorBinary : null,
473
+ };
474
+ }
475
+ catch {
476
+ return null;
477
+ }
174
478
  }
175
479
  /**
176
480
  * In-process VectorDBBase driver that loads embeddings from
177
- * `MJ: Entity Record Documents.VectorJSON` rows associated with a given
481
+ * `MJ: Entity Record Documents` rows (`VectorBinary`, falling back to `VectorJSON`) associated with a given
178
482
  * `EntityDocumentID`.
179
483
  *
180
484
  * Callers pass the EntityDocumentID as the `id` field of `QueryIndex` params:
@@ -198,14 +502,14 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
198
502
  * which makes sense for Pinecone/Qdrant but not for an in-memory provider.
199
503
  */
200
504
  constructor(apiKey) { super(apiKey && apiKey.trim().length > 0 ? apiKey : 'in-memory-no-auth'); }
201
- /** SVS reads vectors out of `MJ: Entity Record Documents.VectorJSON`; it
505
+ /** SVS reads vectors out of `MJ: Entity Record Documents` (VectorBinary / VectorJSON); it
202
506
  * intentionally does not implement `CreateRecord(s)`. Flagging this lets
203
507
  * ingestion pipelines short-circuit the upsert call instead of logging
204
508
  * spurious "unsupported" errors per batch. */
205
509
  get IsReadOnly() {
206
510
  return true;
207
511
  }
208
- /** In-process provider — it reads vectors from `MJ: Entity Record Documents.VectorJSON`
512
+ /** In-process provider — it reads vectors from `MJ: Entity Record Documents` (VectorBinary / VectorJSON)
209
513
  * and never calls an external service, so it needs no API key / credential. Lets the
210
514
  * Entity Vector Sync pipeline and dupe detector skip the "No API Key found" guard. */
211
515
  get RequiresAPIKey() {
@@ -218,10 +522,10 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
218
522
  return true;
219
523
  }
220
524
  /**
221
- * Drop a cached index. The BaseEntity event subscription handles this
222
- * automatically for `Save()` / `Delete()` paths; call this manually only
223
- * when writing VectorJSON via a path that bypasses BaseEntity (raw SQL,
224
- * the sync pipeline's bulk inserts, etc.).
525
+ * Drop a cached index so the next query reloads it. Saves and deletes
526
+ * through `BaseEntity` are applied to loaded indexes automatically; call
527
+ * this only after writing VectorJSON by a path that bypasses BaseEntity
528
+ * (raw SQL, external tools).
225
529
  */
226
530
  static InvalidateIndex(entityDocumentId) {
227
531
  SimpleVectorIndexCache.Instance.Invalidate(entityDocumentId);
@@ -235,10 +539,9 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
235
539
  return SimpleVectorIndexCache.Instance.Size;
236
540
  }
237
541
  /**
238
- * Load (or reload after TTL) the vector pool for an `EntityDocumentID`.
239
- * Returns null when the EntityDocument has no embedded records yet — the
240
- * caller treats this as an empty result rather than an error so a
241
- * freshly-installed system without a sync run yet just returns nothing.
542
+ * Load (or refresh) the vector pool for an `EntityDocumentID`. Returns
543
+ * null when the load fails; an EntityDocument with no embedded records
544
+ * yet loads as an empty index, which the caller treats as no matches.
242
545
  *
243
546
  * Concurrent calls for the same `entityDocumentId` while a load is in
244
547
  * flight share the in-flight Promise via {@link SimpleVectorIndexCache}.
@@ -247,36 +550,51 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
247
550
  return SimpleVectorIndexCache.Instance.GetOrLoad(entityDocumentId, contextUser, async () => {
248
551
  const rv = new RunView();
249
552
  const r = await rv.RunView({
250
- EntityName: 'MJ: Entity Record Documents',
251
- ExtraFilter: `EntityDocumentID='${entityDocumentId.replace(/'/g, "''")}' AND VectorJSON IS NOT NULL`,
252
- Fields: ['ID', 'RecordID', 'VectorJSON'],
553
+ EntityName: ENTITY_RECORD_DOCUMENTS,
554
+ ExtraFilter: `EntityDocumentID='${EscapeSQLString(entityDocumentId)}' AND (VectorBinary IS NOT NULL OR VectorJSON IS NOT NULL)`,
555
+ // Both vector columns: the binary one decodes with a copy instead of a JSON parse,
556
+ // and VectorJSON covers rows embedded before VectorBinary existed. Naming
557
+ // VectorBinary in Fields is what requests it — RunView omits binary columns otherwise.
558
+ Fields: ['ID', 'RecordID', 'VectorJSON', 'VectorBinary'],
253
559
  ResultType: 'simple',
254
560
  }, contextUser);
255
561
  if (!r.Success) {
256
562
  LogError(`SimpleVectorServiceProvider.loadIndex: RunView failed for EntityDocumentID="${entityDocumentId}": ${r.ErrorMessage}`);
257
563
  return null;
258
564
  }
259
- const service = new SimpleVectorService();
260
- const recordIdsByDocId = new Map();
261
- const entries = [];
262
- for (const row of r.Results ?? []) {
263
- if (!row.ID || !row.RecordID || !row.VectorJSON)
264
- continue;
265
- try {
266
- const parsed = JSON.parse(row.VectorJSON);
267
- if (!Array.isArray(parsed) || !parsed.every(v => typeof v === 'number'))
268
- continue;
269
- entries.push({ key: row.ID, vector: parsed, metadata: { RecordID: row.RecordID } });
270
- recordIdsByDocId.set(row.ID, row.RecordID);
271
- }
272
- catch {
273
- // Skip rows with unparseable VectorJSON — likely stale/corrupted; sync will fix
274
- }
275
- }
276
- service.LoadVectors(entries);
277
- return { service, recordIdsByDocId, loadedAt: Date.now() };
565
+ const service = this.buildService(entityDocumentId, r.Results ?? []);
566
+ return { service, loadedAt: Date.now(), contextUser, stale: false };
278
567
  });
279
568
  }
569
+ /**
570
+ * Decodes rows straight into a float32 vector pool, preferring each row's
571
+ * `VectorBinary` (a copy) over its `VectorJSON` (a parse). Vectors are added
572
+ * one at a time into pre-sized storage, so a row's decoded vector is garbage
573
+ * as soon as it is copied — peak memory is the pool, not the pool plus every
574
+ * decoded array.
575
+ */
576
+ buildService(entityDocumentId, rows) {
577
+ const service = new SimpleVectorService({ Precision: 'float32' });
578
+ let mismatched = 0;
579
+ for (const row of rows) {
580
+ if (!row.ID || !row.RecordID)
581
+ continue;
582
+ const vector = ReadStoredVector(row.VectorBinary, row.VectorJSON);
583
+ if (!vector)
584
+ continue; // no usable vector in either column — likely stale/corrupted; sync will fix
585
+ if (service.ExpectedDimensions === null)
586
+ service.ReserveCapacity(rows.length, vector.length);
587
+ if (vector.length !== service.ExpectedDimensions) {
588
+ mismatched++;
589
+ continue;
590
+ }
591
+ service.AddVector(row.ID, vector, { RecordID: row.RecordID });
592
+ }
593
+ if (mismatched > 0) {
594
+ LogError(`SimpleVectorServiceProvider: skipped ${mismatched} EntityRecordDocument row(s) for EntityDocumentID="${entityDocumentId}" whose vector dimensions differ from the rest — re-run vector sync for that document`);
595
+ }
596
+ return service;
597
+ }
280
598
  // ── VectorDBBase implementation ──────────────────────────────────────────
281
599
  /**
282
600
  * Run cosine search over the cached vector pool for the supplied
@@ -301,7 +619,7 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
301
619
  // not error. Caller can fall back to lexical-only ranking.
302
620
  return { success: true, message: 'No embedded records yet', data: { matches: [] } };
303
621
  }
304
- const matches = loaded.service.FindNearest(queryVector, topK, 0);
622
+ const matches = await loaded.service.FindNearestAsync(queryVector, topK, 0);
305
623
  return {
306
624
  success: true,
307
625
  message: `Returned ${matches.length} match(es)`,
@@ -309,7 +627,7 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
309
627
  matches: matches.map(m => ({
310
628
  id: m.key, // EntityRecordDocument.ID
311
629
  score: m.score,
312
- metadata: { RecordID: loaded.recordIdsByDocId.get(m.key) ?? null },
630
+ metadata: { RecordID: m.metadata?.RecordID ?? null },
313
631
  })),
314
632
  },
315
633
  };
@@ -334,8 +652,13 @@ let SimpleVectorServiceProvider = SimpleVectorServiceProvider_1 = class SimpleVe
334
652
  SimpleVectorServiceProvider_1.InvalidateAll();
335
653
  return { success: true, message: 'cache cleared', data: null };
336
654
  }
655
+ /**
656
+ * Lists no IDs: the vectors are `MJ: Entity Record Documents` rows, readable only as a calling
657
+ * user, and this contract carries no user. Read-only drivers are skipped by reconciliation.
658
+ */
337
659
  ListVectorIDs(_p) {
338
- return Promise.resolve({ IDs: [], NextCursor: undefined });
660
+ const result = { IDs: [], NextPaginationToken: undefined };
661
+ return Promise.resolve(result);
339
662
  }
340
663
  unsupported(name) {
341
664
  return {