One Answer Score, Three Different Faults: Measure RAG Retrieval Before You Judge the Answer
An answer score tells you a RAG system failed, not where. This article builds the retrieval half of the evaluation: a versioned golden set, hand-verified metrics, triage that names the stage that lost the answer, and a CI gate on per-query regressions.

Three configurations of the same retriever score 0.969 on recall@5 over the same 32 queries. The first loses an exact lookup of an error code. The other two find that one and lose a paraphrased question about a missing refund instead. Averaged, the three are indistinguishable, and an answer-quality score computed further downstream would inherit the same blindness with model noise added on top.
That result comes from the harness built in this article, and it is the reason to treat RAG evaluation metrics as a retrieval problem first. An end-to-end score says whether the final answer was acceptable. It cannot say whether the document was missing from the index, present but ranked too low to reach the prompt, or sitting in the prompt and ignored. Those are three different defects with three different owners, and they need separate measurements.
One bit of answer quality cannot localise a fault
A grounded answer is the last link of a chain: the document is indexed, it appears among the retriever's candidates, it ranks high enough to be included in the context, the model uses it, and a grader accepts the result. An answer score observes only the end of that chain. When it drops, every link is a suspect.
It can also stay flat while a link breaks. A model that has seen similar material in training can answer correctly without the document. The score records a success, retrieval has failed, and the failure will surface later on a question about private or recent data that no model has memorised. Any evaluation that cannot see this case will overstate how well retrieval works.
Figure 1. Three ways to lose an answer, and one way to get it right without retrieval having worked.
There is a practical asymmetry as well. Retrieval metrics are deterministic, need no model call and run in seconds, so they can gate every change. Answer grading needs a model or a person, costs money, and carries its own variance. Running the cheap, exact measurement first means the expensive, noisy one is only asked about the stage it can actually judge. The same idea, attributing a failure to one stage of a pipeline instead of observing only the response, is what tracing does for distributed systems.
A golden set is a dataset with a schema and an expiry date
The harness runs on the fixture from the hybrid retriever built in the previous article: 36 knowledge-base entries for a fictional payments API and 32 queries in four classes. What changes here is how relevance is recorded.
{"version": 1, "corpus_fingerprint": "a9624a17c1f2f263", "grades": "0 not relevant, 1 related, 2 answers", "pool": "top 5 of bm25 and vector"} {"id": "q09", "class": "paraphrase", "query": "shopper says the money never came back", "judgments": {"kb-01": 0, "kb-03": 0, "kb-05": 1, "kb-06": 2, "kb-09": 0, "kb-14": 0, "kb-18": 0, "kb-23": 0, "kb-30": 0}}
Four decisions are encoded in those two lines.
Grades, not a yes/no flag. Grade 2 means the entry answers the question, grade 1 means it is related and would help. Binary metrics such as recall use a threshold (grade 2 here), while nDCG uses the grades directly. Järvelin and Kekäläinen introduced cumulated gain for exactly this reason: binary judgments give a marginally relevant document the same credit as a highly relevant one.
An explicit zero is different from no entry. A document with grade 0 was looked at and rejected. A document that is absent was never judged. Metrics treat both as non-relevant, which is the convention in pooled test collections such as TREC's, and that convention penalises any new system that surfaces documents nobody has judged. The harness therefore reports how much of each result list was judged at all.
A query class on every row. Every number in the report is broken down by class. The opening example is invisible without it.
A corpus fingerprint. Judgments point at document ids. If a document is edited, split or re-chunked, the judgments silently refer to something else. The header stores a hash of the corpus that was judged, and the harness refuses to run when it no longer matches.
def corpus_fingerprint(docs: dict[str, str]) -> str: """Changes when any document id or text changes. Judgments are only valid for the corpus they were made against.""" digest = hashlib.sha256() for doc_id in sorted(docs): digest.update(doc_id.encode() + b"\x00" + docs[doc_id].encode() + b"\x00") return digest.hexdigest()[:16] def validate(header: dict, queries: list[GoldenQuery], docs: dict[str, str]) -> list[str]: """Returns the reasons this golden set must not be used with this corpus.""" problems = [] if header.get("corpus_fingerprint") != corpus_fingerprint(docs): problems.append("corpus changed since the judgments were made (fingerprint mismatch)") seen: set[str] = set() for q in queries: if q.id in seen: problems.append(f"{q.id}: duplicate query id") seen.add(q.id) unknown = sorted(set(q.judgments) - set(docs)) if unknown: problems.append(f"{q.id}: judgments refer to documents that do not exist: {unknown}") if not any(grade >= 2 for grade in q.judgments.values()): problems.append(f"{q.id}: no document with grade 2, so recall is undefined") if any(grade not in (0, 1, 2) for grade in q.judgments.values()): problems.append(f"{q.id}: grades must be 0, 1 or 2") return problems
Where the queries come from matters more than how many there are. Queries written by someone looking at the documents tend to reuse their vocabulary, which flatters lexical retrieval. Sampling real questions from search logs or support tickets, then adding deliberately hard classes such as paraphrases and identifiers, gives a set that resembles traffic. Public benchmarks do not replace this: the BEIR study evaluated ten retrieval systems on 18 datasets without in-domain training and found that BM25 remained a strong baseline while dense retrievers generalised less well than re-ranking and late-interaction models. A leaderboard position is weak evidence about a private corpus.
RAG evaluation metrics, implemented and checked by hand
Each metric answers a different question, and the choice of k should come from the system, not from habit.
| Metric | Question it answers | Typical use |
|---|---|---|
| recall@k | What share of the relevant documents is in the top k? | Is the evidence available to a later stage? |
| hit@k | Is at least one relevant document in the top k? | With k set to the context size: can this be answered at all? |
| MRR | How early is the first relevant document? | Ranking quality when one document suffices |
| nDCG@k | How close is the whole ordering to ideal, by grade? | Ranking quality with graded relevance |
def recall_at_k(ranked: Sequence[str], judgments: Judgments, k: int, min_grade: int = 2) -> float: """Share of the relevant documents that appear in the top k.""" relevant = relevant_ids(judgments, min_grade) if not relevant: raise ValueError("a query with no relevant document cannot be scored for recall") return len(relevant & set(ranked[:k])) / len(relevant) def reciprocal_rank(ranked: Sequence[str], judgments: Judgments, k: int = 10, min_grade: int = 2) -> float: """1 / position of the first relevant document, 0 if none is in the top k.""" relevant = relevant_ids(judgments, min_grade) for position, doc_id in enumerate(ranked[:k], start=1): if doc_id in relevant: return 1 / position return 0.0 def dcg(grades: Sequence[int]) -> float: """Discounted cumulative gain with the exponential gain 2^grade - 1 and a log2 discount.""" return sum((2 ** g - 1) / math.log2(position + 1) for position, g in enumerate(grades, start=1)) def ndcg_at_k(ranked: Sequence[str], judgments: Judgments, k: int) -> float: """DCG of the ranking divided by the DCG of the best possible ranking. The ideal ranking is built from ALL judged documents, not from the ones that were retrieved. Normalising by the retrieved set gives a perfect score to a system that returns one weak document and misses every strong one. """ ideal = dcg(sorted(judgments.values(), reverse=True)[:k]) if ideal == 0: raise ValueError("a query with no relevant document cannot be scored for nDCG") return dcg([judgments.get(doc_id, 0) for doc_id in ranked[:k]]) / ideal
Two details in the listing are deliberate. A query with no relevant document raises an error and does not return zero, because a zero would be averaged into the mean as a retrieval failure when the fault is in the golden set. And dcg uses the exponential gain 2^grade - 1, which widens the gap between grades; the original formulation used the grade itself as the gain. Either is defensible. What matters is to fix one and write it down, since two teams computing "nDCG" with different gain functions will report different numbers for the same ranking.
Figure 2. One ranked list, six numbers. The relevant document that was never returned lowers recall and nDCG and leaves MRR untouched.
The worked example in Figure 2 is also the first unit test. Every value was computed by hand and asserted to four decimal places, so the implementation is checked against arithmetic and not against another library's output.
The most common nDCG bug deserves its own test. The ideal ranking has to be built from every judged document for the query. Building it from the documents the system happened to retrieve normalises a ranking against itself:
def test_ndcg_is_normalised_by_all_judged_documents_not_by_the_retrieved_ones(): # The system returns only the weak document. Normalising by what it retrieved would score 1.0. ranked = ["d2"] retrieved_only_ideal = dcg(sorted((JUDGMENTS.get(d, 0) for d in ranked), reverse=True)) assert dcg([JUDGMENTS[d] for d in ranked]) / retrieved_only_ideal == 1.0 # the bug assert ndcg_at_k(ranked, JUDGMENTS, k=5) == pytest.approx(1 / 5.3928, abs=1e-4) # the metric
A system that returns one weak document and misses both strong ones scores a perfect 1.0 under the buggy normalisation and 0.185 under the correct one. The bug is easy to introduce when the metric function receives only the retrieved list with labels attached.
Triage: name the stage that lost the answer
Metrics summarise. Triage classifies each query by the first stage that failed, using the candidate list, the context size and, when available, a graded answer.
@dataclass(frozen=True) class Answer: """What the generation stage reports for one query. Produced by your grader, not here.""" correct: bool cited: Sequence[str] = field(default_factory=tuple) def triage(ranked: Sequence[str], judgments: Judgments, context_k: int, answer: Answer | None = None) -> str: """`ranked` is the full candidate list; only its first `context_k` ids reach the prompt.""" relevant = relevant_ids(judgments) in_context = bool(relevant & set(ranked[:context_k])) if answer is not None and answer.correct and not in_context: return "correct_without_evidence" # right, but not because of retrieval if not relevant & set(ranked): return "not_retrieved" # an indexing or recall problem if not in_context: return "ranked_low" # a ranking or context-budget problem if answer is None: return "in_context" # retrieval did its job; generation not assessed if not answer.correct or not relevant & set(answer.cited): return "ignored" # a prompting or model problem return "grounded"
The order of the checks is the design. correct_without_evidence is tested first, because a correct answer would otherwise hide the retrieval failure behind it. not_retrieved and ranked_low are separated by whether the relevant document appears anywhere in the candidate list, which is why the harness keeps the full list of 20 candidates and not just the three that reach the prompt. ignored covers both a wrong answer and a right answer that cites the wrong document, since in both cases the evidence in the context was not what produced the answer.
The generation stage here is a scripted stand-in, in the same spirit as the scripted model used to test the agent loop in the first article of this series. It reads only the first two context documents and is told to "know" one answer without evidence. Its purpose is to exercise every branch; it says nothing about how a real model behaves. On the baseline retriever the report is:
system: rrf golden v1 corpus a9624a17c1f2f263 recall@5 hit@3 mrr@10 ndcg@10 judged@5 all 0.969 0.906 0.828 0.850 0.887 identifier 0.875 0.750 0.594 0.706 0.850 mixed 1.000 1.000 1.000 0.978 0.900 paraphrase 1.000 0.875 0.719 0.737 0.875 plain 1.000 1.000 1.000 0.978 0.925 answer accuracy (scripted reader): 0.906 stages: correct_without_evidence=1, grounded=28, ignored=1, ranked_low=2 q01 [identifier] ranked_low: first relevant at 4 q02 [identifier] correct_without_evidence: first relevant at 6 q06 [identifier] ignored: first relevant at 3 q09 [paraphrase] ranked_low: first relevant at 4
Answer accuracy is 0.906, and that single number contains four different stories. Two queries failed because the document was retrieved and ranked fourth while only three documents reach the prompt: a ranking problem, fixable in fusion or with a reranker. One failed with the document in the context: a generation problem. One succeeded with no evidence in the context and is counted among the 29 correct answers. Recall@5 of 0.969 looked reassuring only because it was measured at a k larger than the context; hit@3, measured at the real cut-off, is 0.906.
The judged@5 column carries a second warning. The pool for this golden set was the top five of each single arm, and the fused system returns documents outside it: 11% of its top-five results have no judgment and are scored as non-relevant by default. Before trusting a comparison in which one system has a much lower judged share than the other, the missing documents should be labelled.
A regression gate that fails on queries, not only on means
A gate compares a candidate report with a baseline committed to the repository.
@dataclass(frozen=True) class Policy: # Largest tolerated drop of each mean, in absolute points. With N queries one query # moves recall by 1/N, so a tolerance below that is zero tolerance. max_drop: dict[str, float] = field(default_factory=lambda: {"recall@5": 0.0, "ndcg@10": 0.02}) max_new_failures: int = 0 # queries that had a relevant document in the top K and lost it @dataclass class GateResult: passed: bool reasons: list[str] new_failures: list[str] fixed: list[str] deltas: dict[str, tuple[float, float, float]] # metric -> (mean diff, CI low, CI high) def _passes(row: dict) -> bool: return row["first_relevant"] is not None and row["first_relevant"] <= K def compare(baseline: dict, candidate: dict, policy: Policy = Policy(), accepted: frozenset[str] = frozenset()) -> GateResult: for key in ("golden_version", "corpus_fingerprint"): if baseline[key] != candidate[key]: raise ValueError(f"reports are not comparable: {key} differs ({baseline[key]} vs {candidate[key]})") ids = list(baseline["queries"]) if ids != list(candidate["queries"]): raise ValueError("reports are not comparable: different queries") before, after = baseline["queries"], candidate["queries"] new_failures = [q for q in ids if _passes(before[q]) and not _passes(after[q])] fixed = [q for q in ids if not _passes(before[q]) and _passes(after[q])] deltas = {m: paired_bootstrap([before[q][m] for q in ids], [after[q][m] for q in ids]) for m in ("recall@5", "mrr@10", "ndcg@10")} reasons = [] for metric, tolerance in policy.max_drop.items(): drop = baseline["metrics"][metric] - candidate["metrics"][metric] if drop > tolerance + 1e-9: reasons.append(f"{metric} fell {drop:.3f} (allowed {tolerance:.3f})") unreviewed = [q for q in new_failures if q not in accepted] if len(unreviewed) > policy.max_new_failures: reasons.append(f"{len(unreviewed)} query(ies) newly fail at k={K}: {', '.join(unreviewed)}") return GateResult(not reasons, reasons, new_failures, fixed, deltas)
Here is the gate applied to a change that looks like a clear improvement: letting the dense arm abstain below a similarity floor.
baseline rrf -> candidate rrf_floor recall@5 0.969 -> 0.969 diff +0.000 95% CI [-0.094, +0.094] mrr@10 0.828 -> 0.938 diff +0.109 95% CI [+0.031, +0.203] ndcg@10 0.850 -> 0.926 diff +0.076 95% CI [+0.015, +0.148] newly failing: q09 [paraphrase] first relevant 4 -> 11 (ranked_low) fixed: q02 [identifier] first relevant 6 -> 1 (in_context) FAIL: 1 query(ies) newly fail at k=5: q09 exit code 1
MRR and nDCG improve, with bootstrap intervals that exclude zero. Mean recall is unchanged. A gate on means would pass this change, and one paraphrase query would quietly stop working. The gate fails instead and names the query. A reviewer can then decide that trading q09 for q02 is acceptable and record that decision with --accept q09, which turns the same run into a pass. The exception lives in the pull request, where it can be reviewed, and not in someone's memory.
Figure 3. The gate has three exits. Only a reviewed exception turns a per-query regression into a pass.
The second run simulates an ingestion fault in which the last six entries never reached the index:
baseline rrf -> candidate rrf_stale recall@5 0.969 -> 0.828 diff -0.141 95% CI [-0.281, +0.000] mrr@10 0.828 -> 0.669 diff -0.159 95% CI [-0.291, -0.047] ndcg@10 0.850 -> 0.666 diff -0.184 95% CI [-0.297, -0.075] newly failing: q03 [identifier] first relevant 2 -> - (not_retrieved) newly failing: q18 [mixed] first relevant 1 -> - (not_retrieved) newly failing: q19 [mixed] first relevant 1 -> - (not_retrieved) newly failing: q21 [mixed] first relevant 1 -> - (not_retrieved) newly failing: q32 [plain] first relevant 1 -> - (not_retrieved) fixed: q02 [identifier] first relevant 6 -> 5 (ranked_low) FAIL: recall@5 fell 0.141 (allowed 0.000); ndcg@10 fell 0.184 (allowed 0.020); 5 query(ies) newly fail at k=5: q03, q18, q19, q21, q32 exit code 1
Three things in this output are worth more than the verdict. The stage label not_retrieved on every newly failing query points at the index, not at ranking. The confidence interval for the recall difference reaches zero even though five queries broke, which shows how little statistical power 32 queries have: a gate that waited for significance would have let this through. And q02 is reported as fixed, because removing documents shifted the correct entry up by one position. A broken index improved a query by accident, which is why "fixed" lines need the same scrutiny as failures.
The interval comes from a paired bootstrap over queries. Smucker, Allan and Carterette compared significance tests for retrieval evaluation and found that bootstrap, randomisation and t-tests largely agree, while the Wilcoxon and sign tests do not and should be avoided. On a small golden set the interval is context for a human reader. The per-query transitions are the gate.
What breaks the harness in production
Tolerances smaller than one query. With N queries, losing the only relevant document of one query moves recall by 1/N. On 32 queries that is 0.031, so a tolerance of 0.02 admits no such loss and a tolerance of 0.05 admits exactly one, without explanation. State tolerances in queries.
Tuning on the gate set. Every threshold chosen by looking at the golden set makes the set less able to detect overfitting. Keep a second set that is run less often and never used to choose parameters.
Label drift. The fingerprint catches edits to the corpus. It does not catch a document that is still present but no longer correct, or new documents that should now be relevant to old queries. Re-judging a sample on a schedule is part of the cost of ownership.
Baselines updated in the same change they judge. The baseline should be regenerated on merge to the main branch by CI, never edited by the author of the change under review.
Offline scores taken for user outcomes. A golden set measures the queries someone thought to include. Production monitoring of reformulations, zero-result searches and citations that users open covers the ones nobody did.
Libraries cover part of this ground. Ragas, for example, documents an ID-based context recall that compares retrieved ids with reference ids, which is the same computation as recall_at_k here, alongside an LLM-based variant that needs only a reference answer and estimates recall from the claims it contains. The second is convenient when no document-level labels exist, and it reintroduces model variance into a measurement that can otherwise be exact. Ragas was not installed or run for this article.
Testing and what was verified
The suite has 40 tests. Eleven cover the metrics against hand-computed values, including the nDCG normalisation bug, the error on a query without relevant documents, and the determinism of the bootstrap for a fixed seed. Four cover the golden set: the committed file must equal what the builder produces, editing one document must invalidate the fingerprint, and each structural problem must be named. Ten parametrised cases cover every triage branch. The remaining tests pin the fixture results quoted above and the behaviour of the gate, including its exit codes when run as a subprocess the way CI would run it.
Verification. All 40 tests pass on Python 3.13.18 with pytest 9.2.0 (November 2026), and run.sh additionally confirms that the gate exits 0 for the baseline and non-zero for the stale index. The retriever under test is the toy hybrid retriever from the previous article, so every number is a measurement on a 36-entry fixture and not a benchmark. No language model was called: the generation stage is a scripted stand-in, and nothing here measures answer quality or the behaviour of an LLM-based grader. The CI integration is the run.sh script; it was not executed on a hosted CI service.
Common mistakes
Measuring recall at a k the prompt never sees. Recall@20 describes the candidate list. The model sees the top three or five.
Reporting one mean. Three systems here share a recall of 0.969 and fail on different queries.
Counting unjudged documents as wrong without saying so. Report the judged share next to the metric.
Normalising nDCG by the retrieved documents. It rewards systems for retrieving little.
Letting the answer grader absorb retrieval failures. A correct answer without evidence in the context is a retrieval failure that has not hurt yet.
Treating a golden set as permanent. Without a version and a corpus fingerprint, it decays unnoticed, and evaluation that stops matching reality is a common root of failed AI projects.
Engineering verdict
Build the retrieval half of the evaluation before the answer half, whenever a system retrieves before it generates. It is cheap, deterministic and fast enough to run on every change, and it converts "the answers got worse" into a named stage and a list of queries.
It is not sufficient alone. Retrieval metrics cannot tell whether an answer is faithful, complete or well phrased, and they depend entirely on the quality of the labels. Use them to gate changes to chunking, indexing, fusion and ranking, and use answer-level evaluation, with a model or with people, for what remains after the evidence is known to be in the prompt.
For production, replace three things in this code: the 32-query fixture with a few hundred queries sampled from real traffic and stratified by class; the scripted reader with the output of whatever grader the team already trusts, passed into triage as it is; and the single golden set with a gate set and a held-out set. Keep the per-query diff. It is the part of the report that people act on.
References
- Cumulated Gain-Based Evaluation of IR Techniques — Järvelin and Kekäläinen, ACM Transactions on Information Systems 20(4), 2002
- Overview of TREC 2005 — Ellen M. Voorhees, NIST
- BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — Thakur et al.
- A Comparison of Statistical Significance Tests for Information Retrieval Evaluation — Smucker, Allan and Carterette, CIKM 2007
- Context Recall — Ragas documentation
Related Articles
AI & Machine Learning16 min read
Hybrid Search from First Principles: BM25, Vectors and Where Rank Fusion Buries an Exact Match
A dependency-free hybrid retriever in about 200 lines of Python: BM25 over an inverted index, a flat cosine index, and reciprocal rank fusion, measured on a labelled fixture. The numbers show where each arm is blind and where default RRF buries an exact match.
AI & Machine Learning14 min read
The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering
A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.
Enterprise Engineering4 min read
Distributed Tracing in 2024: Pitfalls Nobody Warns You About
Distributed tracing is essential for debugging large systems, but real-world adoption exposes subtle and costly pitfalls. This article covers operational anti-patterns and traps that undermine tracing at scale.