Retrieval quality metrics
Two metrics answer different questions
A RAG retriever should find the evidence required by a question, not merely a passage with similar words. Define binary relevance judgments against a fixed authorized corpus revision before calculating metrics. Recall@k is the number of distinct relevant IDs among the first k results divided by the total number of judged relevant IDs. Reciprocal rank at k (RR@k) is the inverse of the position of the first relevant ID in those k results, or zero when none appears. Mean reciprocal rank (MRR@k) averages RR@k across queries. For relevant IDs A and C and ranking B,A,D at k=3, recall is 1/2 and RR is 1/2. If a second query has RR=1, MRR is (0.5+1)/2=0.75. Here queries with no judged relevant items return None for both metrics and are evaluated separately for correct abstention; other evaluation protocols can count such queries differently. Report the convention and cutoff. Reject duplicated ranked IDs instead of rewarding them. The program returns (0.5, 0.5), then (0.5, 1.0), then (None, None).
def metrics(relevant, ranked, k): # Unique ranked IDs; binary relevance judgments for one snapshot. if type(k) is not int or k < 1 or len(ranked) != len(set(ranked)): raise ValueError("positive k and unique ranked IDs required") relevant = set(relevant) if not relevant: return None, None top = ranked[:k] recall = len(relevant.intersection(top)) / len(relevant) rr = next((1 / rank for rank, key in enumerate(top, 1) if key in relevant), 0.0) return recall, rr
print(metrics({"A", "C"}, ["B", "A", "D"], 3))print(metrics({"A", "C"}, ["C", "A"], 1))print(metrics(set(), ["B"], 3))Build a fair evaluation set
Label relevance independently of which retriever found an item. Use versioned, permission-scoped IDs and include paraphrases, exact identifiers, multi-part questions, irrelevant near matches, conflicts and unanswerable cases. An incomplete judgment pool can make a novel relevant hit look like a false positive; record how labels were collected and sample unjudged hits for review. Keep a development split for tuning and a held-out split for reporting. Compare the same snapshot, cutoff, candidate budget and query set. Record candidate recall before reranking and context recall after token-budget truncation. For multi-part questions, high recall or a first relevant hit does not establish that all required facts were found. Report answer coverage and citation support separately, using human-reviewed claim-level judgments.
Hybrid retrieval and reciprocal rank fusion
Lexical search is useful for product codes, exact names and literal terms; dense retrieval uses learned representations and can recover paraphrases. Hybrid retrieval combines candidates from both. Do not simply add raw cosine and BM25 scores: their scales and distributions differ. Reciprocal rank fusion (RRF) gives each candidate a contribution 1/(c+rank) from each list in which it appears, then sorts by the sum. This is not the same as reciprocal rank evaluation: RRF has no relevance judgments and combines rankings, whereas RR measures the first relevant hit. Here c is a positive integer (60 by default, not the result cutoff). Missing candidates contribute zero. Exact rational arithmetic is used only for a tiny teaching example and ensures deterministic tie handling by ID. B appears in both lists and ranks first; A precedes C. In the equal-score case A wins the ID tie. All source rankings must be scoped before retrieval; fusion cannot grant access.
from fractions import Fraction
def fuse(rankings, c=60): # Each input is an eligible, deduplicated ranked list of string IDs. if type(c) is not int or c < 1: raise ValueError("positive rank constant required") scores = {} for ranked in rankings: if len(ranked) != len(set(ranked)): raise ValueError("duplicate within a ranking") for rank, key in enumerate(ranked, 1): scores[key] = scores.get(key, 0) + Fraction(1, c + rank) return sorted(scores, key=lambda key: (-scores[key], key))
print(fuse([["A", "B"], ["B", "C"]]))print(fuse([["B"], ["A"]]))Rerank and transform queries carefully
A reranker scores a bounded set of retrieved query-passage pairs, for example with a cross-encoder that reads both strings together. It can reorder candidates but cannot recover an absent relevant ID. Larger pools may improve recall but increase latency and computation. Query transformation can expand an abbreviation, rewrite conversational context into a standalone question, or generate a translated variant. Preserve the original query and constraints (such as a product code, negation, dates and tenant). Never let a generated rewrite alter authorization or become trusted evidence. Compare original-only and expanded queries with fixed candidate budgets; deduplicate by revision ID. Test chunk sizes and overlap using the same corpus and ground-truth evidence spans: small chunks may lose conditions, large chunks may waste context, and overlapping chunks may inflate ID-level recall. Track document- or fact-level coverage as a complementary measure.
Practice: diagnose a ranking regression
Using A,C as relevant IDs, evaluate B,A,D at k=1,2,3 and 4. At k=1 recall and RR are zero; at k=2,3,4 both equal 0.5. Fuse lexical A,B and dense B,C with c=1 and c=60; B remains first. Imagine a reranker places C,A,B: RR@1 becomes 1 and recall@2 becomes 1. Report these metrics as separate numbers, not a single quality score. If the correct answer needs both A and C, the first hit alone is insufficient. Run the staged exercise and see the next lesson for language slices and evidence security.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Retrieval quality metrics quiz
Apply retrieval evaluation and evidence controls.
Relevant IDs A,C; ranking B,A,D at k=3. Recall@3?
What is RR@3 for the same ranking?
RR values are 0, 0.5 and 1. What is MRR?
Why use rank fusion instead of adding raw BM25 and cosine scores?
A relevant ID is absent from every candidate list. What can a reranker do?