Choose metrics that match the product task, state the judgment set and treat unjudged results as unknown rather than wrong.
Retrieval metrics: read Recall, MRR and nDCG without hiding misses
Metrics answer different questions
Recall at K asks what fraction of all known relevant evidence appears in the first K results. It matters when a downstream reranker or answer generator needs enough candidates to work with. Reciprocal rank asks how early the first relevant item appears; mean reciprocal rank averages that value across queries. It is useful for a task where one good hit suffices, but it ignores a second missing support passage. Normalized discounted cumulative gain uses graded relevance and discounts lower ranks, so it can distinguish a direct answer from a merely related source. Answer evaluation remains separate: a good list does not prove a supported answer.
Define the judged universe and K
A recall denominator needs the known relevant set for each query. If judgments were pooled only from one old search system, a new system can retrieve an unjudged but valid document; scoring that as irrelevant creates bias. Record document or passage identity, corpus generation, permissions, as-of time and judgment policy. Label adjudication establishes those facts. Report the cutoff explicitly: Recall at 20 is not interchangeable with Recall at 5. A query with no relevant evidence needs a separate no-answer evaluation policy rather than a forced zero denominator.
MRR can reward the wrong release
Suppose the first result is somewhat relevant, while the only passage supporting a required number is missing. MRR can still be one because it cares only about the first relevant rank under a binary label. If a task requires multiple facts or independent sources, also report answer-span coverage, multi-hop completion or recall of required evidence units. Multi-hop retrieval makes that dependency explicit. Keep a miss ledger with query slices so an average improvement cannot hide a collapse on rare identifiers or filtered tenants.
nDCG depends on the grade definition
A graded label might use zero for unrelated, one for contextual, two for partially useful and three for a directly supporting passage. Discounted cumulative gain then rewards high grades near the top; dividing by the ideal possible gain makes scores comparable within the same judged query. But grade policies, gain formula and cutoff must stay fixed across releases. Unjudged results should be reviewed or reported as unknown, not silently mapped to grade zero. Copied evidence may require a separate diversity or lineage measure: nDCG does not automatically penalize repeating the same source.
Use release slices and uncertainty
Calculate query-level metrics first, then aggregate by intent, language, corpus age and permission slice. Keep the exact same queries and judgments for a paired comparison, and inspect differences rather than trusting a single global mean. Bootstrap intervals or paired randomization can help separate noise from a real improvement when enough independent queries exist. Do not repeatedly tune on a fixed held-out set until it becomes development data. Release gates should specify minimum recall and answer support for protected slices, while an online test monitors latency and user behavior separately.
Worked contract
from math import log2
def retrieval_scores(grades: dict[str, int],
ranked_ids: list[str], cutoff: int
) -> tuple[float, float, float] | None:
if cutoff < 1:
raise ValueError("invalid cutoff")
window = ranked_ids[:cutoff]
if len(set(window)) != len(window):
raise ValueError("repeated result in scored window")
if any(document_id not in grades for document_id in window):
raise ValueError("unjudged result in scored window")
if any(grade < 0 for grade in grades.values()):
raise ValueError("negative relevance grade")
relevant = {document_id for document_id, grade in grades.items()
if grade > 0}
if not relevant:
return None # evaluate no-answer behavior separately
recall = len(set(window) & relevant) / len(relevant)
first_rank = next((rank for rank, document_id in
enumerate(window, 1) if document_id in relevant), None)
reciprocal_rank = 1 / first_rank if first_rank else 0.0
def gain(values: list[int]) -> float:
return sum((2 ** grade - 1) / log2(rank + 1)
for rank, grade in enumerate(values, 1))
observed = gain([grades[document_id] for document_id in window])
ideal = gain(sorted(grades.values(), reverse=True)[:cutoff])
return recall, reciprocal_rank, observed / ideal if ideal else 0.0
grades = {"manual-47": 3, "manual-81": 1, "manual-94": 0}
recall, mrr, ndcg = retrieval_scores(
grades, ["manual-81", "manual-94", "manual-47"], 2)
assert recall == .5 and mrr == 1.0 and 0 < ndcg < 1Performance and operating cost
For J judged documents and K displayed results, this direct calculation uses O(J log J + K) time because it sorts all judged grades for ideal nDCG and checks the ranked window; its extra space is O(J + K). For many queries, cache each query's ideal gain under an immutable judgment set. Judgment collection and adjudication cost much more than arithmetic. The code rejects unjudged top-K results instead of falsely assigning them zero, but a real evaluation pipeline can queue those results for judging and report the unknown rate. The returned tuple is query-level; macro averages must account for no-answer queries explicitly.
Common Mistakes
- Reporting Recall at K without stating whether the known relevant set is complete.
- Calling MRR an evidence-coverage metric when only the first relevant hit affects it.
- Treating unjudged new results as irrelevant in an incomplete judgment pool.
- Comparing nDCG values across changed grade scales, corpus generations or cutoffs.
Validation drill
Score 91 judged questions at K equal to 5 and 20. Report recall, reciprocal rank and graded nDCG per slice, plus the count of unjudged top-K results. Audit ten queries where the metrics disagree and record whether the generated answer has enough support.
