Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions skills/retriv/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -69,7 +69,6 @@ const docs = new Map<string, Document>()
const search = await createRetriv({ driver: sqliteFts({ path: './.search/fts.db' }), chunking: markdownChunker() })

export async function upsert(doc: Document): Promise<void> {
await search.remove?.([doc.id]) // index() alone leaves old <id>#chunk-<n> rows behind
await search.index([doc])
docs.set(doc.id, doc)
}
Expand Down Expand Up @@ -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 `<table>_embedding_idx` and the opclass for `metric`. To keep ivfflat, run `REINDEX`, then `ALTER DATABASE <db> 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 `<id>#chunk-<n>` 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

Expand Down
51 changes: 38 additions & 13 deletions src/retriv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ function applyRRF(resultSets: SearchResult[][]): SearchResult[] {
.map(({ score, result }) => ({ ...result, score }))
}

const CHUNK_SEPARATOR = '#chunk-'

/** Chunk rows are stored as `<parentId>#chunk-<n>`. */
function parentIdOf(id: string): string {
const sep = id.indexOf(CHUNK_SEPARATOR)
return sep >= 0 ? id.substring(0, sep) : id
}

/**
* Create a unified retrieval instance
*/
Expand Down Expand Up @@ -72,6 +80,21 @@ export async function createRetriv(options: RetrivOptions): Promise<SearchProvid
const parentDocs = new Map<string, Document>()
const seenCategories = new Set<string>()
const categorize = options.categories
/** Stored ids, listed once per instance. */
let knownIds: Set<string> | undefined

/** Stored rows of the re-indexed documents that the new chunks no longer cover. */
async function staleIds(docs: Document[], prepared: Document[]): Promise<string[]> {
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<Document[]> {
if (categorize) {
Expand Down Expand Up @@ -104,7 +127,7 @@ export async function createRetriv(options: RetrivOptions): Promise<SearchProvid
: chunk.text

chunkedDocs.push({
id: `${doc.id}#chunk-${i}`,
id: `${doc.id}${CHUNK_SEPARATOR}${i}`,
content,
metadata: {
...doc.metadata,
Expand Down Expand Up @@ -159,7 +182,16 @@ export async function createRetriv(options: RetrivOptions): Promise<SearchProvid
return {
async index(docs: Document[], options?: IndexOptions) {
const prepared = await prepareDocs(docs, options?.onProgress)
const stale = chunker ? await staleIds(docs, prepared) : []
const results = await Promise.all(drivers.map(d => 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 }
},

Expand Down Expand Up @@ -227,18 +259,15 @@ export async function createRetriv(options: RetrivOptions): Promise<SearchProvid
throw new Error('remove() with chunking requires a driver that implements listIds() — cloudflare does not support this')
const allIds = await lister.listIds!()
const idSet = new Set(ids)
removeIds = allIds.filter((id) => {
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 }
},

Expand All @@ -247,17 +276,13 @@ export async function createRetriv(options: RetrivOptions): Promise<SearchProvid
const ids = await driver?.listIds?.() ?? []
if (!chunker)
return ids
const parentIds = new Set<string>()
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() {
Expand Down
55 changes: 55 additions & 0 deletions test/retriv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:' }),
Expand Down
Loading