06.10 Evaluating and Tuning Retrieval
Lesson 06.9 closed the retrieval stack: embed, index, filter, fuse, rerank. This lesson answers the question that decides whether any of it works: how do you know your retriever is good, and how do you make it better? You will build a labelled evaluation set, implement every retrieval metric that matters (hit rate, recall, precision, MRR, MAP, nDCG, R-precision, needed-set recall), wrap them in a runnable harness that compares retriever configurations with bootstrap confidence intervals, run a failure analysis, tune the whole pipeline one change at a time, and try the query-side techniques — rewriting, multi-query, HyDE, step-back, expansion, conversation-aware queries — each measured on your own data rather than trusted from a blog post. It is the last lesson of Module 06 and the bridge into Module 07: at the end you will have a retriever contract (search(query, k, filters) -> list[Hit]) that RAG builds directly on top of.
What you'll learn
- What "good retrieval" means concretely, and the three levels of evaluation: component, pipeline and end-to-end — and why retrieval gets its own eval loop
- How to build an evaluation set: queries plus qrels (which chunks are relevant), where queries come from, how many you need, stratification, graded vs binary relevance, labeller agreement, versioning, and the train/dev/test discipline that stops you fooling yourself
- The fix for the re-chunking problem: label answer spans in the source document, not chunk IDs, so your labels survive every re-chunk
- Every retrieval metric with intuition, formula and code: hit rate/success@k, recall@k, precision@k, MRR, MAP, nDCG@k, R-precision, needed-set recall for multi-chunk answers, RAGAS-style context precision/recall, and latency and cost as first-class metrics
- A complete evaluation harness: a
Retrieverprotocol, a runner, per-query and aggregate metrics, run records with provenance, paired comparison with a bootstrap confidence interval, and a failure browser - How to run failure analysis like a professional: a miss taxonomy, a triage table mapping each failure to its fix, and the "read 20 failures" workflow
- The tuning loop: change one thing at a time, in the order of typical payoff, with a sweep script, dev/test discipline and cost-aware experiments
- Query-side techniques taught at the retrieval level — rewriting, multi-query, HyDE, step-back and decomposition, acronym/synonym expansion, conversation-aware queries, and query routing — each with a prompt, code, an eval recipe, and an honest statement of the mixed evidence
- Online evaluation signals (clicks, zero-result rate, A/B tests, drift, canary queries) at awareness level — Modules 10A and 11A go deep
- How to use public benchmarks (BEIR, MTEB, MS MARCO, MIRACL) for model selection without pretending they replace your own eval set
- The module wrap-up: a one-page retrieval-quality checklist and the retriever contract you hand to Module 07
What you don't need
- API keys or running services. Every runnable sample is pure Python standard library plus NumPy on a tiny hand-built corpus with deterministic toy vectors. The LLM calls in Part 7 use an injectable function with a deterministic fake; swap in a real provider call and the plumbing is unchanged.
- Deep vector-index internals — 06.4 owns HNSW/IVF/quantization tuning; here index parameters appear only as sweep dimensions.
- RAG pipeline design — query understanding for answering, grounding prompts, citations and RAG evaluation belong to Module 07 and Module 10A (RAG evaluation starts at 07.9 and is covered in full in 10A.6). This lesson evaluates retrieval; it stops where answer generation begins.
- LLM-judge evaluation — Module 10A owns judges, rubrics and LLM-as-metric. Retrieval metrics here are deterministic and need no judge, which is exactly why we evaluate retrieval separately.
Setup
The runnable code needs Python 3.11+ and NumPy (everything except one vectorised-search demo in 4.1 is standard library; NumPy is what you'd reach for at real scale anyway):
uv init retrieval-eval --bare --python 3.13 && cd retrieval-eval
uv add numpy # or: pip install numpyThe command installs the newest release of numpy; the samples were checked against 2.5.4 as of November 2026, so check NumPy's changelog if a number differs. First time with uv? See lesson 03.1, Part 4.
Copy these files from this lesson into your project folder — each is printed in full where it appears: corpus.py (the running corpus + toy vectors), metrics.py (all metrics), retrievers.py (the Retriever protocol + three toy retrievers), eval_queries.jsonl (the labelled set), harness.py (runner, provenance, comparison, failure browser), spans.py (the re-chunking fix), judge.py (the LLM-assisted labelling sketch in 2.9), worked_example.py (the numbers in 3.1), sweep.py (6.3), query_techniques.py (Part 7 demos) and demo.py (the end-to-end run). Then uv run python demo.py; each of the other scripts runs on its own the same way (uv run python spans.py, and so on) once corpus.py, metrics.py, retrievers.py, harness.py and eval_queries.jsonl sit beside it.
What you must be able to do after this lesson#
- Define what good retrieval means for your use case
- Build a labelled evaluation set
- Compute recall, MRR and nDCG and read them
- Run an evaluation harness over a retriever
- Diagnose failures and tune one change at a time
- Monitor retrieval quality after launch
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The search feels bad — where do we even start?" | Part 5: Failure analysis |
| "Is recall@10 or nDCG the number that matters?" | 3.10 Which metric answers which question |
| "Our eval set has 40 queries — is that enough?" | 2.3 How many queries are enough |
| "We changed the chunk size and all our labels broke." | 2.7 The re-chunking problem |
| "The hybrid retriever scored 2 points higher — is that real?" | 4.5 Comparing two runs |
| "Should we add HyDE / multi-query / a reranker?" | Part 7 and the tuning loop |
| "BEIR says model X is best — should we switch?" | Part 10: Public benchmarks |
| "How do we catch search regressions in CI?" | 4.3–4.6 and 8.5 |
| "What exactly does Module 07 need from us?" | 11.2 The retriever contract |
Part 1: What "good retrieval" means#
1.1 The retrieval contract#
Strip away the machinery and retrieval is one function:
search(query, k, filters) -> ranked list of chunks"Good" decomposes into three testable claims:
- Coverage — the chunk(s) that actually answer the question appear in the results at all (recall).
- Position — they appear high enough that they fit the context budget you can afford to send the LLM (rank-sensitive metrics: MRR, nDCG).
- Purity — the list isn't padded with junk that wastes context tokens and confuses the generator (precision).
A retriever can be great on one axis and poor on another. A system that returns the right chunk at rank 40 has perfect recall@50 and useless precision@5. A system that returns one perfect chunk and nine near-duplicates has great top-1 metrics and terrible diversity. Which axis matters depends on what consumes the results — which is why the metrics in Part 3 are paired with "which question does this answer".
1.2 The three levels of evaluation#
flowchart TB
subgraph lvl1 ["Level 1 — component: the retriever alone"]
Q1["query"] --> R1["retriever<br/>dense / BM25 / hybrid / reranked"]
R1 --> M1["ranked chunk ids"]
M1 --> E1["vs qrels:<br/>recall@k, MRR, nDCG"]
end
subgraph lvl2 ["Level 2 — pipeline: retriever + reranker (+ filters)"]
Q2["query"] --> R2["stage-1 candidates → fusion → reranker"]
R2 --> M2["final top-k"]
M2 --> E2["same metrics, reranked list:<br/>did stage 2 help or hurt?"]
end
subgraph lvl3 ["Level 3 — end-to-end: answer quality"]
Q3["query"] --> R3["retriever → LLM → answer + citations"]
R3 --> E3["answer correctness, faithfulness,<br/>citation accuracy — Module 10A"]
end
E1 -.->|"cheap, deterministic,<br/>no LLM judge"| NOTE["run this loop constantly"]
E2 -.-> NOTE
E3 -.->|"expensive, needs judge or humans"| NOTE2["run on samples + milestones"]Each level answers a different question:
| Level | Question it answers | Cost per eval | Needs an LLM judge? |
|---|---|---|---|
| Component | "Did the right chunk get retrieved, and how high?" | milliseconds per query | No — deterministic metrics on ids |
| Pipeline | "Does the reranker/fusion stage improve the final ranking?" | seconds per query | No — same metrics on the final list |
| End-to-end | "Did the user get a correct, grounded answer?" | seconds–minutes per query | Usually yes (or human review) |
1.3 Why retrieval is evaluated separately#
Three practical reasons, and they matter for your workflow:
- It's cheap and fast. Retrieval metrics need no model calls — just ids and grades. You can run hundreds of queries in milliseconds and re-run after every change. End-to-end evals cost money and take minutes; you can't afford them on every commit.
- It's deterministic. Same retriever + same eval set → same numbers, every time. LLM-judge scores wobble; retrieval scores don't. You can put a hard threshold in CI ("recall@5 must not drop below 0.80") without flakiness.
- It isolates blame. When an answer is wrong, is the retriever at fault (chunk never retrieved) or the generator (chunk retrieved but misused)? Evaluating retrieval separately tells you which half to fix. Module 10A's RAG evals measure the whole pipeline; they can't tell you where it broke.
1.4 What the numbers can't tell you#
Before the metrics, calibrate expectations:
- Your eval set is a sample. Sixteen queries (our demo set) can detect gross regressions, not 2-point differences. 2.3 covers how many you need and why confidence intervals matter.
- Labels encode judgement. Two reasonable people disagree on borderline chunks — that's what labeller agreement (2.6) measures.
- Metrics measure the set, not the user. A retriever tuned to your eval queries can overfit them; the dev/test split (2.8) is the defence.
- "Relevant" is defined by your downstream use. A chunk that's irrelevant for a QA bot may be perfect for a search UI. Define relevance against the task (Part 9).
Part 2: Building an evaluation set#
2.1 The two artefacts: queries and qrels#
An evaluation set is two things:
- Queries — the questions users actually ask (or realistic stand-ins).
- Qrels (query relevance judgments) — for each query, which corpus items are relevant, and how much.
The corpus is whatever your retriever searches — for us, the Module 05 running corpus (handbook, help centre, tickets, contracts) in its chunked form. Qrels reference chunk IDs, because that's what retrieval returns.
{"qid": "q05", "query": "why was I charged twice for VPN seats in October?",
"split": "dev", "type": "diagnostic",
"relevant": {"ticket-78": 2, "ticket-77": 1},
"needed": ["ticket-78"],
"notes": "ticket-77 is the customer's question, useful context"}relevant maps chunk ID → grade: 2 = directly answers the query, 1 = useful context or partial. needed is the minimal set that actually answers — for multi-chunk questions it can hold several ids. 3.7 explains why the distinction matters.
2.2 Where queries come from#
The best eval queries come from real usage; the rest are constructed. In rough order of value:
| Source | What it gives you | Caveats |
|---|---|---|
| Production query logs | Real phrasing, real frequency, real failure modes | Privacy (hash or aggregate; 8.2); logs only exist after launch — cold-start problem |
| Support tickets / help-desk exports | The questions your corpus was built to answer | Ticket text ≠ search query; rewrite into question form |
| Domain experts / the team | Hard cases, edge cases, "the question that always breaks" | Small numbers; watch for blind spots — they know the corpus too well |
| Synthetic questions (10A.2) | Scale: hundreds of questions per corpus quickly | Lexical leakage: generated questions often copy the chunk's words, so BM25 looks artificially good and paraphrase robustness is never tested. Mitigate with paraphrase prompts and by filtering (below) |
| Adversarial / hard queries | The cases that discriminate retrievers: acronyms, typos, error codes, multi-hop, negations, "no answer" queries, very short and very long inputs | Must be labelled by hand — they're exactly where labels are hardest |
Our demo set (eval_queries.jsonl) mixes all five sources in miniature: paraphrased factoids, an error code, a multi-hop question, a no-answer query, an ambiguous one, a Spanish query, and a permission-filtered one.
2.3 How many queries are enough#
The honest answer: it depends on the difference you want to detect, and you can estimate it.
- 30–100 queries is the standard starting point for a dev set. Enough to rank configurations coarsely, catch gross regressions, and compute stable-ish means.
- The uncertainty is roughly
1/√n: with 30 queries, a metric's standard error is on the order of ±0.05–0.10 depending on variance; with 100, about half that. You cannot reliably detect a 2-point improvement on 30 queries — the bootstrap CI will usually include zero, and it should. - Rule of thumb: size the set so the smallest improvement worth shipping produces a confidence interval that excludes zero. If you care about 5-point recall gains, a standard power calculation for a paired comparison gives
n ≈ ((z_α + z_β)·σ/δ)², where σ is the standard deviation of the per-query difference between the two systems, δ the gain you want to detect,z_α ≈ 1.96(95% confidence) andz_β ≈ 0.84(80% power). For σ≈0.3 and δ=0.05 that is(2.8 × 0.3 / 0.05)² ≈ 280queries; for 15-point gains (dense vs nothing) it is about 31, so 30–40 suffice. Estimate σ from a pilot run (thestdof your per-query paired differences) rather than guessing. - Stratify, then size per stratum. If 20% of real queries are error codes, ~20% of your set should be too — otherwise your average is dominated by easy factoids. Our 16-query demo is deliberately tiny for teaching; a production set is 10–50× larger.
2.4 Stratification by query type#
Tag every query with a type and report metrics per type, not just overall. Our types: factoid, howto, error-code, diagnostic, keyword, multi-hop, multi-field, no-answer, ambiguous, multilingual, filtered-empty. The per-type breakdown is where tuning decisions come from — "hybrid helps error-code queries by +0.4 recall but hurts nothing elsewhere" is actionable; "hybrid is +0.02 overall" is not.
2.5 Graded vs binary relevance#
- Binary (relevant / not): simpler to label, matches recall/precision/MRR. Most of our metrics use it.
- Graded (0/1/2 or 0–3): captures "this chunk is useful context but doesn't answer" vs "this chunk IS the answer". Required for nDCG and for the
neededset. Costs more labelling effort and more disagreement.
Practical compromise (what we do): grade 2 = answers, 1 = useful context, absent = irrelevant. Binary metrics treat grade ≥1 as relevant; nDCG uses the full grades; needed holds only grade-2 ids.
2.6 Labelling guidelines and labeller agreement#
Write the guidelines down before anyone labels — they matter more than the labels:
- Judge against the query, not the chunk. "Would a user who asked this be satisfied if this chunk (and only this chunk) were shown?"
- Grade 2 requires the answer, not just the topic. A chunk about vacation policy that doesn't state the accrual rate is grade 1 at best.
- Mark every plausible chunk, not just the best one. If two chunks both answer, both get grade 2 — otherwise you'll penalise retrievers for finding the second correct answer.
- When unsure, grade 1 and note it. Borderline calls are data about your guidelines, not noise.
- Label blind to retriever output. Never look at what a retriever returns before grading — you'll anchor on it.
For agreement, have a second person label a sample (20–30% is plenty) and compute Cohen's kappa — agreement beyond chance:
# needs metrics.py, which is printed in full in 3.1
from metrics import cohen_kappa
# two labellers grade the same 8 query-chunk pairs: 1 = relevant, 0 = not
labels_a = [1, 1, 1, 1, 0, 0, 0, 0] # labeller A
labels_b = [1, 1, 1, 0, 1, 0, 0, 0] # labeller B (disagrees on pairs 4 and 5)
k = cohen_kappa(labels_a, labels_b)
print(f"kappa = {k}")kappa = 0.5(kappa = 0.5 on our toy two-labeller example — "moderate" agreement; real sets aim for >0.6, ideally >0.8. Landis & Koch's bands: <0.2 poor, 0.2–0.4 fair, 0.4–0.6 moderate, 0.6–0.8 substantial, >0.8 almost perfect.) Disagreements aren't failures — they're the signal that your guidelines need sharpening.
2.7 The re-chunking problem: label spans, not chunk IDs#
Here is the trap that silently destroys eval sets: your qrels reference chunk IDs, and chunk IDs change every time you re-chunk. Change the chunk size from 400 to 500 tokens? Every label is orphaned. The fix: label where the answer lives in the source document — character offsets — and derive chunk-level qrels at eval time.
# spans.py — the re-chunking problem: label ANSWER SPANS, not chunk IDs.
#
# If your qrels store chunk IDs, changing the chunker invalidates every label.
# The robust fix: label WHERE IN THE SOURCE DOCUMENT the answer lives
# (char offsets), then map spans -> whatever chunks exist at eval time.
#
# Pure stdlib, deterministic, real output.
from __future__ import annotations
import hashlib
import json
# --- a mini source document, split into chunks by char offsets ----------------
SOURCE = """\
Handbook — Leave policy
Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.
Sick leave is separate from vacation: 10 days per year, no accrual cap.
Parental leave: 16 weeks for the primary caregiver and 6 weeks for the secondary caregiver, usable within the first year.
"""
# chunks are (chunk_id, start, end) char offsets into SOURCE
CHUNK_SPANS = [
("handbook-001", SOURCE.index("Full-time"),
SOURCE.index("Sick leave")),
("handbook-002", SOURCE.index("Sick leave"),
SOURCE.index("Parental leave")),
("handbook-005", SOURCE.index("Parental leave"), len(SOURCE)),
]
def span_to_chunks(spans: list[tuple[int, int]],
chunk_spans: list[tuple[str, int, int]]) -> set[str]:
"""Map answer-bearing char spans to the chunks that overlap them.
A span that crosses a chunk boundary marks BOTH chunks relevant — which is
correct: either one alone may not contain the full answer.
"""
out = set()
for s, e in spans:
for cid, cs, ce in chunk_spans:
if s < ce and e > cs: # half-open interval overlap
out.add(cid)
return out
def chunk_id_for_offsets(doc_id: str, start: int, end: int,
strategy_version: str) -> str:
"""Deterministic chunk ID from content position + chunker version
(the 05.6/05.8 convention). Stable across re-runs, changes on re-chunk."""
blob = f"{doc_id}|{start}|{end}|{strategy_version}"
return f"{doc_id}-{hashlib.sha256(blob.encode()).hexdigest()[:10]}"
def rechunk(source: str, size: int) -> list[tuple[str, int, int]]:
"""A DIFFERENT chunking of the same source: fixed-size windows.
Same content, different boundaries -> different chunk IDs."""
out = []
i = 0
n = 0
while i < len(source):
out.append((f"handbook-r{n}", i, min(i + size, len(source))))
i += size
n += 1
return out
if __name__ == "__main__":
# The labelled answer spans, recorded ONCE against the source document.
# q01's answer is the vacation sentence; q06's answer spans renewal AND
# payment terms (two spans, two chunks).
ANSWER_SPANS = {
"q01": [(SOURCE.index("accrue"), SOURCE.index("per year.") + len("per year."))],
"q11": [(SOURCE.index("Parental leave"), len(SOURCE))],
}
print("== labels are spans, stable across chunkings ==")
for qid, spans in ANSWER_SPANS.items():
for label, spanset in [
("structure-aware chunks", CHUNK_SPANS),
("fixed-400-char chunks", rechunk(SOURCE, 400)),
]:
ids = sorted(span_to_chunks(spans, spanset))
print(f" {qid} [{label:26s}] -> {ids}")
print()
print("== what breaks if you store chunk IDs instead ==")
# naive approach: label = chunk id under chunking A
naive_qrels = span_to_chunks(ANSWER_SPANS["q01"], CHUNK_SPANS)
print(f" labelled under structure-aware: {sorted(naive_qrels)}")
# re-chunk, regenerate ids, look up the SAME answer span -> different ids
new_chunks = rechunk(SOURCE, 400)
new_ids = {cid for cid, _, _ in new_chunks}
print(f" after re-chunking, those ids exist? "
f"{sorted(naive_qrels & new_ids) or 'NONE — every label is orphaned'}")
print(f" correct re-derived qrels: {sorted(span_to_chunks(ANSWER_SPANS['q01'], new_chunks))}")Real output (pure Python, deterministic):
== labels are spans, stable across chunkings ==
q01 [structure-aware chunks ] -> ['handbook-001']
q01 [fixed-400-char chunks ] -> ['handbook-r0']
q11 [structure-aware chunks ] -> ['handbook-005']
q11 [fixed-400-char chunks ] -> ['handbook-r0']
== what breaks if you store chunk IDs instead ==
labelled under structure-aware: ['handbook-001']
after re-chunking, those ids exist? NONE — every label is orphaned
correct re-derived qrels: ['handbook-r0']The workflow: during labelling, record {"qid", "doc_id", "span": [start, end], "grade"}. At eval time, load the current chunk manifest (05.8 stores char offsets per chunk) and run span_to_chunks. Re-chunking becomes a non-event for your labels — the same spans just map to different chunk IDs. This is also how you handle multi-chunk answers: label each answer span separately; the union of overlapped chunks is the qrel set, and needed marks the minimal covering subset.
2.8 Versioning the set and the dev/test split#
- Version the eval set like code:
evalset-v3, with a changelog ("added 12 multilingual queries", "re-graded q14 after guideline change"). Theevalset_shayour harness writes into every run record fingerprints the exact qrels used — two runs are only comparable if the hash matches. - Split dev/test before you tune.
devis what you iterate against (the sweep in Part 6);testis touched once at the end to verify the winner generalises. Tuning on the test set is the cardinal sin of retrieval eval — you'll ship a retriever that's 3 points better on your queries and worse on real ones. - Keep a
train-like reserve for anything learned. If you ever train fusion weights or learn a threshold, those queries must not appear in dev or test. - Refresh from production. The offline set decays as the corpus and query mix change; 8.5 closes the loop.
2.9 Scaling labels with an LLM judge (carefully)#
Hand-labelling every (query, chunk) pair does not scale: a 300-query set with a 20-chunk pool per query is 6,000 judgements. Since 2024 the standard way to stretch human effort in IR evaluation is an LLM relevance assessor: a model grades (query, passage) pairs against the same rubric your humans use. The best-known open reproduction is UMBRELA (Upadhyay, Pradeep, Thakur, Craswell and Lin, arXiv 2406.06519, code at github.com/castorini/umbrela), which reimplements the Bing team's LLM-assessor approach, validated against TREC Deep Learning 2019–2023 judgements; its authors state it was to be used to aid relevance assessment in the TREC 2024 RAG track. Where it earns its keep:
- Closing holes. After you add a new retriever, grade the unjudged chunks it returns (the pooling step of 3.11) instead of leaving them silently "irrelevant".
- Cold start. Triage synthetic queries (the leakage check in 2.2) and pre-label candidates for a human to confirm, rather than label from scratch.
- Regression sets. Grade every run of a large set cheaply, with humans auditing a sample.
It is not a replacement for human labels, and the trap is trusting it without measuring. The procedure:
- Write the rubric once (2.6) and give the judge the same grade definitions your humans use.
- Have humans grade a stratified sample (50–100 pairs, every query type) and compute agreement between the LLM and the humans with the
cohen_kappafunction frommetrics.py— at the graded level and at the binary "relevant at all" level. Agreement is usually higher on the binary question than on "answers" vs "useful context". - Read the disagreements. They tell you whether the rubric, the prompt or the model is the problem.
- Freeze the judge model, its version and the prompt text, and write them into the run record next to
evalset_sha(4.4) — a silent judge-model update changes your labels. - Keep humans for the
neededset and for borderline grades; keep auditing a sample on every refresh.
# judge.py — LLM-assisted relevance grading with an injectable `complete` function.
# Pure stdlib; the fake below stands in for a real model call (see lesson 03.11).
from __future__ import annotations
import json
import re
from typing import Callable
from metrics import cohen_kappa
JUDGE_PROMPT = """You are grading search results. Judge ONLY whether the PASSAGE helps
answer the QUERY. Grades: 2 = states the answer; 1 = useful context but does not
state the answer; 0 = irrelevant. Reply with JSON only: {{"grade": <0|1|2>}}
QUERY: {query}
PASSAGE: {passage}
"""
def llm_grade(complete: Callable[[str], str], query: str, passage: str) -> int | None:
"""Grade one (query, passage) pair; None when the reply cannot be parsed.
Unparseable replies are NOT silently graded 0: a missing label and an
'irrelevant' label are different things (count the Nones and look at them).
"""
reply = complete(JUDGE_PROMPT.format(query=query, passage=passage))
m = re.search(r"\{.*?\}", reply, flags=re.S)
if not m:
return None
try:
grade = int(json.loads(m.group(0))["grade"])
except (ValueError, KeyError, TypeError):
return None
return grade if grade in (0, 1, 2) else None
def fake_complete(prompt: str) -> str:
"""Deterministic stand-in: grade 2 if the passage shares 2+ content words
with the query, 1 if it shares one, else 0. Proves the plumbing only."""
q = re.search(r"QUERY: (.*)", prompt).group(1).lower()
p = re.search(r"PASSAGE: (.*)", prompt).group(1).lower()
stop = {"the", "a", "do", "i", "how", "much", "is", "what", "per"}
shared = (set(re.findall(r"[a-z0-9]+", q)) - stop) & set(re.findall(r"[a-z0-9]+", p))
return json.dumps({"grade": 2 if len(shared) >= 2 else 1 if shared else 0})
if __name__ == "__main__":
query = "how much vacation do I get"
pairs = [
("Full-time employees accrue 1.5 days of paid vacation per month.", 2),
("Sick leave is separate from vacation: 10 days per year.", 1),
("Domestic travel per diem is $75 per day.", 0),
("Parental leave: 16 weeks, usable within the first year.", 0),
("Contractors have no paid vacation entitlement.", 1),
("Expense reports are reviewed within 5 business days.", 0),
]
human = [h for _, h in pairs]
llm = [llm_grade(fake_complete, query, p) for p, _ in pairs]
print("human grades:", human)
print("llm grades: ", llm)
# agreement on the BINARY question 'is it relevant at all (grade >= 1)?'
bh = [1 if h >= 1 else 0 for h in human]
bl = [1 if (g or 0) >= 1 else 0 for g in llm]
print("exact grade agreement:", sum(a == b for a, b in zip(human, llm)), "/", len(pairs))
print("binary kappa:", round(cohen_kappa(bh, bl), 3))
print("unparseable replies:", sum(g is None for g in llm))
print("bad reply ->", llm_grade(lambda _: "Sure! I think it's quite relevant.", query, "x"))Real output (pure Python, deterministic — the fake judge is a keyword counter, so the numbers prove the plumbing, not the judgement):
human grades: [2, 1, 0, 0, 1, 0]
llm grades: [1, 1, 0, 0, 1, 0]
exact grade agreement: 5 / 6
binary kappa: 1.0
unparseable replies: 0
bad reply -> NoneNotice the two layers: the fake judge disagrees with the human on one pair (it grades "accrue 1.5 days of paid vacation" as context instead of answer, because it shares only one word with the query), yet the binary agreement is perfect. A real judge shows the same pattern at larger scale, which is why you report both. Notice also that an unparseable reply returns None, never 0 — a missing label and an "irrelevant" label must stay distinguishable.
Part 3: The metrics#
3.1 One worked example for all of them#
Every metric below runs on the same tiny case, so you can see exactly what each one measures. The retriever returned this ranking for a query with four relevant documents — grades {c1: 2, c2: 1, c3: 2, c4: 1}. Since every grade is ≥1, the binary relevant set is all four ids (the convention from 2.5: grade ≥1 counts as relevant):
ranking: ['c1', 'c4', 'c3', 'c2', 'c5', 'c7', 'c6']
relevant (binary): {c1, c2, c3, c4} # = every id with grade >= 1
grades: {c1: 2, c2: 1, c3: 2, c4: 1}metrics.py implements all of them in pure Python:
# metrics.py — retrieval metrics, pure Python (stdlib only).
#
# Every function takes a *ranking* (list of chunk ids, best first) and the
# *relevant* items for one query, and returns a float in [0, 1] (except MRR
# per query and latency helpers, noted inline).
#
# Conventions used throughout:
# * ranks are 1-based when we talk about them ("rank 3"), 0-based in lists
# * `relevant` is a set of ids for binary metrics, a dict id->grade for graded
# * an id missing from the ranking counts as "not retrieved"
from __future__ import annotations
import math
from statistics import mean
# ---------------------------------------------------------------------------
# binary-relevance metrics
# ---------------------------------------------------------------------------
def _topk(ranked: list[str], k: int) -> list[str]:
return ranked[:k] if k is not None else ranked
def hit_at_k(ranked: list[str], relevant: set[str], k: int) -> float:
"""1.0 if ANY relevant item appears in the top-k, else 0.0.
Also called success@k or recall@k when |relevant| == 1. It answers:
'did the user get *something* useful within the first k results?'
"""
return 1.0 if relevant & set(_topk(ranked, k)) else 0.0
def recall_at_k(ranked: list[str], relevant: set[str], k: int) -> float:
"""Fraction of ALL relevant items found in the top-k.
With several relevant chunks this is the metric that matters for RAG:
the LLM can only use what retrieval returned.
"""
if not relevant:
# convention: undefined for empty relevant sets — the harness excludes
# such queries (expected_empty) before calling this, so 0.0 is just a
# safe fallback, never a scored value.
return 0.0
return len(relevant & set(_topk(ranked, k))) / len(relevant)
def precision_at_k(ranked: list[str], relevant: set[str], k: int) -> float:
"""Fraction of the top-k that is relevant. Answers 'how noisy is the list?'"""
top = _topk(ranked, k)
if not top:
return 0.0
return len(relevant & set(top)) / len(top)
def mrr(ranked: list[str], relevant: set[str]) -> float:
"""Mean reciprocal rank component for ONE query: 1/rank of first relevant.
Ignores k — look at the full ranking. 'How high up is the first good hit?'
"""
rel = set(relevant)
for i, cid in enumerate(ranked, start=1):
if cid in rel:
return 1.0 / i
return 0.0
def _average_precision(ranked: list[str], relevant: set[str]) -> float:
"""AP for one query: mean of precision@i over positions i holding a relevant item."""
rel = set(relevant)
hits = 0
total = 0.0
for i, cid in enumerate(ranked, start=1):
if cid in rel:
hits += 1
total += hits / i
return total / len(rel) if rel else 0.0
def map_score(pairs: list[tuple[list[str], set[str]]]) -> float:
"""Mean average precision over queries: the standard 'how good is the ranking'
metric when result order matters."""
return mean(_average_precision(r, rel) for r, rel in pairs) if pairs else 0.0
def r_precision(ranked: list[str], relevant: set[str]) -> float:
"""Precision at rank R, where R = number of relevant items.
'If I showed exactly as many results as there are relevant documents,
how many would be relevant?' Elegant because it needs no k.
"""
R = len(relevant)
if R == 0:
return 0.0
return len(relevant & set(ranked[:R])) / R
def needed_set_recall(ranked: list[str], needed: set[str], k: int) -> float:
"""Fraction of the *minimal* answer-bearing set found in top-k.
Distinct from recall@k: `relevant` may contain helpful context chunks,
`needed` contains only the chunks required to actually answer. For
multi-chunk answers (a question needing two clauses) this is the metric
that catches 'found one of the two pieces'.
"""
if not needed:
return 0.0
return len(needed & set(_topk(ranked, k))) / len(needed)
# ---------------------------------------------------------------------------
# graded relevance: nDCG
# ---------------------------------------------------------------------------
def _gain(grade: float) -> float:
"""Gain for a relevance grade: exponential so grade 2 is worth much more
than two grade-1s (the standard nDCG convention)."""
return (2.0 ** grade) - 1.0
def dcg_at_k(ranked: list[str], grades: dict[str, float], k: int) -> float:
"""Discounted cumulative gain: sum over ranks of gain / log2(rank + 1)."""
total = 0.0
for i, cid in enumerate(_topk(ranked, k), start=1):
g = _gain(grades.get(cid, 0.0))
if g:
total += g / math.log2(i + 1)
return total
def ndcg_at_k(ranked: list[str], grades: dict[str, float], k: int) -> float:
"""DCG@k normalised by the ideal DCG@k (best possible ordering)."""
ideal = sorted(grades.values(), reverse=True)[:k]
idcg = sum(_gain(g) / math.log2(i + 1) for i, g in enumerate(ideal, start=1))
if idcg == 0.0:
return 0.0
return dcg_at_k(ranked, grades, k) / idcg
def context_precision(ranked: list[str], relevant: set[str]) -> float:
"""RAGAS-style context precision: weight each rank's precision by whether
it is relevant, then divide by the number of relevant items retrieved.
Like average precision, but the denominator counts only the relevant
items actually retrieved — so a query whose relevant set was only
half-covered isn't penalised twice. This is the formula on the RAGAS
context-precision page (sum of precision@k x relevance, divided by the
number of relevant items in the top K), applied to whatever ranking you
pass in. RAGAS itself decides relevance with an LLM; here the qrels do.
"""
rel = set(relevant)
total = 0.0
n_rel_found = 0
hits = 0
for i, cid in enumerate(ranked, start=1):
if cid in rel:
hits += 1
n_rel_found += 1
total += hits / i
return total / n_rel_found if n_rel_found else 0.0
# ---------------------------------------------------------------------------
# latency and cost (first-class metrics)
# ---------------------------------------------------------------------------
def percentile(values: list[float], q: float) -> float:
"""The q-th percentile (0-100) with linear interpolation between closest ranks."""
if not values:
return 0.0
xs = sorted(values)
if len(xs) == 1:
return xs[0]
pos = (q / 100.0) * (len(xs) - 1)
lo, hi = int(pos), min(int(pos) + 1, len(xs) - 1)
frac = pos - lo
return xs[lo] * (1 - frac) + xs[hi] * frac
def latency_summary(samples_ms: list[float]) -> dict[str, float]:
"""p50/p95/p99 from per-query latency samples (ms)."""
return {
"p50": percentile(samples_ms, 50),
"p95": percentile(samples_ms, 95),
"p99": percentile(samples_ms, 99),
"mean": mean(samples_ms) if samples_ms else 0.0,
}
def cost_per_query(
embed_price_per_1m_tokens: float,
query_tokens: int,
rerank_price_per_1k_docs: float = 0.0,
n_docs_reranked: int = 0,
llm_price_per_1m_tokens: float = 0.0,
context_tokens: int = 0,
) -> float:
"""Dollars per query: embed + rerank + the LLM context the retrieved
chunks are billed into. Prices are parameters — never hard-code them;
look them up on the provider page (lesson 06.1, 06.9, 03.7).
`rerank_price_per_1k_docs` models per-document or per-search billing. Some
rerankers now bill per input token (lesson 06.9, Part 3): for those, compute
`tokens x price` yourself and add it to the result.
`context_tokens` is the total tokens of retrieved chunks sent to the LLM
(k chunks x chunk_tokens, plus prompt overhead) — usually the dominant
term, which is why precision@k is also a cost metric.
"""
embed_cost = embed_price_per_1m_tokens * query_tokens / 1_000_000
rerank_cost = rerank_price_per_1k_docs * n_docs_reranked / 1000
llm_cost = llm_price_per_1m_tokens * context_tokens / 1_000_000
return embed_cost + rerank_cost + llm_cost
# ---------------------------------------------------------------------------
# labeller agreement
# ---------------------------------------------------------------------------
def cohen_kappa(labels_a: list[int], labels_b: list[int]) -> float:
"""Agreement between two labellers beyond chance, for binary labels (0/1).
kappa = (observed agreement - expected agreement) / (1 - expected agreement).
Rough guide: <0.2 poor, 0.2-0.4 fair, 0.4-0.6 moderate, 0.6-0.8 substantial,
>0.8 almost perfect (Landis & Koch 1977).
"""
n = len(labels_a)
if n == 0 or len(labels_b) != n:
raise ValueError("label lists must be non-empty and equal length")
observed = sum(1 for a, b in zip(labels_a, labels_b) if a == b) / n
# expected agreement from each labeller's marginal proportions
pa1 = sum(labels_a) / n
pb1 = sum(labels_b) / n
expected = pa1 * pb1 + (1 - pa1) * (1 - pb1)
if expected == 1.0:
return 1.0 if observed == 1.0 else 0.0
return (observed - expected) / (1 - expected)
# ---------------------------------------------------------------------------
# bootstrap confidence intervals for paired comparisons
# ---------------------------------------------------------------------------
def bootstrap_ci(
diffs: list[float],
n_boot: int = 2000,
alpha: float = 0.05,
seed: int = 0,
) -> tuple[float, float, float]:
"""Percentile bootstrap CI for the MEAN of paired per-query differences.
`diffs[i]` = metric(new retriever, query i) - metric(old retriever, query i).
Resample the queries with replacement, recompute the mean each time, and
take the alpha/2 and 1-alpha/2 percentiles of the bootstrap distribution.
Returns (mean_diff, lo, hi). Pure Python — fine for the small eval sets in
this lesson; use numpy for thousands of queries.
"""
if not diffs:
raise ValueError("diffs must be non-empty")
import random
rng = random.Random(seed)
n = len(diffs)
means = []
for _ in range(n_boot):
sample = [diffs[rng.randrange(n)] for _ in range(n)]
means.append(mean(sample))
means.sort()
lo = means[int((alpha / 2) * n_boot)]
hi = means[min(int((1 - alpha / 2) * n_boot), n_boot - 1)]
return mean(diffs), lo, hiRun the worked example with this short script (save it as worked_example.py beside metrics.py):
# worked_example.py — the numbers for the ranking above (pure stdlib)
from metrics import (hit_at_k, recall_at_k, precision_at_k, mrr, _average_precision,
r_precision, ndcg_at_k, dcg_at_k, context_precision, percentile,
cohen_kappa)
ranking = ["c1", "c4", "c3", "c2", "c5", "c7", "c6"]
grades = {"c1": 2, "c2": 1, "c3": 2, "c4": 1}
relevant = set(grades) # every grade >= 1
print(f"hit@3 = {hit_at_k(ranking, relevant, 3)}") # c1, c4, c3 are all relevant
print(f"recall@3 = {recall_at_k(ranking, relevant, 3)}") # 3 of 4 found: c2 sits at rank 4
print(f"prec@3 = {precision_at_k(ranking, relevant, 3)}") # all 3 returned items are relevant
print(f"mrr = {mrr(ranking, relevant)}") # first relevant item (c1) at rank 1
print(f"AP = {_average_precision(ranking, relevant)}") # relevant items occupy ranks 1-4
print(f"r_prec = {r_precision(ranking, relevant)}") # R = 4: ranks 1-4 are all relevant
print(f"ndcg@5 = {ndcg_at_k(ranking, grades, 5):.3f}") # c4 (grade 1) sits above c3 (grade 2)
print(f"dcg = {dcg_at_k(ranking, grades, 5):.4f}") # ideal DCG is 5.8235
print(f"ctx_prec = {context_precision(ranking, relevant)}") # equals AP: all 4 were retrieved
latencies = [10.0 * i for i in range(1, 11)] # 10, 20, ... 100 ms
print("pct =", [round(percentile(latencies, q), 1) for q in (50, 95, 99)])
print("kappa =", cohen_kappa([1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0]))hit@3 = 1.0
recall@3 = 0.75
prec@3 = 1.0
mrr = 1.0
AP = 1.0
r_prec = 1.0
ndcg@5 = 0.955
dcg = 5.5616
ctx_prec = 1.0
pct = [55.0, 95.5, 99.1]
kappa = 0.5The pct line is the p50, p95 and p99 of the ten latencies, and kappa is the two-labeller example from 2.6. The nDCG DCG of 5.5616 against an ideal of 5.8235 gives the 0.955.
Read the pattern: hit@k is the most forgiving (one relevant item anywhere in top-k = 1.0), recall@k the strictest about coverage, MRR only cares about the first hit, nDCG is the only one that sees grades and full ordering, and precision@k is the only one that punishes junk in the list. No single number summarises "good" — the art is picking the ones your downstream consumer needs.
3.2 hit rate / success@k and recall@k#
- hit@k (success@k): did anything relevant appear in the top-k? Binary per query, averaged across queries. The classic "did the user get a useful result" metric. With a single relevant item per query it equals recall@k.
- recall@k: what fraction of all relevant items made the top-k? The coverage metric — and for RAG the most important one, because the LLM can only use what retrieval returned. If the answer needs two chunks and you retrieve one, recall@k = 0.5 and the answer is probably incomplete no matter how good the generator is.
When to use: recall@k at your actual context size k (how many chunks you send the LLM — often 3–8, not 50) is the headline metric for RAG. hit@k is the friendlier "user satisfaction" proxy for search UIs.
3.3 precision@k#
What fraction of the top-k is relevant? Precision punishes the junk that wastes context tokens and dilutes the generator's attention. It's most meaningful when k is small (you pay per chunk sent) and when your retriever tends to pad lists. Note the asymmetry: you can always raise precision by returning fewer results — a retriever returning only its single best guess scores precision@1 = 1.0 forever. Precision must be read together with recall; that's why nDCG and the paired metrics exist.
3.4 MRR — mean reciprocal rank#
mrr = mean over queries of 1/rank_of_first_relevant. Rewards putting a relevant item at the very top; ignores everything below the first hit and ignores how many relevant items exist. It's the metric for "the user only looks at the first result" — search-engine style, single-answer QA, and the classic MS MARCO passage-ranking metric. Weakness: blind to coverage — a retriever that finds one relevant chunk at rank 1 and misses four others scores MRR 1.0.
3.5 MAP — mean average precision#
Average precision per query = mean of precision@i over the ranks i that hold relevant items; MAP averages that across queries. MAP rewards all relevant items being ranked highly, not just the first — it's the standard "overall ranking quality" metric in IR benchmarks (TREC, BEIR report variants of it). More sensitive to the full ordering than MRR, more forgiving of a weak first hit than nDCG is of grade ordering. Use it when you have binary labels and care about the whole list.
3.6 nDCG@k — normalised discounted cumulative gain#
The graded-relevance metric. Three ideas:
- Gain — a grade-2 chunk is worth
2²−1 = 3, a grade-1 worth2¹−1 = 1. Exponential gains encode "the answer matters much more than context". - Discount — divide each gain by
log2(rank + 1): rank 1 keeps full gain, rank 2 keeps ~63%, rank 5 ~39%, rank 10 ~29%. Being early matters. - Normalise — divide by the ideal DCG (the best possible ordering of the same grades) so scores are comparable across queries with different numbers of relevant items.
nDCG@k ∈ [0,1], is the standard metric in BEIR/MTEB retrieval leaderboards, and is the right choice when you have graded labels and care about both coverage and position. Our worked example scored 0.955 — the only flaw was grade-1 c4 outranking grade-2 c3.
3.7 R-precision and needed-set recall#
- R-precision: precision at rank R, where R = the number of relevant items for that query. "If I showed exactly as many results as there are relevant documents, how many would be relevant?" Needs no chosen k — elegant for comparing systems.
- Needed-set recall: like recall@k but over the
neededset — the minimal chunks that actually answer. It catches the failure recall@k misses: helpful context retrieved, answer missed. Our eval set has the perfect example inq05("why was I charged twice for VPN seats in October?"):relevant = {ticket-78: 2, ticket-77: 1}butneeded = [ticket-78]—ticket-77is the customer's question (grade-1 context),ticket-78is the resolved answer (grade 2). A retriever returning onlyticket-77scores recall@k = 0.5 (half the relevant set) but needed_recall = 0.0 — and that's exactly what BM25 and hybrid do onq05in the demo (4.7). Whenrelevantandneededcoincide —q06's two-clause MSA answer needs bothcontract-10andcontract-9— the two metrics agree; they diverge precisely when helpful-but-unneeded context exists, which is what you want to see.
3.8 Context precision/recall — the RAG-eval view#
RAG evaluation tools (RAGAS is the best known; docs.ragas.io) define context precision and context recall over the retrieved context rather than the ranking:
- Context precision (implemented above): like AP but denominated by retrieved relevant items — "of the relevant chunks you returned, how well are they ranked at the top?" Our
context_precisionmatches the documented formula shape. - Context recall: "what fraction of the information needed to answer was retrieved?" RAGAS estimates it by decomposing a reference answer into claims and checking each against the retrieved context — it needs an LLM or reference contexts, so it's a Module 10A metric, not a pure function. The idea is what matters here: it's the metric that connects retrieval to answer completeness.
The full treatment of these RAG-side context metrics (precision, recall, relevance, noise and redundancy, all measured on the in-context set rather than the raw search() output) is 10A.6, 3.6; 07.9, 2.9 gives the first-pass definitions.
3.9 Latency percentiles and cost per query — first-class metrics#
Quality without speed is a demo. Track alongside the ranking metrics:
- Latency: report p50/p95/p99, not the mean — means hide the tail that users feel.
latency_summaryabove does it; feed it per-querysearch()wall-times. p99 is what your SLO is written against. - Cost per query:
embed_cost + rerank_cost + llm_context_cost— all three terms are parameters ofcost_per_queryinmetrics.pyabove: the embedding call (query_tokens × embed price), the reranker (n_docs_reranked × rerank price), and the context you send the LLM (context_tokens × llm price). The last usually dominates — every retrieved chunk's tokens are billed on every call — which is why precision@k is also a cost metric.
Prices are parameters — look them up on the provider pages (06.1, 06.9, 03.7); never hard-code them.
3.10 Which metric answers which question#
| You want to know... | Use | Because |
|---|---|---|
| Did the user get anything useful in top-k? | hit@k / success@k | Forgiving, user-facing |
| Will the LLM have all the pieces it needs? | recall@k at your context size | Coverage ceiling for RAG |
| Is the list noisy / wasting context tokens? | precision@k | Cost + dilution |
| Is the first result the answer (search UI, single-answer QA)? | MRR | Rank-1 obsession |
| Overall ranking quality with binary labels | MAP | Whole-list sensitivity |
| Ranking quality with graded labels | nDCG@k | Gains + discounts + normalisation; leaderboard standard |
| "Exactly R results, how many relevant?" | R-precision | No arbitrary k |
| Did we find ALL pieces of a multi-chunk answer? | needed-set recall | Catches half-answers |
| Are relevant items ranked at the top of what we returned? | context precision | RAG-eval style |
| Is it fast enough / cheap enough? | p50/p95/p99 latency, cost/query | First-class, alongside quality |
The RAG rule of thumb: recall@k at the final context size k is your headline metric (it bounds answer quality); rank-sensitive metrics (MRR, nDCG) matter most when a reranker is in the loop, because rerankers exist to fix position, not coverage — a reranker can't rescue a relevant chunk that stage-1 never retrieved. That division of labour is why 06.9 evaluates with the same metrics before and after reranking.
3.11 The pitfalls#
- Unjudged documents counted as irrelevant ("holes"). In a real corpus you can't grade every chunk for every query. If your retriever returns an unjudged chunk that actually answers, metrics score it 0 — you undercount quality and, worse, you can't tell a true miss from a labelling gap. Mitigations: pooling (grade the union of what all your retrievers return, the TREC approach), treat "unjudged" as a third state in analysis, and re-grade the top results of new retrievers before comparing.
- Averaging across queries with wildly different relevant-set sizes. recall@k on a query with 1 relevant chunk is 0 or 1; on one with 8 it's granular. The mean is dominated by whichever type is more common — stratify (2.4) and read per-type numbers.
- Duplicates gaming the metrics. If retrieval returns five copies of the same relevant chunk, recall@5 looks great while diversity is zero. Deduplicate by document/section before scoring (06.6 covers grouping) or penalise near-duplicates in analysis.
- Small-sample noise. A 16-query set's "recall 0.964" has a confidence interval roughly ±0.15 — differences smaller than that are noise. Always compare with CIs (4.5).
- Metric gaming. Optimising one metric at the expense of others is easy: return fewer results → precision up, recall down; return the whole corpus → recall up, precision/latency/cost down. Never ship a change justified by a single metric.
- Scores that aren't probabilities. Don't threshold cosine scores for abstention without tuning the threshold on labelled data — score distributions differ per model, per query, per corpus.
Part 4: The evaluation harness#
Metrics on paper are useless until something runs them. The harness is the piece of code you'll actually keep: it runs a query set against any retriever, scores it, saves the run with provenance, compares two runs honestly, and shows you the failures.
The demo corpus — corpus.py, printed in full (the Module 05 running corpus extended to 14 chunks, with deterministic toy vectors standing in for a real embedding model):
# corpus.py — the module's running corpus, extended to 14 chunks for eval demos.
#
# Chunks 001-004, 101-102, 77-78, 9-10 are the same ten chunks lesson 06.5 uses
# (fictional company handbook / help centre / tickets / contracts). We add four
# chunks so the eval set has enough material: parental leave, password reset,
# a VPN error-code article, and a data-processing addendum.
#
# Vectors are NOT hand-typed numbers. They are generated deterministically:
# - five "domain" directions (leave, expenses, vpn, billing, contracts)
# - one "topic" direction per chunk
# - chunk_vec = normalise(0.55*domain + 0.8*topic + 0.3*noise)
# This mimics how real embedding spaces behave: chunks about the same broad
# area cluster together, and specific topics sit inside their cluster. A real
# embedding model (lesson 06.1) does this far better; swap it in and nothing
# else changes.
from __future__ import annotations
import math
import random
from dataclasses import dataclass, field
DIMS = 32
@dataclass(frozen=True)
class Chunk:
id: str
doc_id: str
section: str
topic: str # the specific sub-topic used to build the toy vector
domain: str # the broad area used to build the toy vector
text: str
metadata: dict = field(default_factory=dict)
vector: tuple[float, ...] = ()
# --- the corpus -----------------------------------------------------------------
RAW = [
# id, doc, section, topic, domain, text, extra metadata
("handbook-001", "handbook", "leave/vacation", "vacation-days",
"leave",
"Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
{"tenant": "acme", "kind": "policy", "lang": "en"}),
("handbook-002", "handbook", "leave/sick", "sick-leave",
"leave",
"Sick leave is separate from vacation: 10 days per year, no accrual cap.",
{"tenant": "acme", "kind": "policy", "lang": "en"}),
("handbook-003", "handbook", "expenses/per-diem", "per-diem-rates",
"expenses",
"Domestic travel per diem is $75 per day; meals are reimbursed with receipts over $25.",
{"tenant": "acme", "kind": "policy", "lang": "en"}),
("handbook-004", "handbook", "expenses/reviews", "expense-review-time",
"expenses",
"Expense reports are reviewed by your manager within 5 business days.",
{"tenant": "acme", "kind": "policy", "lang": "en"}),
("handbook-005", "handbook", "leave/parental", "parental-leave",
"leave",
"Parental leave: 16 weeks for the primary caregiver and 6 weeks for the secondary caregiver, usable within the first year.",
{"tenant": "acme", "kind": "policy", "lang": "en"}),
("help-101", "help-centre", "vpn/setup", "vpn-install",
"vpn",
"Install the VPN client, sign in with your SSO account, and pick the nearest region.",
{"tenant": "acme", "kind": "howto", "lang": "en"}),
("help-102", "help-centre", "vpn/troubleshooting", "vpn-drops",
"vpn",
"If the VPN drops, reconnect; if it keeps failing, flush the DNS cache and retry.",
{"tenant": "acme", "kind": "howto", "lang": "en"}),
("help-103", "help-centre", "access/password", "password-reset",
"access",
"To reset your password, choose 'Forgot password' on the SSO sign-in page; reset links expire after 30 minutes.",
{"tenant": "acme", "kind": "howto", "lang": "en"}),
("help-104", "help-centre", "vpn/errors", "vpn-error-2041",
"vpn",
"Error VPN-ERR-2041 means the VPN gateway certificate has expired; renew it in the admin console under Network > Certificates.",
{"tenant": "acme", "kind": "howto", "lang": "en"}),
("ticket-77", "tickets", "billing/2026-10", "invoice-question",
"billing",
"Customer asked why the October invoice shows two VPN seat charges.",
{"tenant": "globex", "kind": "ticket", "lang": "en"}),
("ticket-78", "tickets", "billing/2026-10", "duplicate-charge",
"billing",
"Duplicate seat charge traced to a provisioning race; refund issued.",
{"tenant": "globex", "kind": "ticket", "lang": "en"}),
("contract-9", "contracts", "msa/2025", "msa-payment-liability",
"contracts",
"Master service agreement: payment terms net-30, liability cap 12 months of fees.",
{"tenant": "initech", "kind": "contract", "lang": "en"}),
("contract-10", "contracts", "msa/2025", "msa-renewal",
"contracts",
"Renewal notice must be given 60 days before the term ends or it auto-renews.",
{"tenant": "initech", "kind": "contract", "lang": "en"}),
("contract-11", "contracts", "dpa/2025", "breach-notification",
"contracts",
"Data processing addendum: subprocessors are listed in Annex B; customers must be notified of a personal-data breach within 72 hours.",
{"tenant": "initech", "kind": "contract", "lang": "en"}),
]
def _rand_unit(rng: random.Random, dims: int) -> list[float]:
v = [rng.gauss(0.0, 1.0) for _ in range(dims)]
n = math.sqrt(sum(x * x for x in v))
return [x / n for x in v]
def _add_scaled(a: list[float], b: list[float], w: float) -> list[float]:
return [x + w * y for x, y in zip(a, b)]
def _normalise(v: list[float]) -> tuple[float, ...]:
n = math.sqrt(sum(x * x for x in v))
return tuple(x / n for x in v)
def build_chunks(seed: int = 20261105) -> list[Chunk]:
"""Deterministically build the corpus with toy vectors."""
rng = random.Random(seed)
domains = sorted({r[4] for r in RAW})
domain_vec = {d: _rand_unit(rng, DIMS) for d in domains}
topic_vec = {}
for r in RAW:
if r[3] not in topic_vec:
topic_vec[r[3]] = _rand_unit(rng, DIMS)
# a per-chunk noise direction so no two chunks are identical
noise_vec = {r[0]: _rand_unit(rng, DIMS) for r in RAW}
chunks = []
for cid, doc, section, topic, domain, text, meta in RAW:
v = [0.0] * DIMS
v = _add_scaled(v, domain_vec[domain], 0.55)
v = _add_scaled(v, topic_vec[topic], 0.80)
v = _add_scaled(v, noise_vec[cid], 0.30)
chunks.append(Chunk(
id=cid, doc_id=doc, section=section, topic=topic, domain=domain,
text=text, metadata=meta, vector=_normalise(v),
))
return chunks
CHUNKS: list[Chunk] = build_chunks()
BY_ID: dict[str, Chunk] = {c.id: c for c in CHUNKS}
# What a query "means" in vector space: the domain + topic it is asking about,
# plus noise so retrieval is not perfect. Multi-topic queries (multi-hop)
# average several topic directions. `None` topics = out-of-corpus query.
QUERY_TOPICS: dict[str, tuple[str, ...]] = {
"q01": ("vacation-days",),
"q02": ("per-diem-rates",),
"q03": ("vpn-drops",),
"q04": ("vpn-error-2041",),
"q05": ("duplicate-charge",),
"q06": ("msa-renewal", "msa-payment-liability"),
"q07": ("msa-payment-liability",),
"q08": ("sick-leave",),
"q09": ("password-reset",),
"q10": ("expense-review-time",),
"q11": ("parental-leave",),
"q12": ("breach-notification",),
"q13": (), # out-of-corpus: office wifi password
"q14": ("per-diem-rates",), # ambiguous/travel-expense question
"q15": ("vacation-days",), # the same question in Spanish
"q16": ("msa-payment-liability",), # would-be leak: initech terms, acme filter
}
# Paraphrases produced by the query_techniques.py demos map back to an eval id.
# A real embedder embeds the TEXT; the toy looks the meaning up by alias.
QUERY_TEXT_ALIASES = {
"reconnect the vpn client": "q03",
"flush the dns cache": "q03",
"contact it support": "q03",
"master service agreement terms": "q06",
}
def query_vector(qid: str, seed: int = 7) -> tuple[float, ...]:
"""A deterministic stand-in for `embedder.embed(query)`.
In production this vector comes from a real embedding model (06.1). Here it
is built from the same topic directions the chunks use, so a 'good' query
lands near the chunks that should answer it — exactly what a real model
learns to do. Queries about the same topic in different languages share the
topic direction, which is how multilingual embeddings behave.
"""
qid = QUERY_TEXT_ALIASES.get(qid.strip().lower(), qid)
rng = random.Random(f"{seed}:{qid}")
topics = QUERY_TOPICS.get(qid)
if topics is None:
# unknown text: behave like an out-of-corpus query rather than crash —
# a real embedder always returns SOME vector; ours returns a random one
return _normalise(_rand_unit(rng, DIMS))
if not topics:
# out-of-corpus: a random direction, roughly equidistant from everything
return _normalise(_rand_unit(rng, DIMS))
# rebuild the same topic vectors corpus.py used (same seed, same order)
base_rng = random.Random(20261105)
domains = sorted({r[4] for r in RAW})
domain_vec = {d: _rand_unit(base_rng, DIMS) for d in domains}
topic_vec = {}
for r in RAW:
if r[3] not in topic_vec:
topic_vec[r[3]] = _rand_unit(base_rng, DIMS)
# NOTE: build_chunks consumed noise vectors after topics; query_vector only
# needs domain+topic directions, which are generated first — consistent.
v = [0.0] * DIMS
weight = 1.0 / len(topics)
for t in topics:
owner = next(r for r in RAW if r[3] == t)
v = _add_scaled(v, domain_vec[owner[4]], 0.55 * weight)
v = _add_scaled(v, topic_vec[t], 0.80 * weight)
v = _add_scaled(v, _rand_unit(rng, DIMS), 0.60)
return _normalise(v)4.1 The Retriever protocol#
Everything in the module converges on one seam. Define it once and every retriever — toy, pgvector, Qdrant, hybrid, reranked — satisfies it:
# retrievers.py — the retriever seam + three toy retrievers for the eval demos.
#
# `Retriever` is the contract the whole module converges on: a query in,
# ranked Hits out. The eval harness (harness.py) only ever sees this protocol,
# so swapping a toy retriever for a real vector store changes nothing else.
from __future__ import annotations
import math
import re
from dataclasses import dataclass, field
from typing import Protocol
from corpus import CHUNKS, Chunk, query_vector
@dataclass(frozen=True)
class Hit:
"""One retrieved result. `score` is retriever-specific and NOT comparable
across retrievers — never average or threshold it across systems.
`source` is provenance: which stage produced this hit ("dense", "bm25",
"rrf", "reranker:..."). Module 07 needs it for citations and debugging —
'which side supplied the winning result' is also the hybrid-monitoring
signal from lesson 06.8."""
id: str
score: float
text: str = ""
metadata: dict = field(default_factory=dict)
source: str = ""
class Retriever(Protocol):
"""The contract Module 07's RAG pipeline will consume."""
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]: ...
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def cosine(a: tuple[float, ...], b: tuple[float, ...]) -> float:
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(x * x for x in b))
return dot / (na * nb) if na and nb else 0.0
def _matches(chunk: Chunk, filters: dict | None) -> bool:
"""Pre-filtering: constraints applied BEFORE scoring (lesson 06.6)."""
if not filters:
return True
for key, want in filters.items():
have = chunk.metadata.get(key)
if isinstance(want, (list, tuple, set)):
if have not in want:
return False
elif have != want:
return False
return True
def _hits(chunk: Chunk, score: float, source: str = "") -> Hit:
return Hit(id=chunk.id, score=score, text=chunk.text,
metadata=chunk.metadata, source=source)
# ---------------------------------------------------------------------------
# retriever 1: toy dense (cosine over the synthetic topic vectors)
# ---------------------------------------------------------------------------
class DenseRetriever:
"""Stands in for 'embed query + embed corpus + ANN search'.
Uses corpus.query_vector() — in production this is embedder.embed(query)
from lesson 06.1. Scores are cosines in [-1, 1].
"""
name = "dense-toy"
def __init__(self, chunks: list[Chunk] = CHUNKS):
self.chunks = chunks
def search(self, query: str, k: int = 10,
filters: dict | None = None, qid: str | None = None) -> list[Hit]:
# qid is a demo convenience: the toy query vector is keyed by eval id.
# A real retriever embeds the `query` string; ours looks up the topic.
qv = query_vector(qid or query)
scored = [
(cosine(qv, c.vector), c)
for c in self.chunks if _matches(c, filters)
]
scored.sort(key=lambda p: -p[0])
return [_hits(c, s, "dense") for s, c in scored[:k]]
# ---------------------------------------------------------------------------
# retriever 2: toy lexical (BM25 over the same chunks)
# ---------------------------------------------------------------------------
_TOKEN = re.compile(r"[a-z0-9]+")
def _tokens(text: str) -> list[str]:
return _TOKEN.findall(text.lower())
class Bm25Retriever:
"""A compact BM25 over the chunk texts. k1=1.2, b=0.75 — the common defaults.
idf uses the +1 form so scores stay non-negative for very common terms.
Lesson 06.7 owns BM25 in depth; this is only good enough to make lexical
retrieval real inside the eval harness.
"""
name = "bm25-toy"
K1 = 1.2
B = 0.75
def __init__(self, chunks: list[Chunk] = CHUNKS):
self.chunks = chunks
self._docs = [_tokens(c.text) for c in chunks]
self._tf = [{t: d.count(t) for t in set(d)} for d in self._docs]
self._dl = [len(d) for d in self._docs]
self._avgdl = sum(self._dl) / len(self._dl) if self._dl else 0.0
df: dict[str, int] = {}
for d in self._docs:
for t in set(d):
df[t] = df.get(t, 0) + 1
n = len(self._docs)
self._idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]:
qterms = _tokens(query)
scored = []
for i, c in enumerate(self.chunks):
if not _matches(c, filters):
continue
score = 0.0
for t in qterms:
tf = self._tf[i].get(t, 0)
if not tf:
continue
idf = self._idf.get(t, 0.0)
denom = tf + self.K1 * (1 - self.B + self.B * self._dl[i] / self._avgdl)
score += idf * tf * (self.K1 + 1) / denom
scored.append((score, c))
scored.sort(key=lambda p: -p[0])
return [_hits(c, s, "bm25") for s, c in scored[:k]]
# ---------------------------------------------------------------------------
# retriever 3: hybrid = RRF fusion of dense + BM25 (lesson 06.8's algorithm)
# ---------------------------------------------------------------------------
def rrf(rankings: list[list[Hit]], k: float = 60.0,
weights: list[float] | None = None) -> list[Hit]:
"""Reciprocal Rank Fusion, 1-based ranks. Scores are fused ranks, not
comparable with either retriever's raw scores — by design."""
if weights is None:
weights = [1.0] * len(rankings)
fused: dict[str, float] = {}
meta: dict[str, Hit] = {}
for w, ranking in zip(weights, rankings):
for rank, hit in enumerate(ranking, start=1):
fused[hit.id] = fused.get(hit.id, 0.0) + w / (k + rank)
meta.setdefault(hit.id, hit)
ordered = sorted(fused.items(), key=lambda p: -p[1])
return [Hit(id=cid, score=s, text=meta[cid].text,
metadata=meta[cid].metadata, source="rrf")
for cid, s in ordered]
class HybridRetriever:
"""Dense + BM25 fused with RRF — the shape lesson 06.8 builds in production."""
name = "hybrid-rrf"
def __init__(self, dense: DenseRetriever, lexical: Bm25Retriever,
prefetch: int = 20, rrf_k: float = 60.0):
self.dense, self.lexical = dense, lexical
self.prefetch, self.rrf_k = prefetch, rrf_k
def search(self, query: str, k: int = 10,
filters: dict | None = None, qid: str | None = None) -> list[Hit]:
d = self.dense.search(query, k=self.prefetch, filters=filters, qid=qid)
x = self.lexical.search(query, k=self.prefetch, filters=filters)
return rrf([d, x], k=self.rrf_k)[:k]Three toy retrievers implement it over the same corpus so you can compare like-for-like: DenseRetriever (cosine over the deterministic topic vectors — stands in for embed + ANN), Bm25Retriever (a compact BM25, k1=1.2/b=0.75), and HybridRetriever (RRF fusion of the two, prefetch 20, k=60 — 06.8's algorithm). corpus.py builds 14 chunks from the Module 05 running corpus with vectors generated from shared domain+topic directions, so chunks about the same area cluster — a toy stand-in for what a real embedding model learns.
One caution: the chunk ids are the same readable ids as in the toy corpora of 06.8 and 06.9, but each lesson's corpus is self-contained and a few texts differ — for example help-102 carries the VPN-ERR-2041 error code in 06.8/06.9 but the DNS-flush advice here (the error code lives in help-104). Don't carry numbers from one lesson's toy corpus to another.
The same search, vectorised — this is what a real vector store does internally, in one NumPy expression (real output, deterministic):
import numpy as np
from corpus import CHUNKS, query_vector
M = np.array([c.vector for c in CHUNKS]) # (14, 32) — the "index"
q = np.array(query_vector("q05")) # what embedder.embed(query) returns
sims = M @ q / (np.linalg.norm(M, axis=1) * np.linalg.norm(q))
for i in np.argsort(-sims)[:5]:
print(f"{CHUNKS[i].id:12s} {sims[i]:+.3f}")ticket-78 +0.820
ticket-77 +0.389
contract-11 +0.198
contract-10 +0.126
contract-9 +0.120DenseRetriever is this loop written out longhand; at real scale the "index" is a ANN structure (06.4) that finds the top-k without scanning every vector — but the math being approximated is exactly this dot product.
4.2 The eval set format#
eval_queries.jsonl — one JSON object per line, the format your harness loads:
{"qid": "q01", "query": "how much vacation do I get?", "split": "dev", "type": "factoid", "relevant": {"handbook-001": 2}, "notes": "paraphrase: chunk says 'accrue 1.5 days per month'"}
{"qid": "q02", "query": "what is the per diem for domestic travel?", "split": "dev", "type": "factoid", "relevant": {"handbook-003": 2}}
{"qid": "q03", "query": "my VPN keeps dropping, what should I try?", "split": "dev", "type": "howto", "relevant": {"help-102": 2, "help-101": 1}, "notes": "help-101 is setup context, grade 1"}
{"qid": "q04", "query": "VPN-ERR-2041", "split": "dev", "type": "error-code", "relevant": {"help-104": 2}, "notes": "exact identifier: lexical should win"}
{"qid": "q05", "query": "why was I charged twice for VPN seats in October?", "split": "dev", "type": "diagnostic", "relevant": {"ticket-78": 2, "ticket-77": 1}, "needed": ["ticket-78"], "notes": "ticket-77 is the customer's question, useful context"}
{"qid": "q06", "query": "when does the MSA auto-renew and what are the payment terms?", "split": "dev", "type": "multi-hop", "relevant": {"contract-10": 2, "contract-9": 2}, "needed": ["contract-10", "contract-9"], "notes": "needs BOTH clauses: needed-set recall catches half answers"}
{"qid": "q07", "query": "net-30 payment terms liability cap", "split": "test", "type": "keyword", "relevant": {"contract-9": 2}}
{"qid": "q08", "query": "how many sick days per year?", "split": "dev", "type": "factoid", "relevant": {"handbook-002": 2}}
{"qid": "q09", "query": "how do I reset my password?", "split": "dev", "type": "howto", "relevant": {"help-103": 2}}
{"qid": "q10", "query": "how long does expense report review take?", "split": "test", "type": "howto", "relevant": {"handbook-004": 2}}
{"qid": "q11", "query": "parental leave entitlement", "split": "test", "type": "factoid", "relevant": {"handbook-005": 2}}
{"qid": "q12", "query": "breach notification window and subprocessors", "split": "test", "type": "multi-field", "relevant": {"contract-11": 2}}
{"qid": "q13", "query": "what is the office wifi password?", "split": "dev", "type": "no-answer", "relevant": {}, "notes": "correct behaviour is abstention / no confident result; excluded from recall averages"}
{"qid": "q14", "query": "can I claim per diem and meal receipts for the same trip?", "split": "dev", "type": "ambiguous", "relevant": {"handbook-003": 1}, "needed": [], "notes": "no chunk fully answers; grade-1 partial only. needed empty => needed-set recall n/a"}
{"qid": "q15", "query": "¿cuántos días de vacaciones tengo al año?", "split": "test", "type": "multilingual", "relevant": {"handbook-001": 2}, "notes": "Spanish for 'how many vacation days per year': dense should win, BM25 cannot match"}
{"qid": "q16", "query": "what are the net-30 payment terms?", "split": "dev", "type": "filtered-empty", "filters": {"tenant": "acme"}, "relevant_unfiltered": {"contract-9": 2}, "relevant": {}, "notes": "an acme user asks about initech contract terms: correct result is EMPTY. returning contract-9 is a cross-tenant leak (lesson 06.6)"}Our 16-query set covers the taxonomy from 2.2: factoids, how-tos, an error code, a diagnostic question, a keyword query, a multi-hop query, a no-answer query, an ambiguous one, a Spanish query, and a filtered-empty query (q16: an acme user asks about initech contract terms — correct behaviour is returning nothing, and returning contract-9 is a cross-tenant leak). split marks dev vs test per 2.8.
4.3 The runner#
harness.py — stdlib only, printed in full (it imports the protocol and metrics from the files above):
# harness.py — the retrieval evaluation harness.
#
# Given any Retriever and a labelled query set (JSONL), it:
# 1. runs every query through the retriever (with the query's filters)
# 2. computes per-query metrics and aggregates (overall / per split / per type)
# 3. saves a run record with full provenance (config + code version)
# 4. compares two runs with paired differences + bootstrap confidence intervals
# 5. lists the failures for human review
#
# Stdlib only. The retriever sees ONLY the Retriever protocol, so a real
# vector store drops in unchanged.
from __future__ import annotations
import csv
import hashlib
import inspect
import json
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from corpus import CHUNKS, BY_ID
from metrics import (
hit_at_k, recall_at_k, precision_at_k, mrr, map_score, r_precision,
needed_set_recall, ndcg_at_k, context_precision, bootstrap_ci,
)
from retrievers import Hit, Retriever, _matches
# ---------------------------------------------------------------------------
# the labelled query set
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class EvalQuery:
qid: str
query: str
split: str # "dev" | "test" | "train"
qtype: str # factoid, howto, error-code, ...
relevant: dict # chunk_id -> grade (1 = useful, 2 = answers)
needed: tuple # minimal answer-bearing set (may be empty)
filters: dict | None
relevant_unfiltered: dict # for filtered-empty queries: what WOULD match
notes: str
def load_evalset(path: str | Path) -> list[EvalQuery]:
queries = []
with open(path) as f:
for line in f:
line = line.strip()
if not line:
continue
d = json.loads(line)
relevant = d.get("relevant", {})
# needed defaults to the grade-2 chunks; explicit [] means
# 'no chunk fully answers this query'
needed = tuple(d["needed"]) if "needed" in d else \
tuple(cid for cid, g in relevant.items() if g >= 2)
queries.append(EvalQuery(
qid=d["qid"], query=d["query"], split=d.get("split", "dev"),
qtype=d.get("type", "other"), relevant=relevant,
needed=needed, filters=d.get("filters"),
relevant_unfiltered=d.get("relevant_unfiltered", relevant),
notes=d.get("notes", ""),
))
return queries
# ---------------------------------------------------------------------------
# running the eval
# ---------------------------------------------------------------------------
@dataclass
class QueryResult:
qid: str
query: str
split: str
qtype: str
retrieved: list[str] # ids, best first
scores: list[float]
relevant: dict
needed: tuple
filters: dict | None
metrics: dict
expected_empty: bool # no-answer OR filtered-empty query
leaked: bool # filtered-empty query that returned a forbidden chunk
def _binary_relevant(q: EvalQuery, k_chunks: set[str] | None = None) -> set[str]:
"""Relevant ids, restricted to chunks that pass the query's filters.
This is the subtle rule: qrels are defined *within the permission
boundary*. A filtered-empty query has relevant={} by construction —
scoring it as a miss would punish correct behaviour.
"""
rel = set(q.relevant)
if q.filters:
allowed = {c.id for c in CHUNKS if _matches(c, q.filters)}
rel &= allowed
return rel
def _accepts_qid(retriever: Retriever) -> bool:
"""Toy retrievers take an optional `qid` so the deterministic query vector
can be looked up by eval id. Real retrievers embed `query` text instead —
the harness must not pass kwargs they don't understand."""
try:
return "qid" in inspect.signature(retriever.search).parameters
except (TypeError, ValueError):
return False
def evaluate_query(retriever: Retriever, q: EvalQuery, k: int = 10) -> QueryResult:
kwargs = {"qid": q.qid} if _accepts_qid(retriever) else {}
hits: list[Hit] = retriever.search(q.query, k=k, filters=q.filters, **kwargs)
ranked_ids = [h.id for h in hits]
rel_bin = _binary_relevant(q, None)
expected_empty = (len(_binary_relevant(q)) == 0)
# leak check for filtered queries: did we return ANY chunk the query's
# filters would reject? Checking membership in relevant_unfiltered is not
# enough — that dict only lists the *known-answer* chunks, so a broken
# filter returning a different forbidden chunk (contract-10 instead of
# contract-9) would slip through. Test every returned id against the
# filters themselves; an id we can't find in the corpus can't be verified
# to pass them either, so it counts as a leak.
leaked = bool(q.filters) and any(
cid not in BY_ID or not _matches(BY_ID[cid], q.filters)
for cid in ranked_ids)
metrics = {}
if not expected_empty:
metrics = {
"hit@k": hit_at_k(ranked_ids, rel_bin, k),
"recall@k": recall_at_k(ranked_ids, rel_bin, k),
"precision@k": precision_at_k(ranked_ids, rel_bin, k),
"mrr": mrr(ranked_ids, rel_bin),
"map": _ap(ranked_ids, rel_bin),
"r_precision": r_precision(ranked_ids, rel_bin),
"ndcg@k": ndcg_at_k(ranked_ids, q.relevant, k),
"context_precision": context_precision(ranked_ids, rel_bin),
}
if q.needed:
metrics["needed_recall@k"] = needed_set_recall(ranked_ids, set(q.needed), k)
# else: empty-expected queries get metrics={} — they are excluded from
# EVERY metric average (hit@k/recall@k included). Scoring them 0.0 would
# punish correct abstention/empty behaviour; they are reported via
# n_empty_expected and checked by the leak flag + the failure browser's
# should-have-abstained class instead.
return QueryResult(
qid=q.qid, query=q.query, split=q.split, qtype=q.qtype,
retrieved=ranked_ids, scores=[h.score for h in hits],
relevant=q.relevant, needed=q.needed, filters=q.filters,
metrics=metrics, expected_empty=expected_empty, leaked=leaked,
)
def _ap(ranked: list[str], relevant: set[str]) -> float:
"""Average precision for one query (re-exported name for readability)."""
from metrics import _average_precision
return _average_precision(ranked, relevant)
def run_eval(retriever: Retriever, queries: list[EvalQuery],
k: int = 10) -> list[QueryResult]:
return [evaluate_query(retriever, q, k=k) for q in queries]
# ---------------------------------------------------------------------------
# aggregation
# ---------------------------------------------------------------------------
METRIC_NAMES = ["hit@k", "recall@k", "precision@k", "mrr", "map",
"r_precision", "ndcg@k", "context_precision", "needed_recall@k"]
def aggregate(results: list[QueryResult], metric: str) -> float | None:
"""Mean of `metric` over queries that have it. Empty-expected queries
carry metrics={} so they drop out of every average automatically."""
vals = [r.metrics[metric] for r in results if metric in r.metrics]
if not vals:
return None
return sum(vals) / len(vals)
def aggregate_by(results: list[QueryResult], metric: str,
key: str) -> dict[str, float]:
out: dict[str, list[float]] = {}
for r in results:
if metric not in r.metrics:
continue
out.setdefault(getattr(r, key), []).append(r.metrics[metric])
return {k: sum(v) / len(v) for k, v in sorted(out.items())}
def summarise(results: list[QueryResult], k: int) -> dict:
scored = [r for r in results if not r.expected_empty]
empty = [r for r in results if r.expected_empty]
leaks = [r for r in results if r.leaked]
return {
"n_queries": len(results),
"n_scored": len(scored),
"n_empty_expected": len(empty),
"n_leaks": len(leaks),
"overall": {m: aggregate(results, m) for m in METRIC_NAMES},
"by_split": {m: aggregate_by(results, m, "split") for m in
["recall@k", "mrr", "ndcg@k"]},
"by_type": {m: aggregate_by(results, m, "qtype") for m in
["recall@k", "mrr"]},
}
# ---------------------------------------------------------------------------
# saving runs with provenance
# ---------------------------------------------------------------------------
def _git_commit() -> str:
try:
return subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, timeout=5,
cwd=Path(__file__).parent,
).stdout.strip() or "unknown"
except Exception:
return "unknown"
def evalset_hash(queries: list[EvalQuery]) -> str:
# Fingerprint of the qrels (not of `split` or `qtype`). `save_run` only receives results, so it
# calls the twin `evalset_hash_from_results` below; both hash the same fields in the same order.
blob = "\n".join(
json.dumps({"qid": q.qid, "query": q.query, "relevant": q.relevant,
"needed": list(q.needed), "filters": q.filters},
sort_keys=True) for q in queries
)
return hashlib.sha256(blob.encode()).hexdigest()[:12]
def save_run(results: list[QueryResult], retriever_name: str,
config: dict, path: str | Path, k: int = 10) -> None:
"""One JSONL file: line 1 = run metadata, rest = per-query results."""
meta = {
"type": "meta", "retriever": retriever_name, "k": k,
"config": config,
"evalset_sha": evalset_hash_from_results(results),
"commit": _git_commit(),
"n_queries": len(results),
}
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
f.write(json.dumps(meta) + "\n")
for r in results:
f.write(json.dumps({
"type": "query", "qid": r.qid, "query": r.query,
"split": r.split, "qtype": r.qtype,
"retrieved": r.retrieved, "scores": r.scores,
"relevant": r.relevant, "needed": list(r.needed),
"filters": r.filters, "metrics": r.metrics,
"expected_empty": r.expected_empty, "leaked": r.leaked,
}) + "\n")
def evalset_hash_from_results(results: list[QueryResult]) -> str:
# reconstruct enough of the eval record to fingerprint the qrels
blob = "\n".join(
json.dumps({"qid": r.qid, "query": r.query, "relevant": r.relevant,
"needed": list(r.needed), "filters": r.filters},
sort_keys=True) for r in results
)
return hashlib.sha256(blob.encode()).hexdigest()[:12]
def export_csv(results: list[QueryResult], path: str | Path) -> None:
"""Flat per-query CSV for spreadsheets."""
fields = ["qid", "query", "split", "qtype", "retrieved_top5",
"recall@k", "mrr", "ndcg@k", "needed_recall@k", "leaked"]
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in results:
w.writerow({
"qid": r.qid, "query": r.query, "split": r.split,
"qtype": r.qtype, "retrieved_top5": "|".join(r.retrieved[:5]),
"recall@k": r.metrics.get("recall@k"),
"mrr": r.metrics.get("mrr"),
"ndcg@k": r.metrics.get("ndcg@k"),
"needed_recall@k": r.metrics.get("needed_recall@k"),
"leaked": r.leaked,
})
# ---------------------------------------------------------------------------
# comparing two runs
# ---------------------------------------------------------------------------
def compare_runs(a: list[QueryResult], b: list[QueryResult],
metric: str = "recall@k", n_boot: int = 2000,
seed: int = 0) -> dict:
"""Paired comparison: per-query metric_b - metric_a with a bootstrap CI.
Only queries scored by BOTH runs enter the comparison.
"""
am = {r.qid: r.metrics.get(metric) for r in a if not r.expected_empty}
bm = {r.qid: r.metrics.get(metric) for r in b if not r.expected_empty}
common = sorted(q for q in am if am[q] is not None and bm.get(q) is not None)
diffs = [bm[q] - am[q] for q in common]
mean_d, lo, hi = bootstrap_ci(diffs, n_boot=n_boot, seed=seed)
wins = sum(1 for d in diffs if d > 0)
losses = sum(1 for d in diffs if d < 0)
return {
"metric": metric, "n_paired": len(common),
"mean_a": sum(am[q] for q in common) / len(common),
"mean_b": sum(bm[q] for q in common) / len(common),
"mean_diff": mean_d, "ci95": (lo, hi),
"wins": wins, "losses": losses, "ties": len(diffs) - wins - losses,
"per_query": {q: bm[q] - am[q] for q in common},
}
# ---------------------------------------------------------------------------
# the failure browser
# ---------------------------------------------------------------------------
def failures(results: list[QueryResult], k: int = 10) -> list[QueryResult]:
"""Queries where retrieval 'failed', for human review.
A failure = a scored query whose best possible outcome wasn't achieved:
no relevant item in top-k (miss), OR relevant items present but not all
needed items found (partial). Leaks are always failures. Expected-empty
queries that still returned hits are included as a separate
'should-have-abstained' review class — retrieval always returns k items,
so deciding whether they should have been suppressed is a downstream
(abstention) concern, but a human should look.
"""
out = []
for r in results:
if r.leaked:
out.append(r)
continue
if r.expected_empty:
if r.retrieved:
out.append(r) # should-have-abstained: returned hits anyway
continue
top = set(r.retrieved[:k])
rel = set(r.relevant)
needed = set(r.needed)
recall = r.metrics.get("recall@k", 0.0)
if not (rel & top):
out.append(r) # total miss
elif needed and not (needed <= top):
out.append(r) # partial: missing a needed chunk
elif recall < 1.0:
out.append(r) # some relevant context not retrieved
return outTwo subtleties worth internalising:
_binary_relevantapplies the query's filters to the qrels. Afiltered-emptyquery hasrelevant = {}within the permission boundary — scoring it as a miss would punish correct behaviour. The separateleakedflag checks the opposite failure: did the retriever return any chunk the query's filters would reject? It tests every returned id against_matches— not just membership inrelevant_unfiltered, which only lists the known-answer chunks (a broken filter returningcontract-10instead ofcontract-9would slip through a qrel-membership check). This is the eval-side of the ACL-filtering rule from 06.6: filters are part of the query contract, and the eval must respect them.- Empty-expected queries get
metrics = {}— the convention, stated explicitly. No-answer and filtered-empty queries are excluded from every metric average, hit@k and recall@k included (scoring them 0.0 would punish correct abstention and empty behaviour — a classic way for an eval to report a fall in quality after a retriever starts correctly returning nothing). They're reported vian_empty_expected, checked by the leak flag, and surfaced in the failure browser's should-have-abstained class. Production systems need an abstention mechanism on top — a score threshold tuned on labelled data — which is a Module 07 concern; here we just make sure the eval notices the cases.
4.4 Saving runs with provenance#
Every run record carries enough context to reproduce and compare it later: save_run (in harness.py above) writes one JSONL file — line 1 is the run metadata, the rest are per-query results:
{"type": "meta", "retriever": "dense", "k": 5,
"config": {"k": 5, "prefetch": 20, "rrf_k": 60.0},
"evalset_sha": "7a355ed5b7ab", "commit": "<your commit>", "n_queries": 16}evalset_sha fingerprints the exact qrels; config holds the retriever knobs (k, prefetch, rrf_k, index params, embedding model id+version — the same lineage fields 05.8 puts on chunks); commit ties the run to the code. Two runs are only comparable if evalset_sha matches — comparing across different qrels is comparing different exams.
4.5 Comparing two runs: paired differences and bootstrap#
"Hybrid scored 0.02 higher than dense" means nothing without knowing if it's noise. The fix is a paired comparison: compute the per-query difference metric_b − metric_a on the same queries, then bootstrap it — bootstrap_ci in metrics.py resamples the paired differences with replacement and returns (mean_diff, lo, hi).
Plain-English reading: if the 95% CI for the mean difference excludes zero, the improvement is probably real on this query set; if it includes zero, you can't distinguish the two — either the effect is small or the set is too small. compare_runs pairs only queries scored by both runs and reports wins/losses/ties alongside the CI.
Real output from demo.py (hybrid vs dense on recall@5, k=5, 2000 bootstrap resamples, seed 0):
compare_runs(hybrid vs dense, metric=recall@k):
{
"metric": "recall@k",
"n_paired": 14,
"mean_a": 0.9642857142857143,
"mean_b": 0.9642857142857143,
"mean_diff": 0.0,
"ci95": [
-0.10714285714285714,
0.10714285714285714
],
"wins": 1,
"losses": 1,
"ties": 12
}
per-query diffs (hybrid - dense):
q03: +0.50
q05: -0.50The honest reading: identical means, a CI of ±0.11, one win and one loss — on 14 scored queries we cannot claim hybrid helps at all. That's the correct conclusion, and it's exactly what a 16-query teaching set is sized to show you. On a production set of hundreds of queries the same machinery resolves much smaller effects. (Note n_paired: 14 — the two empty-expected queries are correctly excluded.)
4.6 The failure browser#
Aggregate metrics tell you that you're failing; the failure browser tells you where. failures() (in harness.py above) returns the queries worth a human look — scored misses and partial answers, plus two review classes: leaks (always) and should-have-abstained cases, where an expected-empty query still returned hits.
Real output for the dense retriever at k=5:
failure browser (dense retriever, top-5):
q03 [howto] 'my VPN keeps dropping, what should I try?'
relevant=['help-101', 'help-102'] needed=['help-102'] empty_expected=False leaked=False
got=['help-102', 'help-104', 'contract-10', 'contract-11', 'ticket-77']
q13 [no-answer] 'what is the office wifi password?'
relevant=[] needed=[] empty_expected=True leaked=False
got=['contract-10', 'ticket-78', 'handbook-001', 'handbook-005', 'ticket-77']
q16 [filtered-empty] 'what are the net-30 payment terms?'
relevant=[] needed=[] empty_expected=True leaked=False
got=['help-102', 'help-103', 'help-104', 'handbook-005', 'handbook-002']Three entries, three different lessons. q03 is a scored partial miss: help-102 (the answer) ranked #1, but help-101 (the grade-1 setup context) fell outside top-5, so recall@5 = 0.5 — is that a real problem? For a QA bot, probably not; for a "show me everything relevant" search UI, it is. q13 and q16 are the should-have-abstained class (empty_expected=True, leaked=False): retrieval always returns k hits, so something came back for a query that has no answer and for a query whose answer is forbidden — they aren't scored misses, they're prompts to check your abstention mechanism (a score threshold — Module 07) and your filter path. The failure browser feeds Part 5: you read failures and classify them, you don't just count them.
4.7 End-to-end: three retrievers, one eval set#
demo.py runs dense, BM25 and hybrid over all 16 queries at k=5 and writes runs/{dense,bm25,hybrid}.jsonl + .csv. Headline (real output):
retriever recall@5 mrr ndcg@5 p@5 needed leaks
------------------------------------------------------------------------------
dense 0.964 1.000 0.988 0.229 1.000 0
bm25 0.964 0.917 0.876 0.229 0.923 0
hybrid 0.964 1.000 0.944 0.229 0.923 0Read it the way an engineer should:
- recall@5 identical (0.964) — averaged over the 14 scored queries (the two empty-expected ones are excluded per 4.3); on this toy set all three find the same coverage, and the interesting differences are elsewhere.
- BM25's nDCG (0.876) and MRR (0.917) lag — its ordering is worse even when coverage matches; look at
q15(the Spanish query): dense rankshandbook-001first, BM25 can't match Spanish at all and returnsticket-78top — the multilingual row of the per-type breakdown is where that shows. - needed recall: dense 1.000 vs BM25/hybrid 0.923 — BM25 misses a needed chunk somewhere. Inspect the per-query table: on
q05("why was I charged twice…") the grade-1 context chunkticket-77ranks #1 for BM25 and hybrid while the grade-2 answerticket-78falls below top-5, so needed_recall = 0.0 — the needed-set doing exactly its job (3.7). - leaks: 0 everywhere — the
filtered-emptyqueryq16correctly returns only acme chunks under thetenant=acmefilter; the pre-filter in_matchesdid its job. - p@5 = 0.229 for all — with ~1–2 relevant chunks per query out of 5 returned, precision is inherently low; it's a reminder that k=5 with sparse relevance is mostly noise for the generator.
The per-query table (abbreviated) shows why: dense and BM25 win on different queries — q04 (error code) is easy for both here, q15 is dense-only, q07 (keyword contract terms) is contested — which is the whole argument for hybrid and for per-type reporting.
demo.py — the whole run, printed in full:
# demo.py — run the whole eval: three retrievers over the labelled set.
from __future__ import annotations
import json
from pathlib import Path
from corpus import CHUNKS
from retrievers import DenseRetriever, Bm25Retriever, HybridRetriever
from harness import (
load_evalset, run_eval, summarise, save_run, export_csv,
compare_runs, failures, aggregate,
)
HERE = Path(__file__).parent
QUERIES = load_evalset(HERE / "eval_queries.jsonl")
K = 5
dense = DenseRetriever(CHUNKS)
lexical = Bm25Retriever(CHUNKS)
hybrid = HybridRetriever(dense, lexical)
RUNS = {}
for name, ret in [("dense", dense), ("bm25", lexical), ("hybrid", hybrid)]:
results = run_eval(ret, QUERIES, k=K)
RUNS[name] = results
out = HERE / "runs"
save_run(results, name, {"k": K, "prefetch": 20, "rrf_k": 60.0},
out / f"{name}.jsonl", k=K)
export_csv(results, out / f"{name}.csv")
# ---- headline table ---------------------------------------------------------
print("=" * 78)
print(f"{'retriever':10s} {'recall@5':>9s} {'mrr':>7s} {'ndcg@5':>8s} "
f"{'p@5':>7s} {'needed':>7s} {'leaks':>5s}")
print("-" * 78)
for name, results in RUNS.items():
s = summarise(results, K)
o = s["overall"]
print(f"{name:10s} {o['recall@k']:9.3f} {o['mrr']:7.3f} {o['ndcg@k']:8.3f} "
f"{o['precision@k']:7.3f} "
f"{(o['needed_recall@k'] or 0):7.3f} {s['n_leaks']:5d}")
print()
print("per-query detail (retrieved top-3 vs relevant):")
print(f"{'qid':5s} {'type':13s} {'rel':28s} {'dense top3':38s} {'bm25 top3':38s} {'hybrid top3':38s}")
for i, q in enumerate(QUERIES):
rel = ",".join(f"{c}:{g}" for c, g in q.relevant.items()) or "(none)"
row = f"{q.qid:5s} {q.qtype:13s} {rel:28s}"
for name in ("dense", "bm25", "hybrid"):
top = "|".join(RUNS[name][i].retrieved[:3])
row += f" {top:38s}"
flag = " LEAK" if any(r.leaked for r in (RUNS['dense'][i], RUNS['bm25'][i], RUNS['hybrid'][i])) else ""
print(row + flag)
# ---- paired comparison: hybrid vs dense -------------------------------------
print()
print("=" * 78)
print("compare_runs(hybrid vs dense, metric=recall@5):")
cmp_ = compare_runs(RUNS["dense"], RUNS["hybrid"], metric="recall@k", n_boot=2000)
print(json.dumps({k: v for k, v in cmp_.items() if k != "per_query"}, indent=2))
print("per-query diffs (hybrid - dense):")
for qid, d in cmp_["per_query"].items():
if d != 0:
print(f" {qid}: {d:+.2f}")
# ---- failures ---------------------------------------------------------------
print()
print("=" * 78)
print("failure browser (dense retriever, top-5):")
for r in failures(RUNS["dense"], k=K):
rel = set(r.relevant) & set(r.retrieved[:K])
print(f" {r.qid} [{r.qtype}] '{r.query[:52]}'")
print(f" relevant={sorted(r.relevant)} needed={list(r.needed)} "
f"empty_expected={r.expected_empty} leaked={r.leaked}")
print(f" got={r.retrieved[:K]}")4.8 Cross-checking against standard IR libraries#
metrics.py is written to be read, and to run in CI with zero dependencies. For numbers you will publish, compare with other teams' numbers, or run on large sets, cross-check against (or switch to) the standard tooling — versions are the PyPI releases seen in November 2026:
| Tool | What it is | Use it for |
|---|---|---|
pytrec-eval-terrier 0.5.11 |
Python bindings for the TREC trec_eval evaluation engine |
The reference implementation most papers' numbers come from |
ranx 0.3.21 |
Fast metrics, run/qrels objects, statistical tests and fusion | Day-to-day evaluation and significance tests; documents both nDCG gain conventions |
ir-measures 0.4.3 |
One interface over several metric backends with a compact metric syntax | Switching backends without rewriting your harness |
ir-datasets 0.6.3 |
Loaders for hundreds of public IR collections | Getting BEIR/MS MARCO-style data with qrels in a standard format |
mteb 2.27.8 and beir 2.2.0 |
The embedding-benchmark framework and the BEIR toolkit | Running public benchmarks on a candidate embedding model |
A good habit: take 10 queries from your set, export your runs and qrels in the tools' formats, and check that recall@k, mrr and ndcg match metrics.py once the conventions agree (gain, cutoff, how unjudged and tied documents are treated). A mismatch is nearly always a convention difference, and finding it once saves a wrong conclusion later. (These are listed for orientation; this lesson does not run them, per the module's keyless, no-install rule for the core samples.)
Part 5: Failure analysis#
5.1 The miss taxonomy#
When the failure browser shows a miss, classify it before fixing anything. Each class has a different owner and a different fix:
| Failure class | Symptom | Likely cause | Fix lives in |
|---|---|---|---|
| Not in corpus | No chunk could ever answer | Document missing, wrong source, stale index | 05.9 ingestion |
| Parse/clean failure | Chunk exists but text is garbled, empty, or truncated | OCR error, parser bug, cleaning over-aggression | 05.2–05.5 |
| Chunking failure | Answer split across chunk boundaries; chunk too big/small; wrong unit | Strategy mismatch for the doc type | 05.6–05.7 |
| Embedding mismatch | Right words, wrong vector — paraphrase fails, related-but-different topics win | Wrong model, missing task-type prefix, un-normalised vectors, mixed model versions | 06.1, 06.2 |
| Lexical gap | Exact term/ID/code present but dense retriever can't see it as a string | No lexical channel | 06.7 + 06.8 |
| Filter bug | Right chunk exists but never returned (or wrong tenant's chunk returned) | Filter applied post-retrieval, wrong field, case mismatch, permission cache stale | 06.6 |
| Ranking issue | Relevant chunk retrieved but at rank 8 of 10; reranker made it worse | Stage-1 recall fine, ordering poor; reranker truncating or mis-scoring | 06.4, 06.9 |
| Ambiguous / unanswerable query | Multiple plausible chunks; or genuinely no answer | Query ambiguity; missing abstention | Part 7, Module 07 |
| Label noise | "Miss" is actually a labelling gap — the returned chunk does answer | Unjudged relevant doc ("hole") | Re-grade; pooling |
5.2 The "read 20 failures" workflow#
Metrics get you the list; humans get you the truth. The discipline:
- Pull the failure browser output for your current retriever.
- Read 20 failures end-to-end: the query, the qrels, the top-10 returned with scores, and the chunk texts. Not a sample of 3 — 20, because failure modes hide in the tail.
- For each, write the class from the taxonomy in one word, plus a one-line note ("q14: per-diem chunk retrieved but doesn't say whether receipts stack — label gap, not retriever fault").
- Tally the classes. The fix goes to the most common real class, not the most interesting one. If 12 of 20 are "not in corpus", no retriever tuning will help — fix ingestion.
- Re-grade suspected label noise before counting it as a retriever failure.
5.3 Triage table: symptom → fix#
| You see... | First suspect | Then check |
|---|---|---|
| recall@k low across the board | corpus/chunking/embedding model | failure classes 1–3 |
| recall fine, MRR/nDCG low | ranking stage (index params, reranker) | class 7 |
| only keyword/error-code queries fail | missing lexical channel | class 5 → add BM25/hybrid |
| only paraphrase/conceptual queries fail | embedding model quality | class 4 → better model or HyDE |
| only multilingual queries fail | multilingual model / cross-lingual gap | class 4 → multilingual model |
| filtered queries return wrong-tenant chunks | filter placement/bug | class 6 → pre-filter, audit |
| everything fails after a deploy | embedding model or chunker version changed silently | lineage fields, evalset_sha vs config |
| scores look fine but users complain | eval set doesn't match real query mix | stratify, add production queries |
Part 6: The tuning loop#
6.1 Change one thing at a time#
The golden rule of retrieval tuning, same as any optimisation: one variable per experiment. Change the chunk size AND the embedding model AND add a reranker in one deploy, and when recall improves you won't know which change did it — or which one will hurt next month. Each experiment = one change + one eval run + one recorded result.
flowchart LR
A["baseline eval<br/>recall@k, MRR, nDCG + CIs"] --> B["pick ONE change<br/>from the payoff table"]
B --> C["re-run eval on dev set"]
C --> D{"CI excludes zero<br/>and no regression<br/>on other metrics?"}
D -->|yes| E["keep it; log the experiment"]
D -->|no| F["revert; log the negative result"]
E --> G{"dev set exhausted<br/>or gains plateau?"}
F --> G
G -->|no| B
G -->|yes| H["final run on TEST set<br/>once, to verify"]6.2 The order of typical payoff#
Roughly cheapest-and-highest-impact first — but verify on your data, don't trust the folklore. Each row is a sweep dimension; measure before moving on.
| Order | Change | Typical payoff | Cost | Lesson |
|---|---|---|---|---|
| 1 | Fix parsing/cleaning/chunking | Often the largest — garbage in, garbage out | Low–medium | 05.2–05.7 |
| 2 | Add lexical channel (BM25/hybrid) | Large when queries contain IDs, codes, rare terms | Medium (second index) | 06.7, 06.8 |
| 3 | Add a reranker | Large on rank-sensitive metrics; fixes ordering not coverage | Medium (latency + cost per query) | 06.9 |
| 4 | Tune k and candidate counts | Medium — recall@k vs context budget trade-off | Low | this lesson |
| 5 | Tune index params (efSearch/nprobe) | Medium — recall vs latency on ANN | Low | 06.4 |
| 6 | Pick a better embedding model | Medium–large, but expensive (re-embed everything) | High | 06.1 |
| 7 | Add metadata filters/boosts | Situational — huge for filtered/temporal queries | Medium | 06.6 |
| 8 | Query-side techniques (rewrite, multi-query, HyDE) | Situational — helps hard query types | Medium (extra model calls per query) | Part 7 |
| 9 | Contextual/parent-child chunking | Situational — better context per chunk | Medium–high (re-chunk + re-embed) | 05.7 |
6.3 The sweep script#
A sweep is just the harness inside a loop over configurations. sweep.py sits beside harness.py and eval_queries.jsonl and runs on the dev split only:
# sweep.py — a first sweep: several configurations over the dev queries (pure stdlib)
from pathlib import Path
from corpus import CHUNKS
from harness import load_evalset, run_eval, summarise
from retrievers import DenseRetriever, Bm25Retriever, HybridRetriever
dense, lexical = DenseRetriever(CHUNKS), Bm25Retriever(CHUNKS)
dev_queries = [q for q in load_evalset(Path(__file__).parent / "eval_queries.jsonl")
if q.split == "dev"] # sweep on dev only; test stays untouched
CONFIGS = [
{"name": "dense-k5", "retriever": dense, "k": 5},
{"name": "bm25-k5", "retriever": lexical, "k": 5},
{"name": "hybrid-k5", "retriever": HybridRetriever(dense, lexical), "k": 5},
{"name": "hybrid-k10", "retriever": HybridRetriever(dense, lexical, prefetch=40), "k": 10},
{"name": "hybrid-rrf60", "retriever": HybridRetriever(dense, lexical, rrf_k=60.0), "k": 5},
{"name": "hybrid-rrf10", "retriever": HybridRetriever(dense, lexical, rrf_k=10.0), "k": 5},
]
for cfg in CONFIGS:
res = run_eval(cfg["retriever"], dev_queries, k=cfg["k"])
recall = summarise(res, cfg["k"])["overall"]["recall@k"]
print(f"{cfg['name']:13s} recall@k = {recall:.3f}")
# then compare_runs(best_so_far, res) for the CIdense-k5 recall@k = 0.944
bm25-k5 recall@k = 0.944
hybrid-k5 recall@k = 0.944
hybrid-k10 recall@k = 1.000
hybrid-rrf60 recall@k = 0.944
hybrid-rrf10 recall@k = 1.000Read it with the sweep rules below in mind: hybrid-k10 is not a fair winner, because it also sends twice as many chunks to the LLM (recall@10 versus recall@5 are different budgets), and hybrid-rrf10 gains on a single dev query (q05, where the sharper k lets the dense rank-1 ticket-78 into the top 5). Both gaps rest on one or two queries out of the nine scored dev queries, far inside the noise, which is the point of the next list.
Sweep discipline:
- Sweep on dev, verify on test. The test set stays untouched until you've picked a winner — then run it once to confirm the win generalises. If it doesn't, your dev gains were overfitting.
- Sweep one dimension at a time where possible (k ∈ {3,5,8,10} holding everything else fixed) so effects are attributable; multi-dimensional sweeps need bigger sets to resolve interactions.
- Track every experiment: config, evalset_sha, metrics + CIs, date, outcome (kept/reverted). A shared
experiments.jsonlis enough — this is your retrieval experiment log, and Module 11A will want it for LLMOps. - Cost-aware sweeps: each config has a price — rerankers cost per query, bigger k costs context tokens, more candidates cost latency. A config that's +0.01 recall for +200ms p99 and 3× cost is usually a bad trade; put latency and cost columns next to quality in the results table, not in a footnote.
6.4 Avoiding overfitting to the dev set#
- The dev/test split (2.8) is the primary defence.
- Don't re-use test queries to debug. If a test query fails and you "fix" the retriever for it, that query is now dev — move it or accept the contamination.
- Watch for wins that don't replicate across query types. A change that helps
factoidbut hurtserror-codeis a trade-off to surface, not a number to average away. - The bootstrap CI is your overfitting alarm: if dev says +0.03 ± 0.02 and test says −0.01, you tuned noise.
- Many configurations are many lottery tickets. At a 95% interval, roughly one comparison in twenty excludes zero by chance alone, so a sweep of 20 configurations will usually hand you a "significant" winner even if none is better. Defences: sweep fewer, better-motivated configurations; demand a bigger margin (or a 99% interval) when you compare many; and treat the single test-set run as the real verdict — a dev winner that does not repeat on test was luck.
Part 7: Query-side techniques#
Deep-dive
Everything so far improved the index side. The other lever is the query: rewrite it, expand it, decompose it, route it. Each technique below is taught at the retrieval level (what query goes into search()); the RAG-pipeline view — where these sit relative to answer generation — is Module 07's. Every one is optional plumbing on top of the Retriever protocol: measure each on your eval set before adopting, because the evidence for all of them is mixed and query-type-dependent.
The pattern for all of them: an LLM call transforms the query, then retrieval runs (sometimes several times) and results fuse. query_techniques.py implements them with an injectable llm function and a deterministic FakeLLM.
query_techniques.py — every technique below as runnable code. The model calls go through the injectable llm argument; FakeLLM is the deterministic stand-in, and if __name__ == "__main__" runs the demos you see quoted in each section:
# query_techniques.py — query-side techniques at the retrieval level.
#
# Each technique rewrites or expands the query BEFORE retrieval. The model
# calls are illustrative (a FakeLLM stands in); the fusion is real code.
# Evaluate every technique with harness.py — never assume it helps.
from __future__ import annotations
from dataclasses import dataclass
from retrievers import DenseRetriever, Bm25Retriever, HybridRetriever, rrf, Hit
# --- an injectable LLM function -------------------------------------------------
@dataclass
class FakeLLM:
"""Deterministic stand-in for `client.responses.create(...)`.
In production this is your provider call (lesson 03.x); outputs differ."""
responses: dict[str, str]
calls: list[str] = None # type: ignore[assignment]
def __post_init__(self):
self.calls = []
def __call__(self, prompt: str) -> str:
self.calls.append(prompt)
for key, val in self.responses.items():
if key in prompt:
return val
return ""
# --- 1. query rewriting / normalisation -----------------------------------------
REWRITE_PROMPT = """\
Rewrite this search query into a clean, standalone search query.
Fix spelling, expand abbreviations you are confident about, remove filler.
Output ONLY the rewritten query.
Query: {query}
Rewritten:"""
def rewrite_query(query: str, llm) -> str:
return llm(REWRITE_PROMPT.format(query=query)).strip() or query
# --- 2. multi-query: N paraphrases, retrieve each, fuse with RRF ---------------
MULTI_QUERY_PROMPT = """\
Write {n} different search queries that could find the same answer as:
"{query}"
Vary wording, formality and level of detail. One per line, no numbering.
"""
def multi_query_retrieve(query: str, retriever, llm, n: int = 3,
k: int = 10, qid: str | None = None) -> list[Hit]:
"""Generate paraphrases, retrieve for each, fuse ranked lists with RRF."""
raw = llm(MULTI_QUERY_PROMPT.format(query=query, n=n))
variants = [query] + [line.strip(" -") for line in raw.splitlines() if line.strip()][:n]
rankings = [retriever.search(v, k=k, qid=qid) for v in variants]
return rrf(rankings)[:k]
# --- 3. HyDE: embed a hypothetical answer instead of the question ----------------
HYDE_PROMPT = """\
Write a short passage that would appear in a document answering this question.
Write it as if it were real documentation — specific, factual, in the style of
a handbook. Do not mention the question.
Question: {query}
Passage:"""
def hyde_retrieve(query: str, retriever, llm, k: int = 10,
qid: str | None = None) -> list[Hit]:
"""HyDE (Gao et al., ACL 2023): generate a hypothetical document, embed THAT,
retrieve neighbours. The dense bottleneck filters the hallucinations.
For our toy retriever we approximate by retrieving on the passage text —
with a real embedder you embed the passage, not the question."""
passage = llm(HYDE_PROMPT.format(query=query)).strip() or query
# toy: our dense retriever keys vectors by qid, so we pass the passage as
# the query text to BM25-style lexical matching via the hybrid retriever.
return retriever.search(passage, k=k)
# --- 4. step-back / decomposition for multi-hop ---------------------------------
STEP_BACK_PROMPT = """\
Given this specific question, first write the more general question it depends on,
then the specific question. Format:
GENERAL: <general question>
SPECIFIC: <original question>
Question: {query}
"""
def step_back_retrieve(query: str, retriever, llm, k: int = 10,
qid: str | None = None) -> list[Hit]:
"""Retrieve for BOTH the general and specific formulations, fuse with RRF.
(Zheng et al., ICLR 2024 — arXiv:2310.06117.)"""
out = llm(STEP_BACK_PROMPT.format(query=query))
general = next((l.split(":", 1)[1].strip() for l in out.splitlines()
if l.startswith("GENERAL:")), query)
rankings = [retriever.search(query, k=k, qid=qid),
retriever.search(general, k=k)]
return rrf(rankings)[:k]
# --- 5. conversation-aware queries ------------------------------------------------
STANDALONE_PROMPT = """\
Rewrite the user's latest message as a standalone search query that makes sense
without the conversation history. Output ONLY the query.
History:
{history}
Latest message: {query}
Standalone query:"""
def standalone_query(history: list[dict], query: str, llm) -> str:
hist = "\n".join(f"{m['role']}: {m['content']}" for m in history)
return llm(STANDALONE_PROMPT.format(history=hist, query=query)).strip() or query
# --- 6. query classification / routing -------------------------------------------
CLASSIFY_PROMPT = """\
Classify this search query as KEYWORD (contains identifiers, codes, exact terms)
or CONCEPTUAL (asks about meaning or topics). Answer with one word.
Query: {query}
Class:"""
def route_query(query: str, llm) -> str:
ans = llm(CLASSIFY_PROMPT.format(query=query)).strip().upper()
return "keyword" if "KEYWORD" in ans else "conceptual"
if __name__ == "__main__":
# Deterministic fakes — the "model outputs" below are canned, not real.
llm = FakeLLM({
"VPN keeps dropping": "reconnect the VPN client\nflush the DNS cache\ncontact IT support",
"auto-renew and what are the payment terms":
"GENERAL: master service agreement terms\nSPECIFIC: when does the MSA auto-renew and what are the payment terms?",
"Latest message": "how much vacation do I get?",
"office wifi": "KEYWORD",
})
dense, bm25 = DenseRetriever(), Bm25Retriever()
hybrid = HybridRetriever(dense, bm25)
print("== multi-query on the VPN question ==")
hits = multi_query_retrieve("my VPN keeps dropping, what should I try?",
hybrid, llm, n=3, k=5, qid="q03")
for h in hits[:5]:
print(f" {h.id:14s} rrf={h.score:.4f}")
print("\n== step-back on the multi-hop MSA question ==")
hits = step_back_retrieve(
"when does the MSA auto-renew and what are the payment terms?",
hybrid, llm, k=5, qid="q06")
for h in hits[:5]:
print(f" {h.id:14s} rrf={h.score:.4f}")
print("\n== conversation-aware standalone query ==")
hist = [{"role": "user", "content": "what's our vacation policy?"},
{"role": "assistant", "content": "Employees accrue 1.5 days/month."}]
sq = standalone_query(hist, "and sick leave?", llm)
print(f" standalone: {sq!r}")
print("\n== query routing ==")
print(f" 'VPN-ERR-2041' -> {route_query('VPN-ERR-2041', llm)}")
print(f" 'why was I charged twice' -> {route_query('why was I charged twice', llm)}")7.1 Query rewriting and normalisation#
The cheapest technique: fix spelling, expand abbreviations you're confident about, strip filler, resolve context-dependent references ("and sick leave?" → a standalone query). Sometimes no LLM needed — a synonym table or regex handles the mechanical 80%.
REWRITE_PROMPT = """\
Rewrite this search query into a clean, standalone search query.
Fix spelling, expand abbreviations you are confident about, remove filler.
Output ONLY the rewritten query.
Query: {query}
Rewritten:"""When it helps: typo-heavy queries, abbreviations your corpus spells out, conversational fragments. When it hurts: over-normalisation that strips the exact terms lexical search needs (rewriting "VPN-ERR-2041" into "VPN error" loses the identifier). Eval recipe: run the eval set through rewrite → retrieve vs retrieve and compare per-type — keep it only where it wins.
7.2 Multi-query retrieval#
Generate N paraphrases of the query, retrieve for each, fuse the ranked lists with RRF (06.8). It hedges against one bad phrasing: if the user's wording misses the chunk's vocabulary, a paraphrase may hit it.
MULTI_QUERY_PROMPT = """\
Write {n} different search queries that could find the same answer as:
"{query}"
Vary wording, formality and level of detail. One per line, no numbering.
"""
# multi_query_retrieve() in query_techniques.py (printed in full above):
# paraphrases in -> retriever.search() per variant -> rrf() fusion -> top-k Hits.
# `qid` is a toy-retriever convenience the eval harness uses to look up the
# deterministic query vector; a real retriever ignores it and embeds each
# variant's text instead.Real output (FakeLLM paraphrases of the VPN question, fused through the hybrid retriever):
== multi-query on the VPN question ==
help-102 rrf=0.0656
help-104 rrf=0.0645
ticket-77 rrf=0.0623
contract-10 rrf=0.0474
help-101 rrf=0.0469Cost: N+1 retrievals + 1 LLM call per query — roughly (N+1)× retrieval latency if serial, or ~1× if you asyncio.gather them (03.9). Evidence: helps on vocab-mismatch queries, neutral-to-slightly-negative on easy ones (more candidates = more noise for the reranker). Always measure.
7.3 HyDE — hypothetical document embeddings#
HyDE (Gao, Ma, Lin, Callan — ACL 2023): instead of embedding the question, generate a hypothetical answer passage and embed that. The intuition: a generated passage shares the vocabulary and semantic shape of real answer documents, so it lands nearer them in embedding space than the question does — and the encoder's "dense bottleneck" filters out the passage's hallucinated details.
HYDE_PROMPT = """\
Write a short passage that would appear in a document answering this question.
Write it as if it were real documentation — specific, factual, in the style of
a handbook. Do not mention the question.
Question: {query}
Passage:"""When it helps: zero-shot / weakly-supervised retrieval, queries very different in form from documents (questions vs passages). When it hurts: adds an LLM call per query (latency + cost), can inject confident-sounding wrong details that pull retrieval toward plausible-but-wrong neighbourhoods, and gains shrink as your embedding model improves. Evidence is genuinely mixed — the original paper showed strong zero-shot gains; production reports are more qualified. Eval recipe: hyde_retrieve vs retrieve on dev, per-type breakdown — adopt only where it wins.
7.4 Step-back and decomposition for multi-hop#
Two related ideas for questions that need multiple hops:
- Step-back prompting (Zheng et al., ICLR 2024): derive a more general question the specific one depends on, retrieve for both, fuse. "When does the MSA auto-renew and what are the payment terms?" → general "master service agreement terms" + specific original.
- Decomposition: split a compound question into sub-questions, retrieve each, union the results — effectively multi-hop retrieval without an agent loop.
STEP_BACK_PROMPT = """\
Given this specific question, first write the more general question it depends on,
then the specific question. Format:
GENERAL: <general question>
SPECIFIC: <original question>
Question: {query}
"""Real output on our multi-hop query (fused through hybrid):
== step-back on the multi-hop MSA question ==
contract-9 rrf=0.0328
contract-10 rrf=0.0320
help-102 rrf=0.0312
handbook-002 rrf=0.0161
help-104 rrf=0.0159Both contract clauses surface — exactly the needed-set the query requires. Cost: 1 LLM call + 2 retrievals. Use for multi-hop/multi-field query types; skip for simple factoids (extra latency for nothing).
7.5 Acronym and synonym expansion#
The deterministic cousin of query rewriting: maintain a domain glossary ("PTO" → "paid time off vacation", "MSA" → "master service agreement", "DPA" → "data processing addendum") and expand query terms before retrieval — helps both dense (better embedding input) and lexical (more matching terms) sides. Cheap, no LLM call, fully testable. Failure mode: over-expansion adds noise terms; keep the glossary curated and versioned, and eval each addition.
7.6 Conversation-aware queries#
In a chat interface the latest message is rarely standalone: "and sick leave?" means nothing without history. Condense the conversation into a standalone query before retrieval — the same trick 04.7 uses for context management, applied at the retrieval boundary.
STANDALONE_PROMPT = """\
Rewrite the user's latest message as a standalone search query that makes sense
without the conversation history. Output ONLY the query.
History:
{history}
Latest message: {query}
Standalone query:"""Real output: history about vacation policy + latest "and sick leave?" → standalone 'how much vacation do I get?' (FakeLLM canned; a real model produces the sick-leave equivalent). Cost: 1 small LLM call per turn — cheap insurance against retrieving on fragments. Module 07 owns the full conversational-retrieval design; this is the retrieval-side primitive.
7.7 Query classification and routing#
Not every query wants the same retriever. A cheap classifier (regex heuristics or a small LLM call) routes: identifier-heavy queries (VPN-ERR-2041, invoice numbers) → favour lexical; conceptual queries → favour dense; filtered/temporal queries → apply metadata filters first. The classifier itself is a retrieval component — evaluate it like one (its errors are routing errors).
CLASSIFY_PROMPT = """\
Classify this search query as KEYWORD (contains identifiers, codes, exact terms)
or CONCEPTUAL (asks about meaning or topics). Answer with one word.
Query: {query}
Class:"""Real output on our toy FakeLLM: 'VPN-ERR-2041' -> conceptual, 'why was I charged twice' -> conceptual — the canned fake is deliberately unhelpful here, which is the point: a bad classifier is worse than none. In production, start with a heuristic (does the query contain tokens matching ID patterns / rare capitalised codes?) and only reach for an LLM when heuristics plateau.
7.8 The query-technique scorecard#
| Technique | LLM calls/query | Extra latency | Helps when | Hurts when | Evidence |
|---|---|---|---|---|---|
| Rewrite/normalise | 0–1 | low | typos, abbreviations, fragments | strips exact terms lexical needs | solid for messy queries |
| Multi-query | 1 + N retrievals | medium | vocab mismatch, ambiguous phrasing | easy queries (noise) | mixed; measure |
| HyDE | 1 | medium | zero-shot, question↔passage gap | latency budget tight, weak embedder | mixed; paper strong, prod qualified |
| Step-back/decompose | 1–2 | medium | multi-hop, compound questions | simple factoids | positive on multi-hop sets |
| Acronym/synonym expansion | 0 | ~0 | domain jargon, abbreviations | over-expansion noise | solid if curated |
| Conversation-aware | 1 | low | chat interfaces | single-shot search | solid for chat |
| Query routing | 0–1 | low | mixed query types | classifier errors | solid with good heuristic |
The meta-rule: every technique is a hypothesis. Add it, eval it on dev per-type, keep it only where the CI says it wins, and record it in the experiment log like any other change.
Part 8: Online evaluation and monitoring#
The offline eval set is your lab; production is the field. You can't put every query through a labelled harness, but you can watch the signals that tell you retrieval is degrading before users complain. This part is awareness-level — Module 10A owns eval methodology (10A.9 covers offline versus online evaluation in full: signals, A/B tests, shadow mode and drift) and Module 11A owns observability platforms. 07.9, Part 8 adds the RAG-specific signals.
8.1 The signals#
| Signal | What it tells you | Caveats |
|---|---|---|
| Click-through / result selection | Users picking result 1 vs scrolling = rank quality proxy | Position bias (users click top regardless); needs randomisation or interleaving (mix the two rankers' results into one list shown to the same user and credit clicks to whichever ranker contributed the clicked result) to debias |
| Explicit feedback (thumbs, "was this helpful") | Direct but sparse and biased | Self-selected; treat as directional |
| Zero-result rate | Queries returning nothing — recall failures or corpus gaps or filter bugs | Spikes can mean corpus loss, index corruption, or a filter regression |
| Reformulation rate | Users re-asking differently = first retrieval missed | Strongest cheap signal of retrieval failure |
| Abandonment / downstream answer quality | Users leaving or complaining after retrieval | Confounded with generator quality — check retrieval first |
| Latency/error dashboards | p95/p99, timeout rate, embed API errors | Operational, not quality — but a retrieval outage looks like quality loss |
8.2 Query logs and privacy#
Logging queries is how you find real failure modes — and a privacy minefield. Rules:
- Log the minimum: query text (or a hash), timestamp, result ids, click/feedback — not full document contents or user identifiers you don't need.
- Hash or truncate if privacy policy forbids raw queries; you lose debuggability but keep aggregate signal.
- Retention limits: query logs are personal data in many jurisdictions; set TTLs and honour deletion requests (the same erasure obligations that hit vectors in 02.3, 10.7).
- Never log secrets: API keys, tokens, PII users paste into queries — scrub before storage.
8.3 A/B tests and canary queries#
- A/B retrieval changes like any ranking change: route a percentage of traffic to the new retriever, compare online metrics (CTR, reformulation, zero-result rate) and guardrail metrics (latency, cost). Offline eval says "should work"; A/B says "does work for real users". Small effects need large traffic — same statistics as the bootstrap CI, bigger n.
- Canary queries: a fixed set of ~20–50 known-answer queries run continuously against production. They're your smoke test — if
q04-equivalent stops returninghelp-104after a deploy, page someone before users do. This is the production version of the sanity queries 06.2 recommends after each index build.
8.4 Drift detection#
Retrieval quality drifts without any code change:
- Corpus drift: new documents shift IDF, change what's "relevant", introduce topics the eval set never covered.
- Embedding drift: provider silently updates a model version (check 06.1's versioning rules — pin versions, store model id+version per vector); your vectors and queries must stay in the same space.
- Query drift: users start asking about a new product feature; the eval set doesn't cover it.
- Index drift: deletes accumulate, segments merge, recall degrades silently.
Detection: track the online signals above over time; periodically re-run the offline eval on a fresh query sample; alert on zero-result-rate and canary-query failures. The eval set itself needs scheduled refresh — add production failure queries monthly, retire stale ones.
8.5 Feeding production failures back into the offline set#
The loop that keeps the lab honest:
- Mine production logs for reformulations, zero-results, and negative feedback.
- Hand-pick ~10–20 per month, label them (spans → chunks, per 2.7), add to the eval set with
source: productionand today's date. - Re-run the eval — production failures become regression tests. A retriever change that fixes them gets credit; one that breaks them gets reverted.
- This is also how the eval set grows toward the real query distribution instead of the distribution you imagined at launch.
Part 9: Retrieval for different goals#
Deep-dive
"Good retrieval" is goal-dependent — the same retriever can be excellent for one use and wrong for another. Define relevance against the task:
| Goal | What "relevant" means | Metrics that matter | Notes |
|---|---|---|---|
| Question answering / RAG | Chunks containing the answer | recall@k at context size, needed-set recall, context precision | Coverage ceiling; precision secondary to recall |
| Search UI / findability | Chunks a user would click | MRR, nDCG, precision@k | Rank-1 and ordering dominate; diversity matters |
| Recommendations / "related content" | Items similar to a seed | recall of held-out interactions, diversity (MMR — 06.3) | Different relevance model entirely — collaborative or semantic |
| Deduplication / clustering | Near-duplicate pairs | pairwise precision/recall at a similarity threshold | Not ranked retrieval — threshold tuning on pairs (02.3, 8.2) |
| Classification / routing | Correct label via nearest-centroid or kNN | accuracy on labelled examples | Embeddings as features, not search (02.3, 8.2) |
Three cross-cutting cases:
- Long-tail queries. Rare intents dominate failure counts while contributing little to the mean — stratify your eval set by frequency and by type, and report the tail separately. A retriever that's +0.05 overall but −0.3 on rare queries is a regression for the users who need it most.
- Multilingual retrieval. Evaluate per language, not just overall — a model can be strong in English and weak in your second language. Our
q15(Spanish) is the toy version: dense handles it, BM25 can't. Real multilingual eval needs per-language qrels (MIRACL is the standard testbed) and language-stratified reporting. - Multimodal retrieval. Searching images/audio/video alongside text (text→image, image→image) is a different embedding space and a different eval — Module 09 previews the applications; the eval principles here carry over unchanged (qrels per modality, same metrics).
Part 10: Public benchmarks and how to use them#
Reference
Public benchmarks exist to compare models, not to replace your eval set. Know what each is good for:
| Benchmark | What it is | Scale | Use it for | Caveats |
|---|---|---|---|---|
| BEIR (github.com/beir-cellar/beir, Apache-2.0) | Heterogeneous zero-shot IR benchmark — diverse datasets (MSMARCO, NQ, HotpotQA, FiQA, SciFact, TREC-COVID, NFCorpus, ...) across domains/tasks | ~18 datasets originally; the repo now ships "15+"/17 preprocessed sets and added multilingual data (mMARCO, Mr.TyDi); NeurIPS 2021 Datasets & Benchmarks; SIGIR 2024 "Resources for Brewing BEIR" maintains an official leaderboard | Comparing embedding/retrieval models zero-shot; sanity-checking a model choice before your own eval | Zero-shot only (no task-specific training signal); dataset mix ≠ your domain; scores don't transfer to your corpus |
| MTEB (leaderboard, arXiv:2210.07316) | Massive Text Embedding Benchmark — hundreds of tasks incl. retrieval, classification, clustering, reranking, across languages | Task count grows continuously; check the live leaderboard | The broadest model-selection signal for embedding models; 02.3, 7.4 covers its caveats (self-reported, contamination, task mix) | Retrieval is one task family among many; aggregate scores hide per-task weakness — read the retrieval subsets |
| MS MARCO (microsoft.github.io/msmarco, arXiv:1611.09268) | ~1.01M real Bing queries, 8.8M passages; passage ranking in full-ranking and reranking subtasks; drove the TREC Deep Learning Track | Large | The classic ad-hoc retrieval testbed; training/fine-tuning retrieval models | Web-search distribution, not enterprise docs; labels are sparse (often 1 relevant per query); the original passage-retrieval leaderboard page was retired — check current task status before citing numbers |
| RTEB (Retrieval Embedding Benchmark, introduced by Hugging Face / the MTEB maintainers as a beta in October 2025; announcement) | Retrieval-only benchmark that combines public datasets with private held-out datasets run by the maintainers, to resist overfitting and training-set contamination | Appears in the Retrieval section of the MTEB leaderboard | A less gameable second opinion on embedding models for retrieval | Newer and still evolving; check its current dataset list and status; private sets mean you cannot inspect them |
| BRIGHT (arXiv:2407.12883, ICLR 2025) | 1,384 queries (per the paper's current version) in economics, psychology, maths, coding and more, where finding the right document needs reasoning, not keyword or semantic matching | Small, hard | Showing the ceiling of retrieval on reasoning-heavy queries; testing query-rewriting/reasoning-augmented retrieval | Numbers differ across paper versions; the paper reports that top MTEB models score far lower here (around 18 nDCG@10 for the MTEB leader), so it is a stress test, not a model-selection score |
| MIRACL (miracl.ai, aclanthology.org/2023.tacl-1.63) | Multilingual ad-hoc retrieval: ~78k queries, ~726k judgments over Wikipedia in 18 languages, monolingual (query and corpus same language) | 18 languages | Evaluating multilingual retrieval per language; the standard for "does this embedding model handle language X" | Wikipedia domain; monolingual only (cross-lingual is a different, harder task); low-resource languages have thin judgments |
How to use them, honestly:
- For model selection only. BEIR/MTEB tell you "model A is probably better than model B zero-shot on some tasks" — a prior for which 2–4 models to put on your own eval set (06.1's selection process). They do not tell you which is best for your corpus.
- Never as a substitute for your eval set. A model that wins BEIR can lose on your domain-specific vocabulary; a model that's mid-table overall can be best on your niche. Your labelled set is the only evidence that counts for shipping.
- Read the leaderboard's date and task mix. Leaderboards evolve; a score from a different task suite or an old model version is not comparable. Verify current state on the live pages — these are volatile facts.
- Watch for contamination and self-reporting. MTEB's caveats (02.3, 7.4) apply to all public benchmarks: some datasets leak into training corpora, and vendor-submitted scores aren't independently verified.
Part 11: Module wrap-up and handoff to Module 07#
Deep-dive
11.1 The retrieval-quality checklist#
One page, before you ship or change anything:
- Eval set exists: ≥30 queries (aim 100+), stratified by type, graded relevance, dev/test split, versioned (
evalset-vN+ sha) - Labels are spans, not chunk IDs — survive re-chunking (2.7)
- Qrels respect the permission boundary — filtered queries evaluated within filters; leak checks pass
- Headline metric: recall@k at your real context size k; rank metrics (MRR/nDCG) alongside; per-type breakdown reviewed
- Latency + cost measured: p50/p95/p99 and cost/query in the results table
- Comparisons are paired with bootstrap CIs — no naked deltas
- Failures classified: the miss taxonomy applied; fixes routed to the right module
- One change per experiment, logged with config + evalset_sha + outcome
- Test set untouched until final verification
- Production signals wired: canary queries, zero-result rate, reformulation monitoring, feedback loop into the eval set
11.2 The retriever contract for Module 07#
Module 06 ends where Module 07 begins. The retriever this module built is the component RAG calls to get grounding material. The contract Module 07 consumes:
from retrievers import Hit # the dataclass defined in retrievers.py (4.1)
def search(query: str, k: int = 10,
filters: dict | None = None) -> list[Hit]: ...Each Hit carries everything downstream stages need:
| Field | Why Module 07 needs it |
|---|---|
id |
Stable chunk identity — for citations, dedup, provenance |
score |
Retriever-specific rank signal — for thresholding/abstention decisions (per-model, tuned on labelled data) |
text |
The chunk content placed into the LLM's context |
metadata |
doc_id, section/breadcrumbs, tenant, lang, dates, page/bbox — for citation display, filtering, freshness, ACL |
source |
Provenance: which stage produced the hit ("dense", "bm25", "rrf", "reranker:...") — for citations, debugging, and the "which side supplied the winning result" monitoring 06.8 describes |
What Module 07 adds on top: query understanding and rewriting for the answer (not just retrieval), hybrid retrieval strategy at pipeline level, grounding prompts and citations, advanced RAG patterns (parent-child expansion, self-RAG, corrective RAG), and RAG evaluation in depth — faithfulness, answer relevance, citation accuracy: 07.9 is the first pass (it builds the docs_qa/eval/ harness) and 10A.6 is the full treatment, which Module 10A completes. This lesson gave you the retrieval metrics and harness those evals build on: the same Retriever protocol, the same eval-set machinery, extended one level up the stack.
Failure gallery#
The ways retrieval evaluation itself goes wrong — each row is a mistake that produces confident, wrong numbers:
| Failure | What you see | Root cause | Fix |
|---|---|---|---|
| Tuning and evaluating on the same synthetic queries | Dev gains evaporate on test/production | Synthetic questions copy chunk vocabulary; the retriever is tuned to them | Paraphrase prompts + leakage checks (2.2); dev/test split (2.8); feed production queries back in (8.5) |
| Ignoring unjudged "holes" | A better retriever scores worse | Its top results were never labelled → scored as irrelevant | Pooling; treat unjudged as a third state; re-grade before comparing (3.11) |
| Averaging recall over very different relevant-set sizes | One number hides per-type disasters | recall@k granularity differs per query; the mean is dominated by the common type | Stratify by query type; report per-type (2.4, 3.11) |
| Changing chunking, keeping chunk-ID qrels | Every label orphans after a re-chunk | Qrels reference unstable chunk IDs | Label answer spans in the source; derive chunk qrels at eval time (2.7) |
| Reporting one number without a confidence interval | "+0.02 recall" ships; it was noise | Small eval sets have wide variance; naked deltas can't distinguish signal from luck | Paired per-query diffs + bootstrap CI (4.5) |
| Tuning k on the dev set only | Dev winner fails on the untouched test set | Overfitting the exam | Sweep on dev, verify once on test (2.8, 6.4) |
| Leak check that only knows the qrels | Cross-tenant chunk returned; metrics look fine | Checking returned ids against relevant_unfiltered misses forbidden chunks that aren't known answers |
Test every returned id against the query's filters (_matches) — 4.3 |
| Scoring empty-expected queries as misses | Correct abstention/empty results drag recall down | Forced 0.0 into the averages | metrics = {} convention — excluded from every average, checked via leak + should-have-abstained classes (4.3, 4.6) |
| Counting label noise as retriever failure | "Misses" that are actually correct answers | An unjudged chunk did answer; the label was the gap | Re-grade suspected holes before tallying classes (5.2) |
What to fix first#
| The eval shows... | Suspect first | Then check |
|---|---|---|
| recall@k low across the board | corpus / chunking / embedding model | failure classes 1–3 in 5.1 |
| recall fine, MRR/nDCG low | ranking stage (index params, reranker) | class 7 |
| only keyword/error-code queries fail | missing lexical channel | class 5 → add BM25/hybrid |
| only paraphrase/conceptual queries fail | embedding model quality | class 4 → better model or HyDE |
| filtered queries return wrong-tenant chunks | filter placement/bug — or a leak-check hole | class 6 → pre-filter, audit, verify the eval's leak check |
| everything fails after a deploy | embedding model or chunker version changed silently | lineage fields, evalset_sha vs config |
| scores fine but users complain | eval set doesn't match the real query mix | stratify, add production queries |
Decision table#
| Situation | Reach for | Because |
|---|---|---|
| Picking the headline retrieval metric | recall@k at your real context size k | It bounds what the LLM can possibly answer with |
| Judging whether a reranker earns its latency | paired per-query diff on nDCG/MRR + bootstrap CI | Rerankers fix position, not coverage — measure rank-sensitive metrics |
| Deciding if a query technique (HyDE, multi-query, step-back) helps | per-type recall@k and latency on the dev split | Techniques help specific query types; adopt only where the CI excludes zero |
| "Is the list noisy / burning context tokens?" | precision@k | Junk chunks cost LLM tokens and dilute attention |
| Multi-chunk answers ("needs both clauses") | needed-set recall | Plain recall can't tell a half-answer from a miss |
| Graded labels available | nDCG@k | The only metric that sees grades and full ordering |
| Comparing two runs or configs | compare_runs + bootstrap CI, never naked deltas |
Small eval sets make un-intervalled differences noise |
| Tuning a knob (k, weights, index params) | sweep on dev, verify once on test | Tuning on the test set overfits the exam |
| No-answer / filtered-empty queries | leak flag + should-have-abstained review; excluded from averages | Scoring them as misses punishes correct behaviour |
| Choosing the context size k | recall@k plateau vs latency/cost budget | Past the plateau you're paying tokens for noise |
| Deciding whether to trust a benchmark number | your own stratified eval set | Leaderboards measure their task mix, not yours |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A higher retrieval score means better answers." | Retrieval bounds answer quality — the answer can only come from retrieved chunks — but a strong generator can compensate for mediocre retrieval and a weak one wastes perfect retrieval. Track both levels separately. |
| "Recall@10 is the number that matters." | It matters only if you actually send 10 chunks to the LLM. Evaluate at your real context size k (often 3–8); recall@50 flatters systems whose relevant chunks sit at rank 30. |
| "More eval queries is always better." | Effective sample size is what matters — 20 rephrasings of one question ≈ 1 independent sample. Stratify by type and dedupe near-identical queries before counting n. |
| "The benchmark leaderboards tell us which embedding model to use." | They compare models zero-shot on their task mix. Your domain eval set is the only evidence that counts for shipping — benchmarks pick the shortlist, your data picks the winner. |
| "If two systems differ by 0.02, the higher one is better." | On small eval sets that's noise. Always compare with a confidence interval; if the CI includes zero you can't distinguish them. |
| "Synthetic questions are a free eval set." | They leak: generated questions copy chunk vocabulary, so lexical search looks artificially good and paraphrase robustness is never tested. Paraphrase prompts + leakage checks required. |
| "Chunk IDs are stable labels." | They change on every re-chunk. Label answer spans in the source document and derive chunk qrels at eval time — or every re-chunk orphans your labels. |
| "Precision and recall move together." | They're in tension: return fewer results → precision up, recall down; return everything → recall up, precision/latency/cost down. Read them together, never alone. |
| "Scores can be thresholded for 'no answer'." | Scores aren't probabilities and distributions differ per model/query/corpus. Tune any abstention threshold on labelled data — and that's a Module 07 mechanism, not a metric. |
| "HyDE/multi-query/reranking always help." | All are hypotheses. Each adds latency and cost; each helps some query types and hurts others. Measure per-type on your eval set before adopting. |
| "You can tune on the test set to check progress." | The test set is for final verification only. Tuning on it contaminates it — your "improvement" is overfitting to the exam. |
| "An empty result on a no-answer query is a retrieval failure." | For no-answer and filtered-empty queries, returning nothing is the correct answer. The eval excludes them from every metric average and instead checks leaks and surfaces should-have-abstained cases for review. |
Key takeaways#
- Good retrieval = coverage + position + purity. recall@k at your real context size is the coverage ceiling for RAG; MRR/nDCG measure position; precision@k measures junk.
- Evaluate retrieval separately — it's cheap, deterministic, and isolates blame. Three levels: component, pipeline, end-to-end (Module 10A).
- An eval set = queries + qrels. Source queries from logs, tickets, experts and synthetic data (with leakage checks); 30–100 to start, stratified by type; graded relevance beats binary for nDCG.
- Label spans, not chunk IDs — char offsets into the source survive every re-chunk.
- Dev/test split is non-negotiable — tune on dev, verify once on test.
- The harness is the deliverable:
Retrieverprotocol → runner → per-query metrics → provenance-stamped runs → paired bootstrap-CI comparison → failure browser (scored misses, leaks, and should-have-abstained cases). - Failure analysis beats metric-watching: classify misses (not-in-corpus → parse → chunking → embedding → lexical → filter → ranking → ambiguous → label noise), fix the most common real class.
- Tune one change at a time in payoff order: chunking → hybrid → reranker → k/candidates → index params → embedding model → filters → query techniques → contextual chunking.
- Query-side techniques are optional, measured plumbing — rewrite, multi-query, HyDE, step-back, expansion, conversation-aware, routing. Each costs latency; adopt only where the CI says it wins.
- Online signals close the loop: canary queries, zero-result rate, reformulation, A/B tests, drift detection, and feeding production failures back into the eval set.
- Benchmarks pick the shortlist; your eval set picks the winner. Prefer benchmarks with held-out data (RTEB) as a second opinion, and treat BRIGHT-style reasoning benchmarks as stress tests.
- LLM judges can scale labelling, but only after you measure them against humans (kappa at graded and binary level, frozen judge version in the run record); and check the nDCG gain convention before comparing numbers across tools.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Qrels | Query relevance judgments: which corpus items are relevant to each eval query, and how much |
| Hit rate / success@k | 1.0 if any relevant item appears in the top-k, else 0.0 |
| Recall@k | Fraction of all relevant items found in the top-k |
| Precision@k | Fraction of the top-k that is relevant |
| MRR | Mean reciprocal rank: average of 1/rank of the first relevant item |
| MAP | Mean average precision: AP averaged across queries |
| nDCG@k | Normalised discounted cumulative gain: graded relevance with exponential gains and rank discounts |
| R-precision | Precision at rank R, where R = number of relevant items |
| Needed-set recall | Fraction of the minimal answer-bearing chunk set found in top-k |
| Context precision/recall | RAG-eval metrics over the retrieved context (RAGAS-style); recall is claims-based and needs an LLM |
| Cohen's kappa | Inter-labeller agreement statistic beyond chance |
| Bootstrap confidence interval | Resample-based CI for a mean difference; excludes zero ⇒ likely real effect |
| Paired comparison | Comparing two systems on the same queries via per-query differences |
| Eval set / dev / test split | Labelled queries for tuning (dev) vs final verification (test) |
| Graded relevance | Relevance as grades (e.g. 0/1/2) rather than binary relevant/not |
| Label span | Char-offset answer location in the source document, mapped to chunks at eval time |
| Unjudged documents / "holes" | Relevant items never labelled, scored as irrelevant and distorting metrics |
| Pooling | Grading the union of what multiple retrievers return (TREC method) |
| Canary queries | A fixed known-answer query set run continuously against production |
| Zero-result rate | Fraction of queries returning no results — a retrieval-health signal |
| Reformulation rate | How often users re-ask differently — a proxy for retrieval failure |
| Retriever protocol | search(query, k, filters) -> list[Hit] — the contract all retrievers satisfy |
| Hit | One retrieved result: id, score, text, metadata, source (provenance: which stage produced it) |
| HyDE | Hypothetical Document Embeddings: embed a generated answer passage instead of the question (Gao et al., ACL 2023) |
| Multi-query retrieval | Generate N paraphrases, retrieve each, fuse with RRF |
| Step-back prompting | Derive a more general question to retrieve alongside the specific one (Zheng et al., ICLR 2024) |
| Query routing | Classify queries and send each type to its best retriever configuration |
| BEIR / MTEB / MS MARCO / MIRACL | Public retrieval benchmarks for model selection (heterogeneous zero-shot / massive embedding tasks / Bing passage ranking / 18-language Wikipedia) |
| RTEB / BRIGHT | A retrieval benchmark with private held-out datasets (anti-contamination) / a reasoning-intensive retrieval benchmark |
| LLM relevance assessor | An LLM that grades (query, passage) pairs with a rubric to extend human labels; trust only after measuring agreement with humans (UMBRELA is an open reproduction) |
| nDCG gain convention | Exponential 2^grade − 1 (used here, also ndcg_burges in ranx) vs linear grade; the two give different scores on graded labels |
All terms are also collected in the glossary.
Exercises#
Run the code and experiment:
- Metrics by hand (Part 3): on the worked example, compute
recall@5,precision@5, andhit@1by hand before runningmetrics.py. Which metric changed most when you movedc2from rank 4 to rank 2? Why? - The re-chunking fix (2.7): modify
spans.pyto userechunk(SOURCE, 200)(smaller windows). Confirm the span labels still resolve correctly while naive chunk-ID labels would all orphan. What happens when a span crosses a chunk boundary — which chunks get marked, and is that right? - Harness end-to-end (Part 4): run
demo.py. Then changeK = 5toK = 3indemo.pyand re-run. Which metrics moved most, and does the ranking of the three retrievers change? Explain using the metric definitions. - Bootstrap intuition (4.5): in
compare_runs, setn_boot=100vsn_boot=5000. How stable is the CI? Then artificially duplicate the eval set 5× (same queries, but give each copy uniqueqids such asq01#0,q01#1) — does the CI narrow? Should it? (It shouldn't — effective n didn't change. Explain why the bootstrap does narrow anyway, and what that reveals about bootstrap limitations on duplicated data.) - A real failure (Part 5): pick the worst-scoring query type in the per-type breakdown. Trace one failure through the taxonomy: is it corpus, chunking, embedding, lexical, filter, ranking, ambiguity, or label noise? Propose the fix and the lesson it belongs to.
- Sweep (Part 6): extend
CONFIGSin the sweep sketch withhybridatprefetch=10vsprefetch=40. Which direction does recall@k move, and what does that tell you about candidate-set depth vs fusion quality? - Query technique eval (Part 7): implement
hyde_retrievefor real: use theBm25Retrieveron the generated passage as the query (the toy stand-in). Evaluatehydevsdenseon theambiguousandmultilingualquery types only. Does it help? What would you need to measure on a real embedder? - Leak check (4.3): temporarily remove the
filtersargument inevaluate_query'sretriever.searchcall and re-rundemo.py. What happens toq16'sleakedflag and then_leakscount? What does that teach you about where filtering must live? - Judge audit (2.9): extend
judge.py's sample to 12 pairs, include two pairs where the passage shares many words with the query but does not answer it, and compute graded and binary agreement with your own grades. Where does the keyword fake fail, and what would you change in the rubric or prompt for a real model?
Hints and what you should see
- Ranking
c1, c4, c3, c2, c5: recall@5 = 4/4 = 1.0, precision@5 = 4/5 = 0.8, hit@1 = 1.0. After movingc2from rank 4 to rank 2 (c1, c2, c4, c3, c5) only nDCG changes (0.955 → 0.931): all four relevant chunks were already in the top 4, so every binary metric is blind to their order, and the grade-2 chunkc3now sits lower, which only a graded, position-discounted metric can see. - With 200-character windows the 309-character source becomes two chunks,
handbook-r0andhandbook-r1.q01still resolves to['handbook-r0'], andq11's span (the parental-leave paragraph to the end) crosses the boundary, so both chunks are marked relevant. That is right for relevance (either half alone may miss part of the answer) but it meansneededfor that query should be treated as both chunks — a good reason to record spans per answer part. - Real output with
K = 3: dense recall 0.964, BM25 and hybrid 0.929 (both lose one query's coverage); precision rises (0.381 dense, 0.357 BM25/hybrid, as fewer slots are filled with junk); MRR is unchanged (it ignores k beyond the first hit); nDCG@3 is 0.988 / 0.868 / 0.936. The ranking of the retrievers by recall now separates dense from the other two — exactly the effect of a smaller context window. - For
hybrid vs dense,n_boot=100gives[-0.107, 0.071]andn_boot=5000gives[-0.107, 0.107]— few resamples give a ragged interval, so use at least 2,000. Five copies with unique ids given_paired = 70and a CI of about[-0.043, 0.043](roughly 1/√5 as wide). It narrows because the bootstrap treats the 70 rows as independent, although they are 14 queries repeated: this is the "effective sample size" warning of 2.3 made visible. (If you reuse the originalqids,compare_runskeys its dictionaries byqid, the copies collapse and nothing changes.) - Example: if
multi-hophas the lowest per-type recall, traceq06: both contract clauses are needed, BM25 putscontract-9first andcontract-10third — a ranking/needed-set issue, not corpus or chunking. Candidate fixes: step-back/decomposition (7.4) or a reranker (06.9). - In this 14-chunk corpus
prefetch=10andprefetch=40give identical results (recall@5 0.964, MRR 1.000): the candidate pool already covers nearly the whole corpus, so depth cannot matter. Candidate depth is a recall decision that only bites when the corpus is much larger than the prefetch — which is why you must re-run this on a realistic corpus size. hyde_retrievesearches with the generated passage instead of the question. With the toy corpus the vectors are keyed by eval id, so the gain you see is the toy's, not a real embedder's; on a real embedder compare per-type recall@k with CIs, and also record the extra LLM latency and cost per query.- With
filtersremoved, the acme user'sq16gets initech chunks back: the dense retriever returnscontract-9,contract-11,contract-10, and BM25 and hybrid also putcontract-9first.leakedbecomesTrueandn_leaksrises above 0 for each retriever. Lesson: filtering must live inside the retriever (pre-filter, 06.6); an eval that only scores relevance would never notice, which is why the leak check tests every returned id against the filters. - Expect the keyword fake to over-grade keyword-overlap distractors (it cannot tell "mentions vacation" from "answers how much vacation") — binary agreement stays high while graded agreement falls. For a real model, tighten the rubric ("2 = states the number or rule that answers the query; mentioning the topic is at most 1"), add two worked examples to the prompt, and re-measure kappa on a fresh sample.
Check yourself#
- What are the three claims that make up "good retrieval", and which metric family measures each?Coverage (did the right chunks appear at all — recall@k/needed-set recall), position (how high — MRR/nDCG), purity (how much junk — precision@k).
- Why is retrieval evaluated separately from answer quality, and what are the three levels of evaluation?Retrieval eval is cheap, deterministic and isolates blame (retriever vs generator). The three levels: component (retriever alone), pipeline (retriever + reranker/filters), end-to-end (answer quality — Module 10A).
- What are qrels, and why is graded relevance (0/1/2) more informative than binary for nDCG?Qrels are per-query labels of which corpus items are relevant and how much. Graded relevance lets nDCG weight "the answer" above "useful context" and lets metrics distinguish partial from complete coverage.
- What's the re-chunking problem, and what's the robust fix?Chunk IDs change on every re-chunk, orphaning labels. Fix: label answer-bearing char spans in the source document and map spans→chunks at eval time.
- What's the difference between
relevantandneededin an eval query, and which metric usesneeded?relevant= all chunks a labeler marked useful (grades 1–2);needed= the minimal set that actually answers.needed_set_recallusesneeded— it catches half-answers that recall@k onrelevantcan mask. - Why does recall@k at your actual context size matter more than recall@50 for RAG?Because the LLM can only use retrieved chunks: relevant chunks at rank 30 of a k=50 list never reach a k=5 context window. recall@k must be measured at the k you actually send downstream.
- What does MRR measure that recall@k doesn't, and vice versa?MRR cares only about the first relevant item's rank (search UX); recall@k cares about all relevant items being retrieved (RAG coverage). MRR is blind to misses below the first hit; recall is blind to ordering.
- Why can't you compare a retriever's raw scores across systems or queries?Scores are retriever-specific and query-specific: cosine, BM25 and RRF scores live on different scales, and the same retriever's score distribution shifts per query. Metrics are rank/set-based precisely because raw scores can't be compared.
- What is a "hole" in an eval set, and how does pooling mitigate it?A "hole" is a relevant item that was never labelled, so it's scored as irrelevant — distorting metrics downward and hiding true quality. Pooling (grading the union of what all retrievers return, TREC-style) reduces holes.
- Why is a paired bootstrap CI better than comparing two mean scores?It isolates the per-query effect and quantifies uncertainty: the CI tells you whether the mean difference is distinguishable from zero, which two bare means can't.
- Name three query-side techniques and one situation where each helps.Multi-query (vocab mismatch), HyDE (question↔passage form gap / weak supervision), step-back/decomposition (multi-hop), acronym expansion (domain jargon), conversation-aware (chat fragments), query routing (mixed query types). Each helps specific types — measure per-type.
- What's the difference between the dev set and the test set, and what happens if you tune on the test set?Dev is for iterating/tuning; test is for one final verification. Tuning on test overfits the exam — improvements don't generalise to real queries.
- Which public benchmarks are best for (a) multilingual retrieval, (b) broad embedding-model selection, and (c) ad-hoc passage ranking — and what is each not for?(a) MIRACL (18 languages, monolingual Wikipedia); (b) MTEB (broadest task coverage); (c) MS MARCO (Bing passage ranking, TREC DL heritage). None replaces your own domain eval set — they pick the shortlist, your data picks the winner.
- What does the
filtered-emptyquery type test, and why is it an eval concern rather than just a filter concern?It tests whether the system returns forbidden chunks to a filtered query (cross-tenant leak) vs correctly returning nothing. It's an eval concern because qrels must be computed within the permission boundary — a correct empty result must not be scored as a miss, and a leak must be caught. - You use an LLM to grade (query, chunk) pairs. What must you measure before trusting its labels, and what must you record in each run?Agreement with human labels on a stratified sample (Cohen's kappa at graded and binary level, plus reading the disagreements). Record the judge model, its version and the prompt text with
evalset_sha, because a silent judge update changes your labels (2.9). - A paper reports nDCG@10 = 0.62 and your harness reports 0.58 for the same system. Name two convention differences to check before suspecting a bug.
Further resources#
- Järvelin & Kekäläinen, "Cumulated gain-based evaluation of IR techniques" (ACM TOIS, 2002) — the nDCG paper; the standard reference for graded relevance metrics.
- Manning, Raghavan & Schütze, Introduction to Information Retrieval (Cambridge UP, 2008; free online edition — the live Stanford site was unreachable on 2026-11-05, so this is the archived copy; publisher page) — the standard textbook for precision/recall, MAP, MRR and evaluation methodology.
- Cormack, Clarke & Büttcher, "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods" (SIGIR 2009) — the RRF paper behind 06.8's fusion.
- BEIR: github.com/beir-cellar/beir + the wiki's dataset list — heterogeneous zero-shot retrieval benchmark and how to load its datasets.
- MTEB: leaderboard on Hugging Face + arXiv:2210.07316 — the massive embedding benchmark; read 02.3, 7.4 for caveats first.
- MS MARCO: microsoft.github.io/msmarco + arXiv:1611.09268 — the classic ad-hoc retrieval dataset.
- MIRACL: miracl.ai + aclanthology.org/2023.tacl-1.63 — 18-language retrieval benchmark.
- HyDE: aclanthology.org/2023.acl-long.99 (arXiv:2212.10496) — hypothetical document embeddings.
- Step-back prompting: arXiv:2310.06117 (ICLR 2024) — abstraction for multi-hop reasoning.
- RAGAS metrics docs: docs.ragas.io — available metrics — context precision/recall and the wider RAG-eval metric family (Module 10A goes deep).
- Upadhyay et al., UMBRELA — open-source LLM relevance assessor; RTEB announcement; BRIGHT; ranx metrics (both nDCG conventions) and pytrec_eval.
- Efron & Tibshirani, An Introduction to the Bootstrap (1993) — the bootstrap method behind the confidence intervals in 4.5.
← 06.9 — Reranking | Module 06 overview | Module 07: Retrieval-Augmented Generation (RAG) →