@memberjunction/ai-vectors-memory 6.2.0-edge.2 → 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.
- package/README.md +73 -12
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/models/MetadataFilterEvaluator.d.ts +37 -0
- package/dist/models/MetadataFilterEvaluator.d.ts.map +1 -0
- package/dist/models/MetadataFilterEvaluator.js +233 -0
- package/dist/models/MetadataFilterEvaluator.js.map +1 -0
- package/dist/models/SimpleVectorDatabase.d.ts +55 -11
- package/dist/models/SimpleVectorDatabase.d.ts.map +1 -1
- package/dist/models/SimpleVectorDatabase.js +148 -35
- package/dist/models/SimpleVectorDatabase.js.map +1 -1
- package/dist/models/SimpleVectorService.d.ts +164 -12
- package/dist/models/SimpleVectorService.d.ts.map +1 -1
- package/dist/models/SimpleVectorService.js +612 -286
- package/dist/models/SimpleVectorService.js.map +1 -1
- package/dist/models/SimpleVectorServiceProvider.d.ts +151 -35
- package/dist/models/SimpleVectorServiceProvider.d.ts.map +1 -1
- package/dist/models/SimpleVectorServiceProvider.js +429 -106
- package/dist/models/SimpleVectorServiceProvider.js.map +1 -1
- package/dist/models/StoredVector.d.ts +35 -0
- package/dist/models/StoredVector.d.ts.map +1 -0
- package/dist/models/StoredVector.js +83 -0
- package/dist/models/StoredVector.js.map +1 -0
- package/dist/models/VectorAccelerator.d.ts +109 -0
- package/dist/models/VectorAccelerator.d.ts.map +1 -0
- package/dist/models/VectorAccelerator.js +97 -0
- package/dist/models/VectorAccelerator.js.map +1 -0
- package/dist/models/VectorKernels.d.ts +117 -0
- package/dist/models/VectorKernels.d.ts.map +1 -0
- package/dist/models/VectorKernels.js +338 -0
- package/dist/models/VectorKernels.js.map +1 -0
- package/dist/models/VectorStore.d.ts +157 -0
- package/dist/models/VectorStore.d.ts.map +1 -0
- package/dist/models/VectorStore.js +376 -0
- package/dist/models/VectorStore.js.map +1 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -226,6 +226,8 @@ const allVectors = service.ExportVectors();
|
|
|
226
226
|
|
|
227
227
|
Dimension validation is automatic -- all vectors must have the same dimensionality.
|
|
228
228
|
|
|
229
|
+
Every input accepts a `VectorValues` value — `number[]`, `Float32Array` or `Float64Array` — and is copied into the packed store, so a vector decoded from a binary column (below) can be loaded without converting it to an array first.
|
|
230
|
+
|
|
229
231
|
## Clustering Algorithms
|
|
230
232
|
|
|
231
233
|
### K-Means (with K-Means++ Initialization)
|
|
@@ -316,17 +318,64 @@ results.forEach(r => {
|
|
|
316
318
|
});
|
|
317
319
|
```
|
|
318
320
|
|
|
321
|
+
## Storage and Precision
|
|
322
|
+
|
|
323
|
+
Vectors are stored packed — one contiguous typed array for the whole service, with each row's sum of squares cached — rather than one `number[]` per key. Searches allocate nothing per row, cosine needs only a dot product, and top-K selection is a bounded insertion instead of a full sort.
|
|
324
|
+
|
|
325
|
+
```typescript
|
|
326
|
+
// Default: float64. Every value and score is exactly as before.
|
|
327
|
+
const general = new SimpleVectorService();
|
|
328
|
+
|
|
329
|
+
// Model embeddings: float32 halves memory. Embeddings are float32 at the source,
|
|
330
|
+
// so scores differ from float64 only around the 7th significant digit.
|
|
331
|
+
const embeddings = new SimpleVectorService({ Precision: 'float32' });
|
|
332
|
+
embeddings.ReserveCapacity(rowCount, 1536); // optional: one allocation for a bulk load
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
Behaviour is unchanged from the `Map`-based implementation: same scores (bit-for-bit at float64), same tie-breaking (insertion order), same `topK` / threshold / filter semantics. `GetVector` and `ExportVectors` now return **copies**, so mutating a returned array no longer changes the stored vector. Subclasses that override a metric method (`CalculateDistance`, `CosineSimilarity`, …) keep working — the service detects the override and scores row by row through it.
|
|
336
|
+
|
|
337
|
+
## Reading Persisted Embeddings
|
|
338
|
+
|
|
339
|
+
MemberJunction stores each persisted embedding twice: a JSON column (`VectorJSON`, `EmbeddingVector`, …) and a binary companion (`VectorBinary`, `EmbeddingVectorBinary`, …) holding the same vector as little-endian float32 bytes, base64-encoded in a `BaseEntity`. Decoding the binary column is a copy; parsing the JSON builds a string per number (20,000 × 1,536 vectors on Node 22: 0.28 s vs 3.9 s). These helpers read either form:
|
|
340
|
+
|
|
341
|
+
| Function | Returns |
|
|
342
|
+
|---|---|
|
|
343
|
+
| `ReadStoredVector(binary, json)` | The binary vector when it is valid, otherwise the parsed JSON vector, otherwise `null` |
|
|
344
|
+
| `DecodeVectorBinary(binary)` | `Float32Array`, or `null` when missing, not base64, not a whole number of float32 values, or non-finite |
|
|
345
|
+
| `ParseVectorJSON(json)` | `number[]`, or `null` when missing, malformed, empty, or containing anything but finite numbers |
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
import { ReadStoredVector } from '@memberjunction/ai-vectors-memory';
|
|
349
|
+
|
|
350
|
+
const vector = ReadStoredVector(note.EmbeddingVectorBinary, note.EmbeddingVector);
|
|
351
|
+
if (vector) service.AddOrUpdateVector(note.ID, vector, metadata);
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
The JSON fallback covers rows written before the binary column existed, browser code that did not fetch binary fields (`RunView` omits them unless asked), and a corrupt binary value. The helpers are browser-safe. See the [Binary Fields Guide](../../../../guides/BINARY_FIELDS_GUIDE.md).
|
|
355
|
+
|
|
356
|
+
## Async Search and Server Acceleration
|
|
357
|
+
|
|
358
|
+
`FindNearestAsync`, `KMeansClusterAsync` and `DBSCANClusterAsync` take the same arguments and return the same results as their synchronous forms. In a browser, or anywhere no accelerator is registered, they run in-process. On a server that loads [`@memberjunction/ai-vectors-memory-server`](../MemoryServer/README.md), large searches and every clustering run move to a worker-thread pool reading the store through shared memory, optionally using a native SIMD backend — so the event loop keeps serving other requests.
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
const matches = await service.FindNearestAsync(queryVector, 10, 0.5, 'cosine', m => m.agentId === id);
|
|
362
|
+
const clusters = await service.KMeansClusterAsync(5);
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
The seam is `BaseVectorAccelerator`, resolved through the ClassFactory (`VECTOR_ACCELERATOR_KEY`). An accelerator only proposes candidate rows; the service re-scores them against its live store, so an accelerator — or a write racing a worker — can never surface a wrong score. Prefer the async forms in server code paths that handle requests.
|
|
366
|
+
|
|
319
367
|
## Performance Characteristics
|
|
320
368
|
|
|
321
369
|
| Operation | Complexity | Notes |
|
|
322
370
|
|---|---|---|
|
|
323
|
-
| AddVector / LoadVectors | O(1) per vector |
|
|
324
|
-
|
|
|
325
|
-
| FindNearest (
|
|
326
|
-
|
|
|
327
|
-
|
|
|
371
|
+
| AddVector / LoadVectors | O(1) amortized per vector | Packed storage; LoadVectors pre-sizes |
|
|
372
|
+
| RemoveVector | O(1) amortized | Tombstone; order-preserving compaction when >25% removed |
|
|
373
|
+
| FindNearest (no filter) | O(n·d) | Single pass, bounded top-K buffer, no sort |
|
|
374
|
+
| FindNearest (with filter) | O(n + m·d), m < n | Filter runs first; only matches are scored |
|
|
375
|
+
| KMeansCluster | O(n · k · d · iterations) | K-Means++ initialization |
|
|
376
|
+
| DBSCANCluster | O(n² · d) | Neighborhood pre-computation |
|
|
328
377
|
|
|
329
|
-
**Memory usage**:
|
|
378
|
+
**Memory usage**: `dimensions × 8 bytes` per vector at float64, `× 4 bytes` at float32, plus a few bytes of bookkeeping. Example: 20,000 embeddings at 1,536 dimensions is about 123 MB at float32.
|
|
330
379
|
|
|
331
380
|
## VectorDBBase Providers
|
|
332
381
|
|
|
@@ -336,9 +385,21 @@ This package ships **two `VectorDBBase` driver implementations** so the in-memor
|
|
|
336
385
|
|
|
337
386
|
In-process VectorDBBase driver that reads from an `MJ: Vector Indexes` row configured to point at any entity and field. Use when you have arbitrary entity rows with embeddings stored in a column and want to make them queryable through the `SearchEngine` cross-scope fusion path.
|
|
338
387
|
|
|
388
|
+
Rows are read on every query, as the calling user, so row-level security always applies. The parsed vectors are reused only when the index config and the rows just read (their keys, `__mj_UpdatedAt` values and vector presence) match what they were built from, so one user never receives another user's rows. After writing vectors by a path that bypasses `BaseEntity`, call `DeleteAllRecords(indexName)` to drop the cached vectors.
|
|
389
|
+
|
|
390
|
+
When the index's ProviderConfig names a `binaryVectorField`, the driver fetches that column too (setting `IncludeBinaryFields`) and prefers it over `vectorField`, falling back to the JSON for rows whose binary value is empty or invalid:
|
|
391
|
+
|
|
392
|
+
```json
|
|
393
|
+
{ "entityName": "MJ: AI Agent Notes", "vectorField": "EmbeddingVector", "binaryVectorField": "EmbeddingVectorBinary" }
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
**Metadata filters.** `QueryIndex` applies `QueryOptions.filter` in memory, using the same Pinecone/MongoDB-style language the remote drivers accept: a bare value (equality), `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$and` and `$or`. The filter sees the row's columns plus `Entity` / `EntityName` (the configured entity), `RecordID` (the prefixed primary-key segment) and `SourceType` (`'entity'`), so a search scope's filter means the same thing here as on Pinecone. A filter it cannot apply — an unknown operator, a malformed operand — fails the query with `Unsupported metadata filter: …` rather than running unfiltered, because a scope's tenant push-down lives in that filter. The evaluator is exported as `CompileMetadataFilter` for other in-process drivers.
|
|
397
|
+
|
|
398
|
+
The driver reports `IsReadOnly = true` and `RequiresAPIKey = false`, so ingestion pipelines skip it and it loads without a key. `ListVectorIDs` returns `{ IDs: [] }`: the contract carries no user, and rows are only readable as a calling user.
|
|
399
|
+
|
|
339
400
|
### `SimpleVectorServiceProvider` (new in v5.38)
|
|
340
401
|
|
|
341
|
-
**EntityDocument-keyed** in-process driver, purpose-built for `Provider.SearchEntities()` and any other `EntityDocument`-backed search. Each "index" corresponds to one `MJ: Entity Documents` row; vectors come from `MJ: Entity Record Documents
|
|
402
|
+
**EntityDocument-keyed** in-process driver, purpose-built for `Provider.SearchEntities()` and any other `EntityDocument`-backed search. Each "index" corresponds to one `MJ: Entity Documents` row; vectors come from `MJ: Entity Record Documents` rows filtered by `EntityDocumentID` — `VectorBinary` when valid, falling back to `VectorJSON` (both are fetched), and matches surface the **underlying entity record's RecordID** in their metadata (not the EntityRecordDocument PK).
|
|
342
403
|
|
|
343
404
|
```typescript
|
|
344
405
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
@@ -351,18 +412,18 @@ const result = await provider.QueryIndex(
|
|
|
351
412
|
// result.data.matches[i].metadata.RecordID is the parent record's ID
|
|
352
413
|
```
|
|
353
414
|
|
|
354
|
-
**
|
|
415
|
+
**Incrementally maintained cache:** one loaded index per `EntityDocumentID`, held at float32. Saves and deletes of `MJ: Entity Record Documents` rows — local, or on another server via `remote-invalidate` — are applied to the loaded index **row by row**; the index is never thrown away because one row changed. Remote changes use the broadcast record when the host opts the entity into record-data broadcast, otherwise only the changed rows are re-read (batched), once per user an index was loaded as, and each read is applied only to that user's indexes. Once the TTL (default 15 minutes) passes, the index keeps serving while it reloads in the background. Call `SimpleVectorServiceProvider.InvalidateIndex(entityDocumentId)` only after writing `VectorBinary` / `VectorJSON` by a path that bypasses `BaseEntity` (raw SQL, external tools); it forces the next query to reload first, even if a load was already running when you called it.
|
|
355
416
|
|
|
356
|
-
**Read-only:** ingestion methods (`CreateRecord`, `UpdateRecord`, etc.) throw via the `unsupported()` path. The vector-sync pipeline writes `EntityRecordDocument.VectorJSON` directly; this driver just rehydrates from those rows.
|
|
417
|
+
**Read-only:** ingestion methods (`CreateRecord`, `UpdateRecord`, etc.) throw via the `unsupported()` path. The vector-sync pipeline writes `EntityRecordDocument.VectorBinary` and `VectorJSON` directly; this driver just rehydrates from those rows.
|
|
357
418
|
|
|
358
|
-
**When NOT to use:**
|
|
419
|
+
**When NOT to use:** many hundreds of thousands of `EntityRecordDocument` rows per `EntityDocument`, or scenarios that need a persistent ANN index. For those, configure a colocated or remote provider (pgvector, SQL Server, Qdrant, Pinecone) on the `EntityDocument`'s `VectorDatabaseID` instead. (A server running `@memberjunction/ai-vectors-memory-server` can opt into an in-memory HNSW index for large stores.)
|
|
359
420
|
|
|
360
421
|
## Dependencies
|
|
361
422
|
|
|
362
423
|
| Package | Purpose |
|
|
363
424
|
|---|---|
|
|
364
|
-
| `@memberjunction/core` | `LogError`, `RunView`, `UserInfo` |
|
|
365
|
-
| `@memberjunction/global` | `RegisterClass` for VectorDBBase registrations |
|
|
425
|
+
| `@memberjunction/core` | `LogError`, `RunView`, `UserInfo`, `BaseEntityEvent` |
|
|
426
|
+
| `@memberjunction/global` | `RegisterClass` / ClassFactory for VectorDBBase and accelerator registrations, `BaseSingleton`, `EscapeSQLString` |
|
|
366
427
|
| `@memberjunction/ai-vectordb` | `VectorDBBase` contract that the two providers implement |
|
|
367
428
|
|
|
368
429
|
This package has minimal dependencies, making it lightweight and suitable for both server-side and client-side use.
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,12 @@
|
|
|
2
2
|
* @module @memberjunction/ai-vectors-memory
|
|
3
3
|
* @description In-memory vector similarity search service for MemberJunction
|
|
4
4
|
*/
|
|
5
|
-
export { SimpleVectorService, VectorEntry,
|
|
5
|
+
export { SimpleVectorService, SimpleVectorServiceOptions, VectorEntry, VectorInputEntry, VectorValues, VectorSearchResult, ClusterResult } from './models/SimpleVectorService.js';
|
|
6
|
+
export * from './models/VectorKernels.js';
|
|
7
|
+
export * from './models/VectorStore.js';
|
|
8
|
+
export * from './models/VectorAccelerator.js';
|
|
9
|
+
export * from './models/StoredVector.js';
|
|
10
|
+
export * from './models/MetadataFilterEvaluator.js';
|
|
6
11
|
export { SimpleVectorDatabase, LoadSimpleVectorDatabase } from './models/SimpleVectorDatabase.js';
|
|
7
12
|
export { SimpleVectorServiceProvider, SimpleVectorIndexCache, LoadSimpleVectorServiceProvider } from './models/SimpleVectorServiceProvider.js';
|
|
8
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,kBAAkB,EAClB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,WAAW,EACX,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACd,MAAM,8BAA8B,CAAC;AAEtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,kCAAkC,CAAC;AAEjD,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
* @description In-memory vector similarity search service for MemberJunction
|
|
4
4
|
*/
|
|
5
5
|
export { SimpleVectorService } from './models/SimpleVectorService.js';
|
|
6
|
+
export * from './models/VectorKernels.js';
|
|
7
|
+
export * from './models/VectorStore.js';
|
|
8
|
+
export * from './models/VectorAccelerator.js';
|
|
9
|
+
export * from './models/StoredVector.js';
|
|
10
|
+
export * from './models/MetadataFilterEvaluator.js';
|
|
6
11
|
export { SimpleVectorDatabase, LoadSimpleVectorDatabase } from './models/SimpleVectorDatabase.js';
|
|
7
12
|
export { SimpleVectorServiceProvider, SimpleVectorIndexCache, LoadSimpleVectorServiceProvider } from './models/SimpleVectorServiceProvider.js';
|
|
8
13
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,mBAAmB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,mBAAmB,EAOpB,MAAM,8BAA8B,CAAC;AAEtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,kCAAkC,CAAC;AAEjD,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Reads one field of the record a filter is evaluated against; `undefined` when it has none. */
|
|
2
|
+
export type MetadataFieldReader = (field: string) => unknown;
|
|
3
|
+
/** A compiled filter: true when the record the reader describes passes it. */
|
|
4
|
+
export type MetadataFilterPredicate = (read: MetadataFieldReader) => boolean;
|
|
5
|
+
/** The outcome of {@link CompileMetadataFilter}. */
|
|
6
|
+
export type MetadataFilterCompilation =
|
|
7
|
+
/** No filter was given (null, undefined or `{}`): every record passes. */
|
|
8
|
+
{
|
|
9
|
+
Status: 'none';
|
|
10
|
+
}
|
|
11
|
+
/** A valid filter. */
|
|
12
|
+
| {
|
|
13
|
+
Status: 'ok';
|
|
14
|
+
Predicate: MetadataFilterPredicate;
|
|
15
|
+
}
|
|
16
|
+
/** A filter was given that this evaluator cannot apply. The caller must not run the query unfiltered. */
|
|
17
|
+
| {
|
|
18
|
+
Status: 'unsupported';
|
|
19
|
+
Reason: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Validates `filter` and compiles it into a predicate.
|
|
23
|
+
*
|
|
24
|
+
* @param filter - The filter object (`QueryOptions.filter`), or nothing.
|
|
25
|
+
* @returns `none` when there is nothing to apply, `ok` with the predicate, or `unsupported` with the
|
|
26
|
+
* reason — an unknown operator, a non-array `$and` / `$in`, a nested object used as a value, and so on.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const compiled = CompileMetadataFilter({ Entity: { $in: ['Members'] }, Status: 'Active' });
|
|
31
|
+
* if (compiled.Status === 'ok') {
|
|
32
|
+
* const keep = compiled.Predicate(field => row[field]);
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare function CompileMetadataFilter(filter: object | null | undefined): MetadataFilterCompilation;
|
|
37
|
+
//# sourceMappingURL=MetadataFilterEvaluator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MetadataFilterEvaluator.d.ts","sourceRoot":"","sources":["../../src/models/MetadataFilterEvaluator.ts"],"names":[],"mappings":"AAoCA,iGAAiG;AACjG,MAAM,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC;AAE7D,8EAA8E;AAC9E,MAAM,MAAM,uBAAuB,GAAG,CAAC,IAAI,EAAE,mBAAmB,KAAK,OAAO,CAAC;AAE7E,oDAAoD;AACpD,MAAM,MAAM,yBAAyB;AACjC,0EAA0E;AACxE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE;AACpB,sBAAsB;GACpB;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,SAAS,EAAE,uBAAuB,CAAA;CAAE;AACtD,yGAAyG;GACvG;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAUhD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,yBAAyB,CAYlG"}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Evaluates a vector-database metadata filter in memory, for drivers that hold their vectors
|
|
3
|
+
* in-process (`SimpleVectorDatabase`) and so have no remote store to push the filter to.
|
|
4
|
+
*
|
|
5
|
+
* The language is the Pinecone / MongoDB-style object every MJ caller builds — `VectorSearchProvider`
|
|
6
|
+
* and `VectorMetadataFilter.ToNativeFilter` produce it, and a search scope's rendered
|
|
7
|
+
* `MetadataFilter` is written in it:
|
|
8
|
+
*
|
|
9
|
+
* ```json
|
|
10
|
+
* { "$and": [ { "Entity": { "$in": ["Members", "Accounts"] } }, { "OrganizationID": "8F2C…" } ] }
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* | Form | Meaning |
|
|
14
|
+
* |---|---|
|
|
15
|
+
* | `{ Field: value }` | equality (same as `{ Field: { $eq: value } }`) |
|
|
16
|
+
* | `$eq`, `$ne` | equal / not equal |
|
|
17
|
+
* | `$gt`, `$gte`, `$lt`, `$lte` | ordering — numbers, dates (as instants) or strings |
|
|
18
|
+
* | `$in`, `$nin` | membership in an array of values |
|
|
19
|
+
* | `$exists` | the field is present (non-null) or absent |
|
|
20
|
+
* | `$and`, `$or` | every / any of an array of sub-filters |
|
|
21
|
+
*
|
|
22
|
+
* Several conditions in one object must all hold. A field whose value is an array (a list of tags)
|
|
23
|
+
* matches `$eq` / `$in` when any element matches, and `$ne` / `$nin` when none does. An absent field
|
|
24
|
+
* fails every condition except `$ne`, `$nin`, `$exists: false` and equality with `null`, as in MongoDB.
|
|
25
|
+
*
|
|
26
|
+
* **Fail closed.** A filter is where a search scope's tenant and permission push-down lives, so an
|
|
27
|
+
* operator this evaluator does not understand is reported as `unsupported` — the caller must refuse
|
|
28
|
+
* the query rather than run it unfiltered. The filter is validated once, up front, by
|
|
29
|
+
* {@link CompileMetadataFilter}; evaluating the compiled predicate never throws.
|
|
30
|
+
*
|
|
31
|
+
* Browser-safe: no Node APIs.
|
|
32
|
+
*
|
|
33
|
+
* @module MetadataFilterEvaluator
|
|
34
|
+
*/
|
|
35
|
+
import { IsValidUUID, UUIDsEqual } from '@memberjunction/global';
|
|
36
|
+
const COMPARISON_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin', '$exists']);
|
|
37
|
+
/** Thrown inside compilation only; turned into an `unsupported` result by {@link CompileMetadataFilter}. */
|
|
38
|
+
class UnsupportedFilterError extends Error {
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Validates `filter` and compiles it into a predicate.
|
|
42
|
+
*
|
|
43
|
+
* @param filter - The filter object (`QueryOptions.filter`), or nothing.
|
|
44
|
+
* @returns `none` when there is nothing to apply, `ok` with the predicate, or `unsupported` with the
|
|
45
|
+
* reason — an unknown operator, a non-array `$and` / `$in`, a nested object used as a value, and so on.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* const compiled = CompileMetadataFilter({ Entity: { $in: ['Members'] }, Status: 'Active' });
|
|
50
|
+
* if (compiled.Status === 'ok') {
|
|
51
|
+
* const keep = compiled.Predicate(field => row[field]);
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export function CompileMetadataFilter(filter) {
|
|
56
|
+
if (filter == null)
|
|
57
|
+
return { Status: 'none' };
|
|
58
|
+
if (!isPlainObject(filter)) {
|
|
59
|
+
return { Status: 'unsupported', Reason: `a metadata filter must be an object, got ${describe(filter)}` };
|
|
60
|
+
}
|
|
61
|
+
if (Object.keys(filter).length === 0)
|
|
62
|
+
return { Status: 'none' };
|
|
63
|
+
try {
|
|
64
|
+
return { Status: 'ok', Predicate: compileObject(filter) };
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
if (e instanceof UnsupportedFilterError)
|
|
68
|
+
return { Status: 'unsupported', Reason: e.message };
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** One filter object: every key (logical operator or field) must hold. */
|
|
73
|
+
function compileObject(filter) {
|
|
74
|
+
const parts = [];
|
|
75
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
76
|
+
parts.push(key.startsWith('$') ? compileLogical(key, value) : compileField(key, value));
|
|
77
|
+
}
|
|
78
|
+
return read => parts.every(part => part(read));
|
|
79
|
+
}
|
|
80
|
+
/** `$and` / `$or` over an array of sub-filters. */
|
|
81
|
+
function compileLogical(operator, value) {
|
|
82
|
+
if (operator !== '$and' && operator !== '$or') {
|
|
83
|
+
throw new UnsupportedFilterError(`unsupported logical operator "${operator}"`);
|
|
84
|
+
}
|
|
85
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
86
|
+
throw new UnsupportedFilterError(`"${operator}" needs a non-empty array of filters`);
|
|
87
|
+
}
|
|
88
|
+
const parts = value.map((sub, i) => {
|
|
89
|
+
if (!isPlainObject(sub))
|
|
90
|
+
throw new UnsupportedFilterError(`"${operator}[${i}]" must be an object, got ${describe(sub)}`);
|
|
91
|
+
return compileObject(sub);
|
|
92
|
+
});
|
|
93
|
+
return operator === '$and'
|
|
94
|
+
? read => parts.every(part => part(read))
|
|
95
|
+
: read => parts.some(part => part(read));
|
|
96
|
+
}
|
|
97
|
+
/** One field's condition: a bare value (equality) or an object of comparison operators. */
|
|
98
|
+
function compileField(field, condition) {
|
|
99
|
+
if (!isPlainObject(condition)) {
|
|
100
|
+
const equals = equalsPredicate(toScalar(condition, field));
|
|
101
|
+
return read => equals(read(field));
|
|
102
|
+
}
|
|
103
|
+
const operators = Object.entries(condition);
|
|
104
|
+
if (operators.length === 0)
|
|
105
|
+
throw new UnsupportedFilterError(`"${field}" has an empty condition object`);
|
|
106
|
+
const parts = operators.map(([op, operand]) => compileOperator(field, op, operand));
|
|
107
|
+
return read => {
|
|
108
|
+
const actual = read(field);
|
|
109
|
+
return parts.every(part => part(actual));
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** One comparison operator applied to a field's value. */
|
|
113
|
+
function compileOperator(field, op, operand) {
|
|
114
|
+
if (!COMPARISON_OPERATORS.has(op))
|
|
115
|
+
throw new UnsupportedFilterError(`unsupported operator "${op}" on "${field}"`);
|
|
116
|
+
const path = `${field}.${op}`;
|
|
117
|
+
switch (op) {
|
|
118
|
+
case '$eq': return equalsPredicate(toScalar(operand, path));
|
|
119
|
+
case '$ne': {
|
|
120
|
+
const equals = equalsPredicate(toScalar(operand, path));
|
|
121
|
+
return actual => !equals(actual);
|
|
122
|
+
}
|
|
123
|
+
case '$in': {
|
|
124
|
+
const vs = toScalarArray(operand, path);
|
|
125
|
+
return actual => matchesAny(actual, a => vs.some(v => valuesEqual(a, v)));
|
|
126
|
+
}
|
|
127
|
+
case '$nin': {
|
|
128
|
+
const vs = toScalarArray(operand, path);
|
|
129
|
+
return actual => !matchesAny(actual, a => vs.some(v => valuesEqual(a, v)));
|
|
130
|
+
}
|
|
131
|
+
case '$exists': {
|
|
132
|
+
if (typeof operand !== 'boolean')
|
|
133
|
+
throw new UnsupportedFilterError(`"${path}" needs true or false`);
|
|
134
|
+
return actual => (actual != null) === operand;
|
|
135
|
+
}
|
|
136
|
+
default: {
|
|
137
|
+
const v = toScalar(operand, path);
|
|
138
|
+
if (v === null || typeof v === 'boolean')
|
|
139
|
+
throw new UnsupportedFilterError(`"${path}" needs a number, date or string`);
|
|
140
|
+
return actual => matchesAny(actual, a => orderingHolds(op, compare(a, v)));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Equality with one filter scalar. `null` matches a null or absent field (as in MongoDB); any other
|
|
146
|
+
* value matches the field, or any element of an array-valued field.
|
|
147
|
+
*/
|
|
148
|
+
function equalsPredicate(expected) {
|
|
149
|
+
if (expected === null)
|
|
150
|
+
return actual => actual == null;
|
|
151
|
+
return actual => matchesAny(actual, a => valuesEqual(a, expected));
|
|
152
|
+
}
|
|
153
|
+
/** For an array-valued field, true when any element matches; for a scalar, whether it matches. Absent never matches. */
|
|
154
|
+
function matchesAny(actual, test) {
|
|
155
|
+
if (actual === undefined || actual === null)
|
|
156
|
+
return false;
|
|
157
|
+
return Array.isArray(actual) ? actual.some(test) : test(actual);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Equality between a record value and a filter scalar. Two UUIDs compare case-insensitively (SQL
|
|
161
|
+
* Server returns them upper case, PostgreSQL lower case); a `Date` compares by instant with an ISO
|
|
162
|
+
* string or epoch number; everything else is strict.
|
|
163
|
+
*/
|
|
164
|
+
function valuesEqual(actual, expected) {
|
|
165
|
+
if (expected === null)
|
|
166
|
+
return actual == null;
|
|
167
|
+
if (actual instanceof Date) {
|
|
168
|
+
const instant = toInstant(expected);
|
|
169
|
+
return instant !== null && actual.getTime() === instant;
|
|
170
|
+
}
|
|
171
|
+
if (typeof actual === 'string' && typeof expected === 'string') {
|
|
172
|
+
return actual === expected || (IsValidUUID(actual) && IsValidUUID(expected) && UUIDsEqual(actual, expected));
|
|
173
|
+
}
|
|
174
|
+
return actual === expected;
|
|
175
|
+
}
|
|
176
|
+
/** Orders a record value against a filter scalar: negative, 0 or positive, or null when they cannot be compared. */
|
|
177
|
+
function compare(actual, expected) {
|
|
178
|
+
if (actual instanceof Date) {
|
|
179
|
+
const instant = toInstant(expected);
|
|
180
|
+
return instant === null ? null : actual.getTime() - instant;
|
|
181
|
+
}
|
|
182
|
+
if (typeof actual === 'number' && typeof expected === 'number')
|
|
183
|
+
return actual - expected;
|
|
184
|
+
if (typeof actual === 'string' && typeof expected === 'string')
|
|
185
|
+
return actual < expected ? -1 : actual > expected ? 1 : 0;
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
function orderingHolds(op, order) {
|
|
189
|
+
if (order === null || Number.isNaN(order))
|
|
190
|
+
return false;
|
|
191
|
+
switch (op) {
|
|
192
|
+
case '$gt': return order > 0;
|
|
193
|
+
case '$gte': return order >= 0;
|
|
194
|
+
case '$lt': return order < 0;
|
|
195
|
+
default: return order <= 0; // $lte — the only remaining ordering operator
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** An epoch-ms instant from a filter scalar (a number, or a parseable date string), or null. */
|
|
199
|
+
function toInstant(value) {
|
|
200
|
+
if (typeof value === 'number')
|
|
201
|
+
return value;
|
|
202
|
+
if (typeof value === 'string') {
|
|
203
|
+
const ms = Date.parse(value);
|
|
204
|
+
return Number.isNaN(ms) ? null : ms;
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
/** A filter operand as a scalar; `path` names it in the error (`Entity.$in[0]`). */
|
|
209
|
+
function toScalar(value, path) {
|
|
210
|
+
if (value === null)
|
|
211
|
+
return null;
|
|
212
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
213
|
+
return value;
|
|
214
|
+
if (value instanceof Date)
|
|
215
|
+
return value.toISOString();
|
|
216
|
+
throw new UnsupportedFilterError(`"${path}" must be a string, number, boolean or null, got ${describe(value)}`);
|
|
217
|
+
}
|
|
218
|
+
function toScalarArray(value, path) {
|
|
219
|
+
if (!Array.isArray(value))
|
|
220
|
+
throw new UnsupportedFilterError(`"${path}" needs an array, got ${describe(value)}`);
|
|
221
|
+
return value.map((v, i) => toScalar(v, `${path}[${i}]`));
|
|
222
|
+
}
|
|
223
|
+
function isPlainObject(value) {
|
|
224
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
225
|
+
}
|
|
226
|
+
function describe(value) {
|
|
227
|
+
if (value === null)
|
|
228
|
+
return 'null';
|
|
229
|
+
if (Array.isArray(value))
|
|
230
|
+
return 'an array';
|
|
231
|
+
return typeof value === 'object' ? 'an object' : typeof value;
|
|
232
|
+
}
|
|
233
|
+
//# sourceMappingURL=MetadataFilterEvaluator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MetadataFilterEvaluator.js","sourceRoot":"","sources":["../../src/models/MetadataFilterEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAA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;AAED,SAAS,aAAa,CAAC,KAAc;IACjC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC;AAC5G,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC5B,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAClC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC;IAC5C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC;AAClE,CAAC"}
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Use this driver when you want SearchScope multi-provider fusion to include
|
|
5
5
|
* vector search WITHOUT standing up a remote store (Pinecone / pgvector /
|
|
6
|
-
* Qdrant). It reads the rows of a single MJ entity,
|
|
7
|
-
*
|
|
6
|
+
* Qdrant). It reads the rows of a single MJ entity, decodes each row's
|
|
7
|
+
* vector column(s), and uses {@link SimpleVectorService} for
|
|
8
8
|
* cosine ranking — exactly the same primitive `AgentContextInjector` already
|
|
9
9
|
* uses for its `FindSimilarAgentNotes` path.
|
|
10
10
|
*
|
|
@@ -44,31 +44,70 @@ export declare class SimpleVectorDatabase extends VectorDBBase {
|
|
|
44
44
|
/** Materialize the index — load rows from the configured entity, parse
|
|
45
45
|
* each row's vector, and pack them into a `SimpleVectorService`.
|
|
46
46
|
*
|
|
47
|
-
* **Cache freshness model:** the
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
47
|
+
* **Cache freshness model:** the rows are read on every query, as the
|
|
48
|
+
* calling user, so row-level security always applies. The parsed
|
|
49
|
+
* vectors are reused only when the index config is unchanged and the
|
|
50
|
+
* rows just read have the same keys, `__mj_UpdatedAt` values and
|
|
51
|
+
* vector presence as the rows they were built from. A user who sees a
|
|
52
|
+
* different set of rows therefore never receives another user's
|
|
53
|
+
* vectors. An edit that bypasses `BaseEntity` (raw SQL that changes a
|
|
54
|
+
* vector without touching `__mj_UpdatedAt`) is not detected; call
|
|
55
|
+
* `DeleteAllRecords` after one. Production-scale corpora should use
|
|
56
|
+
* Pinecone/Qdrant. */
|
|
54
57
|
private loadIndex;
|
|
58
|
+
/**
|
|
59
|
+
* Identifies the rows a cached index was built from: the set of columns
|
|
60
|
+
* that came back, then each row's primary key, `__mj_UpdatedAt` and
|
|
61
|
+
* whether it has a vector, in the order read. Far cheaper than re-parsing
|
|
62
|
+
* every vector, and it differs whenever the rows a query sees differ —
|
|
63
|
+
* another user's row-level security, an insert-plus-delete that keeps the
|
|
64
|
+
* count, or a vector added or edited.
|
|
65
|
+
*
|
|
66
|
+
* The column set matters because the cache is shared across users and the
|
|
67
|
+
* provider drops each user's field-level-security-denied columns from the
|
|
68
|
+
* SELECT. Without it, a user who may not read `Title` or `Body` would be
|
|
69
|
+
* served the title and snippet another user's rows carried.
|
|
70
|
+
*/
|
|
71
|
+
private rowsFingerprint;
|
|
55
72
|
/** Run RunView for the configured entity; returns null if the entity is
|
|
56
73
|
* unknown or the RunView call failed (both already logged). The entity's
|
|
57
74
|
* metadata comes back alongside the rows because its primary key column(s)
|
|
58
75
|
* — not a hardcoded `ID` — are what key each vector. */
|
|
59
76
|
private fetchEntityRows;
|
|
60
|
-
/**
|
|
77
|
+
/** Decode each row's vector (binary companion first, then the JSON field), and
|
|
61
78
|
* pack the survivors into a fresh `SimpleVectorService` plus the
|
|
62
79
|
* ID→row map used to enrich match metadata. Rows with missing IDs,
|
|
63
80
|
* missing vector columns, or unparseable JSON are silently skipped
|
|
64
81
|
* — callers haven't necessarily embedded every row yet (e.g. only
|
|
65
|
-
* `Status='Active'` rows have embeddings), so logging would spam.
|
|
82
|
+
* `Status='Active'` rows have embeddings), so logging would spam.
|
|
83
|
+
* Rows whose vector size differs from the first one are skipped too,
|
|
84
|
+
* with one log line, since they point at an embedding-model mix-up. */
|
|
66
85
|
private buildServiceFromRows;
|
|
86
|
+
/**
|
|
87
|
+
* Reads one row's vector: the binary companion when configured and valid, else the JSON field
|
|
88
|
+
* (a JSON string, or an already-parsed numeric array). Returns null for a row with no usable
|
|
89
|
+
* vector — callers haven't necessarily embedded every row yet.
|
|
90
|
+
*/
|
|
91
|
+
private readRowVector;
|
|
67
92
|
/** Build the metadata bag returned in QueryIndex matches. Mirrors what
|
|
68
93
|
* Pinecone/Qdrant return so {@link VectorSearchProvider.convertMatches}
|
|
69
94
|
* can consume it without special-casing. */
|
|
70
95
|
private buildMatchMetadata;
|
|
71
96
|
QueryIndex(params: QueryOptions, contextUser?: UserInfo): Promise<BaseResponse>;
|
|
97
|
+
/**
|
|
98
|
+
* Adapts a compiled metadata filter to the service's per-row filter. The filter sees the row's
|
|
99
|
+
* own columns plus the fields remote drivers store as vector metadata, so one filter means the
|
|
100
|
+
* same thing on every driver: `Entity` and `EntityName` (the configured entity name —
|
|
101
|
+
* `VectorSearchProvider` filters on the first, `SharedIndexFilterOptions.EntityNames` on the
|
|
102
|
+
* second), `RecordID` (the prefixed primary-key segment) and `SourceType` (`'entity'` — every row
|
|
103
|
+
* here is an entity record). These names take precedence over a row column of the same name.
|
|
104
|
+
*/
|
|
105
|
+
private rowFilter;
|
|
106
|
+
/** Vectors live in entity rows written by `BaseEntity` saves; this driver never ingests, so
|
|
107
|
+
* ingestion pipelines should skip it instead of logging an "unsupported" error per batch. */
|
|
108
|
+
get IsReadOnly(): boolean;
|
|
109
|
+
/** In-process — it reads entity rows through `RunView` and calls no external service, so it needs no API key. */
|
|
110
|
+
get RequiresAPIKey(): boolean;
|
|
72
111
|
ListIndexes(): IndexList;
|
|
73
112
|
GetIndex(_p: BaseRequestParams): BaseResponse;
|
|
74
113
|
CreateIndex(_p: CreateIndexParams): BaseResponse;
|
|
@@ -83,6 +122,11 @@ export declare class SimpleVectorDatabase extends VectorDBBase {
|
|
|
83
122
|
DeleteRecord(_r: VectorRecord): BaseResponse;
|
|
84
123
|
DeleteRecords(_r: VectorRecord[]): BaseResponse;
|
|
85
124
|
DeleteAllRecords(_n: string): BaseResponse;
|
|
125
|
+
/**
|
|
126
|
+
* Lists no IDs. The vectors are rows of the configured entity, readable only as a calling user
|
|
127
|
+
* (row-level security applies), and this contract carries no user — so there is no honest list
|
|
128
|
+
* to return. Callers that reconcile a remote store against its source skip read-only drivers.
|
|
129
|
+
*/
|
|
86
130
|
ListVectorIDs(_p: ListVectorIDsParams): Promise<ListVectorIDsResult>;
|
|
87
131
|
private unsupported;
|
|
88
132
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SimpleVectorDatabase.d.ts","sourceRoot":"","sources":["../../src/models/SimpleVectorDatabase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAAoE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAClH,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,KAAK,EACR,iBAAiB,EAAE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EACnE,SAAS,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,aAAa,EAAE,YAAY,EACnF,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"SimpleVectorDatabase.d.ts","sourceRoot":"","sources":["../../src/models/SimpleVectorDatabase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAAoE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAClH,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,KAAK,EACR,iBAAiB,EAAE,YAAY,EAAE,iBAA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