fix(rag): make BM25 indexing incremental and idempotent - #81
Open
Agnik47 wants to merge 1 commit into
Open
Conversation
`addToBM25Index` rescanned the whole `docLengths` map on every insert to recompute `avgDocLength`, making ingest O(n^2) in the number of chunks. It also incremented `docCount` unconditionally, so re-adding a chunk ID — which happens on a forced or resumed ingest, since chunk IDs are deterministic — pushed `docCount` above `docLengths.size` and corrupted both `avgDocLength` and idf for every term, while leaving stale postings for the replaced content. Track a running `totalLength`, and replace an existing entry (dropping its postings and length) before re-adding it. Ingest is now linear and BM25 scores no longer depend on run history. Fixes supermemoryai#74 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JqGuPVWVYRJEJQp2RXchf1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #74.
Problem
Two defects in
addToBM25Index(src/providers/rag/search.ts).1. Quadratic ingest.
avgDocLengthwas recomputed by walking the entiredocLengthsmap on every single insert, so indexing n chunks scanned the map n times.2. Re-ingest corrupted the index.
addChunksoverwritescontainer.chunks(idempotent) butaddToBM25Indexunconditionally diddocCount++. Chunk IDs are deterministic (${containerTag}_${sessionId}_${chunkIndex}), so a forced or resumed ingest re-adds the same IDs —docCountdrifted abovedocLengths.size, which skewed:avgDocLength = totalLength / docCount→ understated, distorting length normalisation for every documentidf = log((docCount - df + 0.5) / (df + 0.5) + 1)→ inflated for every termPostings from the replaced content were also left behind, so a chunk kept matching terms that were no longer in its text. Since BM25 carries 30% of the hybrid score,
ragretrieval quality depended on run history rather than on the algorithm.Fix
totalLengthon the index instead of rescanning.docTerms(distinct terms per document) soremoveFromBM25Indexcan drop an entry's postings, length and count in O(terms) before it is re-added.addToBM25Indexnow replaces rather than appends, keepingdocCount === docLengths.sizeand the inverted index consistent with current content.No public API change;
HybridSearchEnginebehaves identically for a fresh ingest.Tests
New
src/providers/rag/search.test.ts(3 tests, run withbun test):All three fail on
mainand pass with this change.Ingest timing
addChunkswith 30-token chunks, before → after:Before scales ~4x per doubling; after, ~2x.
bunx tsc --noEmitis clean and the new file is Prettier-clean. I left the pre-existing Prettier warnings elsewhere insearch.tsalone to keep the diff scoped —bun run format:checkalready fails on 69 files onmain.🤖 Generated with Claude Code
https://claude.ai/code/session_01JqGuPVWVYRJEJQp2RXchf1