Mental model
Retrieval evaluation decouples search and ranking quality from downstream LLM generation by scoring retrieved evidence chunks directly against versioned relevance judgments (qrels), expected citations, and access-control boundaries—preventing teams from misdiagnosing missing or misranked documents as prompt failures.
Learning outcomes
- Separate candidate-generation recall metrics (
Recall@K) from top-slot ranking precision metrics (MRR@10,nDCG@10). - Construct stratified golden datasets including rare exceptions, multi-hop queries, unanswerable negative controls, and tenant ACL boundaries.
- Diagnose whether end-to-end RAG failures originate in chunking, lexical/dense fusion, cross-encoder reranking, or generator synthesis.
Theory
Grading only the final LLM response obscures whether an incorrect answer came from hallucination over strong evidence or starvation because retrieval returned noisy or obsolete chunks. Evaluating each pipeline boundary independently reveals the true failure bottleneck before code or prompts change:
| Retrieval Stage | Primary Metrics | Question Answered | Concrete Intervention When Low |
|---|---|---|---|
| Index & Chunk Coverage | Gold Span Presence in Corpus (%) | Did PDF/HTML parsing or splitting clip the table or heading? | Switch to structure-aware / parent-child chunking |
Candidate Generator (BM25 + HNSW) | Recall@50, Recall@100 | Does the decisive chunk enter the coarse candidate set at all? | Improve query expansion, RRF hybrid weights, embeddings |
| Cross-Encoder Reranker | nDCG@10, MRR@10, Precision@5 | Are decisive chunks promoted into the top 3–5 LLM context slots? | Upgrade cross-encoder checkpoint or calibrate score cutoffs |
| Governance & Freshness Slice | UnauthorizedLeakRate == 0, StaleVersionRate | Did superseded docs or cross-tenant records bypass filters? | Enforce pre-filter ACLs & atomic index tombstones |
Standard metrics rely on binary (relevant in {0, 1}) or graded (0..3) labels per (query_id, doc_chunk_id):
Beyond positive passages, production test suites must maintain hard negatives (lexically near-identical documents from superseded fiscal years or sibling product tiers) and abstention queries where no authoritative chunk exists so rerankers cannot inflate recall simply by returning maximum chunk counts indiscriminately.
pythonimport mathfrom typing import Mapping, Sequencedef evaluate_retrieval_slice(ranked_results: Mapping[str, Sequence[str]],graded_qrels: Mapping[str, Mapping[str, int]],k_recall: int = 20,k_rank: int = 10,) -> dict[str, float]:"""Compute Recall@K, MRR@K, and nDCG@K cleanly across a frozen evaluation dataset."""recalls, mrrs, ndcgs = [], [], []for qid, rel_map in graded_qrels.items():positives = {doc_id for doc_id, grade in rel_map.items() if grade > 0}if not positives:continuepreds = list(ranked_results.get(qid, []))hits = [doc_id for doc_id in preds[:k_recall] if doc_id in positives]recalls.append(len(hits) / len(positives))rr = next((1.0 / (idx + 1) for idx, doc_id in enumerate(preds[:k_rank]) if doc_id in positives), 0.0)mrrs.append(rr)dcg = sum((2 ** rel_map.get(d, 0) - 1) / math.log2(idx + 2) for idx, d in enumerate(preds[:k_rank]))ideal = sorted(rel_map.values(), reverse=True)[:k_rank]idcg = sum((2 ** rel - 1) / math.log2(idx + 2) for idx, rel in enumerate(ideal))ndcgs.append(dcg / idcg if idcg > 0 else 0.0)n = max(1, len(recalls))return {f"recall@{k_recall}": round(sum(recalls) / n, 4),f"mrr@{k_rank}": round(sum(mrrs) / n, 4),f"ndcg@{k_rank}": round(sum(ndcgs) / n, 4),}
Trade-offs
Offline static evaluation benchmarks (qrels) deliver fast deterministic CI regression checks whenever teams tune chunk overlaps, hybrid weights, or rerankers cleanly before deployment, yet slowly drift behind emerging enterprise acronyms and newly ingested corpora unless refreshed from sanitized production misses. Conversely, live online telemetry (citation clicks, user thumbs, reformulation rate) captures real-world ambiguity cleanly while remaining heavily confounded by UI layout, generator verbosity, and latency variance. Pairing compact CI holdouts with weekly human-audited stratified failure sampling combines determinism with live relevance tracking cleanly.
Failure modes and misconceptions
- Grading End-to-End Answers Only: Blaming LLM hallucination or prompt formatting when
Recall@50for the target policy chunk is already0%. - Synthetic Query Leakage: Evaluating chunkers solely using questions generated cleanly from those identical chunks inflates
nDCGartificially compared to terse messy user queries. - Unsegmented Metric Averaging: Reporting a healthy
0.86global recall while customer-facing rare policy exceptions fail70%of the time due to un-weighted query distributions. - Omitting Security & Version Negatives: Never asserting that deleted documents, restricted tenant folders, or deprecated pricing PDFs rank at zero relevance scores.
Decision scenario
An enterprise HR assistant answers common PTO queries accurately (92%) yet hallucinates outdated answers whenever staff ask about state-specific parental leave exceptions. Design a segmented retrieval benchmark measuring corpus extraction, Recall@50, nDCG@5, and superseded-policy false positives separately before touching system prompts.
Which retrieval evaluation metrics distinguish missing a relevant document during candidate search from misranking it below noisy distractors?