Score recall@k, ranking and citation support separately
Measure recall@k, rank quality and citation support independently and classify each failure by pipeline stage.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
A RAG answer can fail at several stages, so one overall score hides the cause. Score retrieval with recall@k and rank metrics against labelled expected sources, score generation by whether each citation really supports its claim, and keep these scores separate. Then classify every failure by the stage that caused it: ingestion, search, permission filtering or generation.
Explained simply
When the assistant gets a question wrong, you need to know why. Maybe the right document was never loaded. Maybe search did not find it. Maybe the permission filter removed it. Maybe the model had it and still wrote the wrong thing. Each cause needs a different fix.
So instead of one score, you measure each stage on its own. For search, you check whether the expected documents came back near the top. For the answer, you check whether each cited source really says what the answer claims.
To do this you need labels. For each test question, write down which source IDs should be found. Do this before you run the system, so the labels reflect the truth and not what the system happened to return.
Then you look at each failure and name the stage that broke first. After a few dozen questions you see patterns, such as most failures being search problems. That tells you where to spend your time.
Press Play on a diagram to walk through it one step at a time.
- Ingestion
- Document never indexed
- Parse failed
- Wrong or stale version
- Search
- Indexed but not in top k
- Ranked below noise
- Permission filter
- Allowed source filtered out
- Denied source leaked in
- Generation
- Evidence ignored
- Claim not supported
- Wrong citation
- 1Label questions
Expected IDs and outcomes
- 2Run pipeline
Save ranked IDs and answers
- 3Score each stage
Recall, MRR, support
- 4Classify failures
Earliest broken stage
- 5Fix one stage
Then rerun the same set
- Back to step 1
In depth
Labelling a question set
Start with 20 to 50 questions written from real support needs, using the synthetic corpus. For each, record the expected source IDs at section level, the expected outcome (answered, abstained or escalated) and the caller scope. Include unanswerable questions with no expected sources, and questions only the finance scope may answer.
Some questions have several acceptable sources, for example the same fact in a policy and in product docs. Record them as a set of acceptable IDs, or as groups where any one member counts. Decide this rule before scoring.
Store the set as a versioned JSON or YAML file in the repository. When documents change, update the labels in the same commit, so scores stay comparable over time.
- question, scope, expected_ids, expected_outcome
- Include unanswerable and denied cases
- Allow groups of equivalent sources
- Version labels with the corpus
Recall@k, MRR and nDCG
Recall@k is the share of expected sources found in the top k results. With expected sources A and B, and only A in the top 5, recall@5 is 0.5. Choose k to match how many chunks you actually pass to the model; recall@20 is irrelevant if you only send 5.
Recall ignores order. Mean reciprocal rank (MRR) adds it: for each question take 1 divided by the rank of the first expected source, then average. First place scores 1, third place 0.33, missing scores 0.
nDCG (normalised discounted cumulative gain) gives credit for every relevant result, discounted by how far down it appears, and compares the result to the ideal order. It is useful when several sources matter and you rerank. For a small project, recall@k and MRR are usually enough.
- Found expected sources in top k?
- Ignores order inside k
- Match k to what you send the model
- Rank of the first relevant hit
- 1, 0.5, 0.33 ... or 0
- Good when one source is enough
- Credit for all relevant hits
- Discounted by position
- Useful after reranking
Citation support is a separate score
Retrieval metrics say whether the right sources were found. They do not say whether the answer used them correctly. Citation support asks, for each claim in the answer, whether the cited passage actually states it.
Start with cheap deterministic checks: every cited ID is in the evidence set, and at least one cited ID is in the expected set. Then check support itself. For a small set, a person can mark each claim supported, partly supported or unsupported. For larger sets, a model grader can do it, but calibrate it first against a sample of human labels and report how often they agree.
Track two numbers: citation precision (share of citations that support their claim) and claim coverage (share of claims that have a supporting citation). An answer can have perfect precision and still leave half its claims uncited.
- Deterministic first: IDs valid and expected
- Citation precision: citations that support claims
- Claim coverage: claims with support
- Calibrate any model grader against people
Classifying failures by stage
Walk each failed question through the pipeline in order and stop at the first broken stage. Ingestion: is the expected section in the index, at the current version, with sensible text? If not, it is an ingestion failure. Search: run retrieval without the permission filter. If the section is missing from the top k, search failed. Permission filter: run with the filter. If the section disappears for a caller who should see it, or a denied section appears, the filter failed. Generation: the evidence was there, but the answer was wrong, unsupported or cited the wrong ID.
Record the stage in a results file next to each question. A table of counts per stage after each change is the most useful single view of your pipeline.
- Step 1Is it indexed?
No: ingestion failure
- Step 2In top k unfiltered?
No: search failure
- Step 3Still there filtered?
Wrong result: permission failure
- Step 4Answer correct and supported?
No: generation failure
Learn it in 4 short steps
About 55m each. Track them with a timer in your plan.
- 1Label expected sources per question~55m
- 2Compute recall@k and rank metrics~55m
- 3Check citation support~55m
- 4Classify failures by stage~55m
Key points
- Label expected source IDs for each question before you look at system output.
- Recall@k asks how many expected sources appear in the top k; MRR rewards finding the first one early.
- Citation support is checked separately: a retrieved source is not proof that the cited text backs the claim.
- Unanswerable questions have no expected sources; score them on correct abstention instead.
- Diagnose in pipeline order so you fix the earliest broken stage first.
Key terms
Tap a card to flip it. 0/5 known
Examples
def recall_at_k(expected: set[str], ranked: list[str], k: int) -> float:
if not expected:
return float('nan') # unanswerable: score abstention instead
return len(expected & set(ranked[:k])) / len(expected)
def reciprocal_rank(expected: set[str], ranked: list[str]) -> float:
for i, sid in enumerate(ranked, start=1):
if sid in expected:
return 1 / i
return 0.0
assert recall_at_k({'kb-refunds#s2', 'kb-vat#s1'}, ['kb-refunds#s2', 'kb-faq#s4'], 2) == 0.5Scoring a five-question run
Prerequisites: a labels file and saved ranked IDs from one run, both local. Step 1: load both. Step 2: compute recall@5 and reciprocal rank for answerable questions. Step 3: skip unanswerable ones for recall and check their status instead. Expected evidence: a printed summary such as recall@5 = 0.80, MRR = 0.70, abstention correct 1 of 1. Keep the output file in the repository under evals/results with the commit hash in the name so you can compare runs.
import json, statistics
labels = json.load(open('evals/labels.json'))
runs = json.load(open('evals/run.json'))
rec, rr, abst = [], [], []
for q in labels:
got = runs[q['id']]
if not q['expected_ids']:
abst.append(got['status'] == 'abstained')
continue
exp = set(q['expected_ids'])
rec.append(recall_at_k(exp, got['ranked_ids'], 5))
rr.append(reciprocal_rank(exp, got['ranked_ids']))
print(f'recall@5={statistics.mean(rec):.2f} MRR={statistics.mean(rr):.2f}')
print(f'abstention correct {sum(abst)} of {len(abst)}')Tracing one failure to its stage
Question: what is the VAT rate on training courses? Expected source: kb-vat#s3. Step 1: SELECT the section by ID; it exists at the current version, so ingestion is fine. Step 2: run retrieval without the scope filter; kb-vat#s3 ranks 9th, outside the top 5. Search failed. Step 3: inspect why. The question says training courses while the document says workshops, so keyword search misses it and vector search ranks it low. Fix: add the synonym to the hybrid query or the chunk's metadata, then rerun the full set. Expected evidence: kb-vat#s3 in the top 5 and no drop in other questions.
Quick reference
- Label expected source IDs and outcomes before running the system
- recall@k = expected found in top k / expected; set k to what you send the model
- Reciprocal rank = 1 / rank of first expected source; MRR is the mean
- Unanswerable questions: skip recall, score correct abstention
- Citation precision and claim coverage are separate from retrieval scores
- Diagnose in order: ingestion, search, permission filter, generation
- Save results per commit so runs are comparable
Common mistakes
- Labelling expected sources after reading the system's answers, which bakes its mistakes into the labels.
- Averaging recall over unanswerable questions as zero or one, which distorts the score.
- Blaming the prompt for a wrong answer when the right document was never indexed.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write five labelled questions for the synthetic corpus, including one unanswerable and one finance-only question.
- Exercise 2medium
Write a function that computes citation precision for one answer, given the cited IDs and a set of IDs a reviewer marked as supporting.
- Exercise 3hard
Write a classify_failure function that takes the labels, index lookup, unfiltered results, filtered results and answer for one question and returns ingestion, search, permission, generation or ok.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many test questions do I need?
- Twenty to fifty well-chosen questions are enough to find patterns in a small project. Cover each request type, including unanswerable and denied cases, rather than chasing volume.
- Is a model grader good enough to score answers?
- It can help at scale, but check it against human labels on a sample first and report the agreement rate. Use deterministic checks wherever they work.
- Which k should I use for recall@k?
- Use the number of chunks you actually pass to the model. Recall at a larger k only tells you what reranking could recover.