FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Retrieval Evaluation

Measure whether retrieval finds sufficient, relevant, authorized, and fresh evidence before grading generation.

Freshness: current•15 min read•Retrieval and Knowledge Systems

Key Learning Outcomes

  • ✓Explain the operating model behind Retrieval Evaluation.
  • ✓Evaluate trade-offs and failure modes for Retrieval Evaluation.
  • ✓Apply Retrieval Evaluation to a production decision.
Full Technical Reference Document

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.

Versioned query + qrel golden set
Candidate generation (Recall@K)
Reranker ordering (nDCG / MRR)
Negative ACL & freshness slices
Threshold gate & root-cause log
Conceptual teaching model synthesized from:Introduction to Information RetrievalEvaluation Best Practices

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 StagePrimary MetricsQuestion AnsweredConcrete Intervention When Low
Index & Chunk CoverageGold 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@100Does the decisive chunk enter the coarse candidate set at all?Improve query expansion, RRF hybrid weights, embeddings
Cross-Encoder RerankernDCG@10, MRR@10, Precision@5Are decisive chunks promoted into the top 3–5 LLM context slots?Upgrade cross-encoder checkpoint or calibrate score cutoffs
Governance & Freshness SliceUnauthorizedLeakRate == 0, StaleVersionRateDid 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):

MRR=1∣Q∣∑q∈Q1rankq,nDCG@K=1∣Q∣∑q∈Q∑i=1K2reli−1log⁡2(i+1)IDCGq@K\text{MRR} = \frac{1}{|Q|} \sum_{q \in Q} \frac{1}{\text{rank}_q}, \qquad \text{nDCG}@K = \frac{1}{|Q|} \sum_{q \in Q} \frac{\sum_{i=1}^{K} \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)}}{\text{IDCG}_q@K}

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.

python
import math
from typing import Mapping, Sequence
​
def 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:
continue
preds = 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@50 for the target policy chunk is already 0%.
  • Synthetic Query Leakage: Evaluating chunkers solely using questions generated cleanly from those identical chunks inflates nDCG artificially compared to terse messy user queries.
  • Unsegmented Metric Averaging: Reporting a healthy 0.86 global recall while customer-facing rare policy exceptions fail 70% 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.

Reflect before revealing the guide

Which retrieval evaluation metrics distinguish missing a relevant document during candidate search from misranking it below noisy distractors?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next