From 5ee0b9ebb76acc4ad90c3662856c26975ffd0446 Mon Sep 17 00:00:00 2001 From: Ori <18102267+oritwoen@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:11:10 +0100 Subject: [PATCH] fix: drop stale chunks --- skills/retriv/SKILL.md | 5 ++-- src/retriv.ts | 51 +++++++++++++++++++++++++++++---------- test/retriv.test.ts | 55 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 16 deletions(-) diff --git a/skills/retriv/SKILL.md b/skills/retriv/SKILL.md index f93debc..80c456f 100644 --- a/skills/retriv/SKILL.md +++ b/skills/retriv/SKILL.md @@ -57,7 +57,7 @@ await search.close?.() ## Common tasks -`returnContent: true` returns a 5-line snippet around the best matching line, not the stored text. Keep your own copy and re-index changed documents through `remove()`: +`returnContent: true` returns a 5-line snippet around the best matching line, not the stored text. Keep your own copy. `index()` with an existing id replaces that document, old chunks included: ```ts import type { Document } from 'retriv' @@ -69,7 +69,6 @@ const docs = new Map() const search = await createRetriv({ driver: sqliteFts({ path: './.search/fts.db' }), chunking: markdownChunker() }) export async function upsert(doc: Document): Promise { - await search.remove?.([doc.id]) // index() alone leaves old #chunk- rows behind await search.index([doc]) docs.set(doc.id, doc) } @@ -119,7 +118,7 @@ export default { - **Upstash and Cloudflare filter in memory** over the `limit * 4` nearest vectors, so a selective filter can return few rows or none; raise `limit`. There, `$ne` keeps a document without the field but drops one without metadata, `a.b` never matches, and a bad field name returns `[]`. - **One model per index.** The vector table takes its dimensions from the first open; another model on the same file throws `Dimension mismatch`. `cachedEmbeddings` hashes only the text, so give each model its own storage. Never pass `dimensions` to `transformersJs()` for a known model; a wrong value gives silent garbage vectors. - **pgvector recall is low by default.** The driver builds ivfflat (`lists = 100`) before rows exist, and `ivfflat.probes` is 1: recall@10 is near 0.2, and about 0.44 after `REINDEX`. Replace it with HNSW under the same name, which the driver's `CREATE INDEX IF NOT EXISTS` keeps: `DROP INDEX vectors_embedding_idx; CREATE INDEX vectors_embedding_idx ON vectors USING hnsw (embedding vector_cosine_ops)`. Use `_embedding_idx` and the opclass for `metric`. To keep ivfflat, run `REINDEX`, then `ALTER DATABASE SET ivfflat.probes = 10`. -- **Cloudflare:** `remove()` with chunking and `clear()` throw. Each vector keeps its text in metadata, which Cloudflare caps at 10 KiB, so chunk large documents. `retriv/embeddings/cached` needs `nodejs_compat`. +- **Cloudflare:** `remove()` with chunking and `clear()` throw, and re-indexing a chunked document leaves its old `#chunk-` rows behind. Each vector keeps its text in metadata, which Cloudflare caps at 10 KiB, so chunk large documents. `retriv/embeddings/cached` needs `nodejs_compat`. ## Version limits diff --git a/src/retriv.ts b/src/retriv.ts index c8ad50a..9302c4b 100644 --- a/src/retriv.ts +++ b/src/retriv.ts @@ -40,6 +40,14 @@ function applyRRF(resultSets: SearchResult[][]): SearchResult[] { .map(({ score, result }) => ({ ...result, score })) } +const CHUNK_SEPARATOR = '#chunk-' + +/** Chunk rows are stored as `#chunk-`. */ +function parentIdOf(id: string): string { + const sep = id.indexOf(CHUNK_SEPARATOR) + return sep >= 0 ? id.substring(0, sep) : id +} + /** * Create a unified retrieval instance */ @@ -72,6 +80,21 @@ export async function createRetriv(options: RetrivOptions): Promise() const seenCategories = new Set() const categorize = options.categories + /** Stored ids, listed once per instance. */ + let knownIds: Set | undefined + + /** Stored rows of the re-indexed documents that the new chunks no longer cover. */ + async function staleIds(docs: Document[], prepared: Document[]): Promise { + if (!knownIds) { + const lister = drivers.find(d => d.listIds) + if (!lister) + return [] + knownIds = new Set(await lister.listIds!()) + } + const parents = new Set(docs.map(d => d.id)) + const fresh = new Set(prepared.map(d => d.id)) + return Array.from(knownIds).filter(id => parents.has(parentIdOf(id)) && !fresh.has(id)) + } async function prepareDocs(docs: Document[], onProgress?: IndexOptions['onProgress']): Promise { if (categorize) { @@ -104,7 +127,7 @@ export async function createRetriv(options: RetrivOptions): Promise d.index(prepared, options))) + if (stale.length) + await Promise.all(drivers.filter(d => d.remove).map(d => d.remove!(stale))) + if (knownIds) { + for (const id of stale) + knownIds.delete(id) + for (const doc of prepared) + knownIds.add(doc.id) + } return { count: results[0].count } }, @@ -227,18 +259,15 @@ export async function createRetriv(options: RetrivOptions): Promise { - if (idSet.has(id)) - return true - const sep = id.indexOf('#chunk-') - return sep >= 0 && idSet.has(id.substring(0, sep)) - }) + removeIds = allIds.filter(id => idSet.has(id) || idSet.has(parentIdOf(id))) } const results = await Promise.all( drivers.filter(d => d.remove).map(d => d.remove!(removeIds)), ) for (const id of ids) parentDocs.delete(id) + for (const id of removeIds) + knownIds?.delete(id) return { count: results[0]?.count ?? 0 } }, @@ -247,17 +276,13 @@ export async function createRetriv(options: RetrivOptions): Promise() - for (const id of ids) { - const sep = id.indexOf('#chunk-') - parentIds.add(sep >= 0 ? id.substring(0, sep) : id) - } - return Array.from(parentIds) + return Array.from(new Set(ids.map(parentIdOf))) }, async clear() { await Promise.all(drivers.filter(d => d.clear).map(d => d.clear!())) parentDocs.clear() + knownIds?.clear() }, async close() { diff --git a/test/retriv.test.ts b/test/retriv.test.ts index 5d257a8..5a09c03 100644 --- a/test/retriv.test.ts +++ b/test/retriv.test.ts @@ -150,6 +150,61 @@ describe('createRetriv', () => { expect(doc2Results.length).toBeGreaterThanOrEqual(1) }) + it('replaces the old chunks when a chunked document is indexed again', async () => { + const retriv = await createRetriv({ + driver: sqliteFts({ path: ':memory:' }), + chunking: markdownChunker({ chunkSize: 100, chunkOverlap: 0 }), + }) + const long = Array.from({ length: 4 }, (_, i) => `## Part ${i}\n\nold wombat text ${i} ${'filler '.repeat(8)}`).join('\n\n') + + await retriv.index([ + { id: 'notes.md', content: long }, + { id: 'other.md', content: long }, + ]) + await retriv.index([{ id: 'notes.md', content: 'new wombat text' }]) + + const ids = (await retriv.search('wombat', { limit: 20 })).map(r => r.id).sort() + expect(ids).toEqual(['notes.md', 'other.md#chunk-0', 'other.md#chunk-1', 'other.md#chunk-2', 'other.md#chunk-3']) + }) + + it('drops the unchunked row when a document grows into chunks', async () => { + const retriv = await createRetriv({ + driver: sqliteFts({ path: ':memory:' }), + chunking: markdownChunker({ chunkSize: 100, chunkOverlap: 0 }), + }) + const long = Array.from({ length: 3 }, (_, i) => `## Part ${i}\n\nnew wombat text ${i} ${'filler '.repeat(8)}`).join('\n\n') + + await retriv.index([{ id: 'notes.md', content: 'old wombat text' }]) + await retriv.index([{ id: 'notes.md', content: long }]) + + const ids = (await retriv.search('wombat', { limit: 20 })).map(r => r.id).sort() + expect(ids).toEqual(['notes.md#chunk-0', 'notes.md#chunk-1', 'notes.md#chunk-2']) + }) + + it('still indexes chunked documents on a driver without listIds()', async () => { + const indexed: string[] = [] + const removed: string[] = [] + const retriv = await createRetriv({ + driver: { + async index(docs) { + indexed.push(...docs.map(d => d.id)) + return { count: docs.length } + }, + async search() { return [] }, + async remove(ids) { + removed.push(...ids) + return { count: ids.length } + }, + }, + chunking: markdownChunker({ chunkSize: 100, chunkOverlap: 0 }), + }) + + await retriv.index([{ id: 'notes.md', content: 'new wombat text' }]) + + expect(indexed).toEqual(['notes.md']) + expect(removed).toEqual([]) + }) + it('extracts snippets with highlights', async () => { const retriv = await createRetriv({ driver: sqliteFts({ path: ':memory:' }),