@dudousxd/nestjs-agent-rag 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,6 +99,57 @@ before the repair only become filterable on that key once re-ingested). A change
99
99
  model swap — can't be repaired without a full reindex, so it throws `RedisVectorSchemaMismatchError`
100
100
  instead of silently leaving the index on the old width.
101
101
 
102
+ ## Changing metadata without re-embedding
103
+
104
+ Some metadata is derived from the document's content and only changes when the content does (its
105
+ size, its mime type, its ingestion fingerprint). Some isn't: who may see it, which bases or teams it
106
+ is relevant to, what it was last classified as. That second kind changes on its own schedule, and
107
+ without a way to say so you are left choosing between re-embedding a whole document to change a
108
+ string — paying the model bill, and the ingestion budget, for a reclassification — or refusing to
109
+ stamp the dimension onto chunks at all and resolving it at query time instead, which turns a filter
110
+ the index could have applied into a join you have to.
111
+
112
+ `updateMetadata` is that way to say so. It rewrites the metadata of **every chunk** of a document and
113
+ touches neither the text nor the embeddings:
114
+
115
+ ```ts
116
+ // this document now covers bases B and C, and no longer A. No embedding is recomputed.
117
+ const chunks = await store.updateMetadata(documentId, { bases: ['B', 'C'] });
118
+ ```
119
+
120
+ The patch is applied as a shallow [JSON Merge Patch](https://www.rfc-editor.org/rfc/rfc7386):
121
+
122
+ | in the patch | effect |
123
+ | --- | --- |
124
+ | key absent | the stored value is kept — this is a **partial** update, not a replacement |
125
+ | `key: value` | the stored value is replaced |
126
+ | `key: [a, b]` | replaced **wholesale** — an array is a set-valued dimension, not something to append to |
127
+ | `key: null` | the key is **removed**. This is the only way to remove one |
128
+ | `key: undefined` | **ignored**, as if the patch had not mentioned the key |
129
+
130
+ `undefined` is ignored rather than treated as a removal on purpose. It does not survive
131
+ `JSON.stringify`, and a patch routinely crosses a JSON boundary (an HTTP body, a workflow step
132
+ payload) on its way in, so honouring it would make `{ audience: undefined }` mean *delete* on one
133
+ side of that boundary and *no-op* on the other. It is also what `{ ...doc, audience: doc.audience }`
134
+ produces by accident — and an accidental deletion of an access-control dimension is the worst thing
135
+ this API could do. The cost is that a literal `null` cannot be stored as a value, which is no loss:
136
+ "absent" and "null" filter identically anyway.
137
+
138
+ The return value is the number of chunks written. **An unknown document id updates nothing and
139
+ returns `0` rather than throwing** — like `remove`, this is a reconciliation-shaped call, made by a
140
+ loop diffing your source of truth against the index, and such a loop races with ingestion and
141
+ deletion by construction; an exception would make the ordinary case an error you had to catch and
142
+ swallow. (A patch that writes nothing also returns `0`: the count is chunks *written*, not chunks
143
+ *matched*.)
144
+
145
+ Both representations move together. `RedisVectorStore` stores metadata twice — as `meta_<field>`
146
+ TAGs, which is what RediSearch filters on, and as a `metadata_json` blob, which is what comes back on
147
+ a `Passage` — and `updateMetadata` rewrites both from the same merged object, dropping the TAG of a
148
+ removed key rather than leaving it matching a value the document no longer carries. A patched chunk
149
+ is indistinguishable from a re-ingested one: filtering on the new value finds it, filtering on the
150
+ old value does not, and the metadata read back off a retrieved passage agrees with both. (A plain
151
+ `HSET` is all RediSearch needs to re-index — proven against a real Redis Stack, not assumed.)
152
+
102
153
  ## Hybrid search (dense + lexical)
103
154
 
104
155
  `HybridRetriever` fuses several retrievers with Reciprocal Rank Fusion. RRF is **rank**-based, so the
@@ -192,6 +243,59 @@ library upgrade. The interface is open, so it can be added later without changin
192
243
  - `KeywordRetriever` — in-process BM25 over chunks you feed it; the single-process lexical half:
193
244
  `add(chunks)`, `remove(documentId)`, `clear()`, `size`.
194
245
  - `HybridRetriever(retrievers, { k?, fetchTopK?, weights? })` — RRF fusion of the two.
195
- - `MemoryVectorStore` / `PgVectorStore` / `RedisVectorStore` — `VectorStore` adapters.
246
+ - `MemoryVectorStore` / `PgVectorStore` / `RedisVectorStore` — `VectorStore` adapters:
247
+ `upsert(records)`, `search(embedding, opts)`, `remove(documentId)`,
248
+ `updateMetadata(documentId, patch)`, `listDocuments(filter?)`.
249
+ - `applyMetadataPatch(metadata, patch)` — the `MetadataPatch` merge semantics, exported so your own
250
+ `VectorStore` can implement `updateMetadata` with exactly the same ones.
196
251
  - `isLexicalVectorStore(store)` — type guard for the optional `LexicalVectorStore` capability.
197
252
  - `createRetrievalTool(retriever, { name?, description?, topK? })` — the agentic-retrieval tool.
253
+
254
+ ## Collection maintenance
255
+
256
+ `remove` and `listDocuments` can only enumerate documents *with* their metadata and delete them *one
257
+ at a time*, which makes routine maintenance quadratic-ish: dropping a 2 000-document collection that
258
+ way is one `listDocuments()` that parses a metadata blob per chunk, then 2 000 `remove()` calls — and
259
+ on Redis each of those is a `SCAN` over the whole keyspace, queues and app cache included.
260
+
261
+ So `VectorStore` **requires** four more methods, each doing the same work as one filtered query. They
262
+ are not an optional capability and there is nothing to narrow to — every store has them:
263
+
264
+ ```ts
265
+ await store.countChunks({ collection: 'handbook' }); // FT.SEARCH LIMIT 0 0 / count(*)
266
+ await store.listDocumentIds({ collection: 'handbook' }); // ids only — no metadata round-trip
267
+ await store.removeWhere({ collection: 'handbook' }); // one query, returns chunks removed
268
+ await store.removeMany(['doc-a', 'doc-b']); // N documents, one pass
269
+ ```
270
+
271
+ `removeWhere` is the destructive one, so it has two rules worth knowing before you call it:
272
+
273
+ | filter | result |
274
+ |---|---|
275
+ | `{ collection: 'handbook' }` | deletes that scope, returns the chunk count |
276
+ | `{ audience: [] }` (or any empty array) | **deletes nothing**, returns `0` — the empty array is this package's deny primitive, and a deny must never be read as "no filter" |
277
+ | `{}` | throws `UnsafeRemovalError` — an empty filter is far more often a filter built wrong than a deliberate request to wipe the store |
278
+ | `{ notFilterable: 'x' }` (Redis) | throws `UnsafeRemovalError` — the key has no `meta_*` TAG to match on |
279
+
280
+ Deliberate mass deletion is still available; it just has to be spelled out:
281
+ `await store.removeMany(await store.listDocumentIds())`.
282
+
283
+ `VectorStore.remove` deliberately stays a `SCAN` on the Redis adapter. Turning it into an `FT.SEARCH`
284
+ would mean stamping the document id as an indexed field at write time, and chunks written before that
285
+ change carry no such field — the search would find none of them and `remove` would silently stop
286
+ deleting. The methods above need no new field, so they have no migration.
287
+
288
+ ### Why these are required and `searchText` is optional
289
+
290
+ A method is **required on `VectorStore`** when every backend can implement it from what it already
291
+ stores. Enumeration and bulk deletion are CRUD over records the store already holds — the same
292
+ footing as `remove` and `listDocuments` — so making them optional would only cost every consumer a
293
+ permanent `if (supported)` and an unreachable "and if it isn't?" branch.
294
+
295
+ A method goes in an **optional capability interface** when some backend genuinely *cannot* provide it
296
+ without infrastructure the consumer has to adopt. `LexicalVectorStore.searchText` is the only one
297
+ today, and it earns it: RediSearch has BM25 natively, Postgres needs a `tsvector` column, a GIN index
298
+ and a migration you run and watch, and `MemoryVectorStore` would have to implement BM25 itself.
299
+
300
+ The test is whether a backend can do it at all — not whether adding it would inconvenience an
301
+ implementer who has already shipped.