Watch the video above for the step-by-step math trace and live demo on 26,614 passages. This companion piece is the architecture decision guide, code contract, and production fallback spec behind why rag-core uses 28-line Reciprocal Rank Fusion, and when hybrid search isn’t worth the extra complexity.
Most teams reach for a larger LLM or a paid cloud retrieval stack the moment their RAG app misses an obvious document. In practice, retrieval failures rarely come from generation. They come from asking a single search algorithm to handle two conflicting jobs at once: exact technical syntax and paraphrased human intent.
Across 240 learner questions over 1,371 documentation files on my learning platform, BM25 keyword search alone only placed the expected document in the top three 30% of the time when learners phrased questions differently from the docs. Bridging BM25 and dense vector search with a 28-line Reciprocal Rank Fusion (fusion.py) function lifted paraphrased top-3 accuracy to 66.7% and overall accuracy to 75%, without changing the LLM.
Retrieval Decision Matrix: When to Stop and When to Upgrade
Adding hybrid retrieval introduces embedding models, GPU/latency overhead (~150 ms locally), and another failure surface. Use this matrix to decide how far down the retrieval stack a product actually needs to go:
| Retrieval Stage | Excels At | Blind Spot | Extra Infrastructure | Measured rag-core Result | When to Stop Here |
|---|---|---|---|---|---|
| Keyword (BM25) | Exact flags, error codes, function/CLI names | Paraphrased queries (“skip heavy tests” vs “slow test marker”) | None (zero AI models, zero GPU) | 30.0% top-3 on paraphrased LMS queries | Internal docs searched mainly by exact symbols or tight zero-GPU constraints |
| Vector-Only | Semantic similarity when wording differs | Exact jargon, version strings, specific syntax | Embedding model + vector index | 64 / 137 #1 hits (85 / 137 top-3) | Rarely alone for technical docs; misses exact tokens |
Hybrid (BM25 + Vector + RRF k = 60) | Consensus between exact terms and semantic intent | Cannot recover a passage that missed both top-200 lists | Both indexes + 28 lines of Python | 66.7% paraphrased top-3 (75% overall) | Strong default baseline before paying reranker latency |
| Hybrid + Cross-Encoder Reranker | Fine-grained passage precision on top-30 candidates | Extra inference latency per query | Cross-encoder model | 100 / 137 #1 hits (121 / 137, >88% top-3) | High-stakes Q&A where #1 precision directly drives answer quality |
Why Rank Fusion Beats Score Blending
Merging BM25 and vector results by adding raw scores fails because the two scales are incompatible: BM25 might score a top match at 14.8 while cosine similarity scores its best match at 0.84. Adding them lets keyword scores drown out vector similarity, much like adding a 100-point exam score to a 5-star rating.
Reciprocal Rank Fusion (RRF) avoids fragile score normalization by discarding raw scores completely and scoring only finishing rank (rank starting at 1):
score(passage) = sum over lists of 1 / (k + rank) with k = 60
Why k = 60 matters as a product guard rather than an arbitrary constant:
- At
k = 1, an isolated fluke ranked #1 in one retriever (1 / 2 = 0.50) beats a consensus passage ranked #3 and #4 across both retrievers (1/4 + 1/5 = 0.45). - At
k = 60, that same single-list fluke drops to1 / 61 ≈ 0.0164, while the two-list consensus passage scores1/63 + 1/64 ≈ 0.0315(nearly double).
Where RRF still has limits: RRF only reorders what upstream retrievers hand it (top 200 each in rag-core). If chunk boundaries sliced an answer apart or neither judge surfaced the passage in its candidate window, RRF cannot rescue it.
fusion.py and Its Three Production Invariants
Rather than pulling in a heavy framework wrapper, rag-core keeps fusion in 28 lines of standard-library Python (fusion.py):
"""Reciprocal rank fusion (spec 15 section 3.2): merge ranked lists without needing comparable scores."""
from __future__ import annotations
K = 60
def rrf(lists: list[list[int]], k: int = K, n: int | None = None) -> list[tuple[int, float]]:
"""Rows from all lists, best first, each with its fused score: the sum of 1 / (k + rank) over the lists it is in
(ranks from 1; a row repeated inside one list counts once, at its first rank). Equal scores (the same ranks in the
same lists) go to the lower row position, so the order is repeatable."""
if k < 1:
raise ValueError(f"k must be at least 1, got {k}")
if n is not None and n < 1:
raise ValueError(f"n must be at least 1, got {n}")
score: dict[int, float] = {}
for ranked in lists:
seen: set[int] = set()
for rank, row in enumerate(ranked, start=1):
if row in seen:
continue
seen.add(row)
score[row] = score.get(row, 0.0) + 1.0 / (k + rank)
fused = sorted(score, key=lambda row: (-score[row], row))
return [(row, score[row]) for row in fused[:n]]
Three small engineering choices inside this function prevent subtle bugs in evaluation and production:
- Per-list deduplication (
seen): If an upstream retriever emits duplicate row IDs, a passage cannot double-dip points; only its highest rank counts. - Explicit bounds validation (
k < 1,n < 1): Misconfiguration fails immediately instead of silently returning empty or skewed rankings. - Deterministic tie-breaking (
(-score[row], row)): Identical fused scores always break by lower row ID, so repeated benchmark runs produce identical ordering (pinned by 9 unit tests intest_fusion.py).
The Production Fallback Contract: Never Fail Quietly
Any retrieval tier that depends on neural models can fail: a model fails to load, an index goes offline, or a request hits a strict latency budget. When wiring rag-core into my learning platform, I kept hybrid search optional behind a single retriever interface and enforced three rules:
- Zero-dependency floor: Keyword-only BM25 requires no AI models and no GPU, so retrieval stays available even if every embedding service is down.
- Automatic degradation without crashing: If hybrid retrieval fails or times out, the retriever automatically falls back to keyword search.
- Explicit user disclosure: The response visibly labels itself
keyword search onlynext to the answer, never faking full hybrid confidence when running in degraded mode.
Stated Limits and What I Deliberately Skipped
Good retrieval engineering is as much about what you leave out as what you add:
- Evaluation transparency: On the 137-question passage validation set (where hybrid + reranker hit 100/137 at #1 and 121/137 in the top 3), the benchmark is not blind. Every passage in the 26,614-passage index also carries its upstream URL, licence, and exact character span verified at index build time so errors remain auditable.
- Contextual retrieval skipped on purpose: Adding LLM-generated passage context or running exhaustive chunk sweeps could push the hardest paraphrased queries past 90%, at the cost of extra indexing spend and complexity. I designed that step and parked it: ship a measured baseline first, and pay extra latency or cost only when real users prove you need it.
Links & Resources
- Live Interactive Demo (26,614 passages on Hugging Face): https://huggingface.co/spaces/asheeshsrivastava9/rag-core-portfolio
- Source Code (
rag-coreon GitHub): https://github.com/AsheeshSrivastava/Content-Library-Aethelgard-Academy - YouTube Walkthrough: https://www.youtube.com/watch?v=iS5hw3ZNPt0
