Retrieval engineering · Advanced
How to Measure RAG Quality: From Chunking to Reranking

A practical, reproducible benchmark for finding out whether a pipeline change retrieves better evidence, produces more accurate answers, or merely changes the way errors look.
A retrieval-augmented generation (RAG) system can fail before the language model writes a single word. If the relevant passage is not retrieved, an otherwise capable model has little chance of answering correctly. If the passage is retrieved but ranked below distracting text, the model may ignore it. If the evidence is present and the answer is still wrong, retrieval may not be the limiting factor at all.
The practical question is therefore not “does the new RAG pipeline feel better?” It is: does this change improve the probability that the right evidence is retrieved and used, on a fixed set of questions, under a fixed evaluation protocol?
This article describes a minimal benchmark for comparing:
- different chunking strategies;
- dense retrieval and lexical retrieval;
- hybrid search;
- reranking;
- answer accuracy and citation support;
- confidence-based abstention.
The examples use an imaginary internal documentation corpus. They are illustrative, not measured results. No performance claim in this article should be read as a result from a particular model, database, provider, or customer dataset.
1. Define what “better” means
RAG quality is not one metric. It is a chain of dependent outcomes:
- The corpus contains the information needed to answer the question.
- The index makes that information retrievable.
- The retriever places relevant passages in the candidate set.
- The ranker orders useful passages above distracting ones.
- The generator answers from the evidence rather than from unsupported prior knowledge.
- The system declines to answer when the evidence is insufficient.
A useful evaluation separates these stages. For a question q, define:
retrieval(q) -> ranked passages
context(q) -> passages sent to the generator
answer(q) -> generated response
decision(q) -> answer or abstain
Then ask distinct questions:
| Stage | Question | Primary evidence |
|---|---|---|
| Coverage | Does the corpus contain a supporting passage? | Human-verified relevance labels |
| Retrieval | Is a supporting passage in the top k? | Recall@k, hit rate |
| Ranking | Are the most useful passages near the top? | MRR, nDCG@k |
| Generation | Does the answer satisfy the question? | Exact match, rubric score, human review |
| Grounding | Are answer claims supported by retrieved evidence? | Claim-level support review |
| Abstention | Does the system answer only when evidence is adequate? | Selective accuracy, coverage, abstention errors |
This separation prevents a common diagnostic mistake: treating answer accuracy as proof that retrieval improved. A model may compensate for missing evidence using memorized knowledge. Conversely, retrieval may improve while answer accuracy stays flat because the generator, prompt, or answer rubric is now the bottleneck.
Use a decision rule before running the experiment
Write down what would count as an improvement. For example:
Candidate B is preferred if it improves Recall@5 on answerable questions, does not reduce unsupported-answer performance on unanswerable questions, and improves answer accuracy without exceeding the agreed latency and context limits.
The exact thresholds are project decisions, not universal facts. State them before looking at results so that the benchmark does not become a search for a favorable metric.
2. Build a benchmark that can be repeated
The smallest useful benchmark has four fixed inputs:
- a versioned corpus;
- a versioned question set;
- relevance labels and answer references;
- a configuration manifest.
Every run should produce machine-readable output containing the configuration, retrieved identifiers, scores, latency, generated answer, and evaluation labels. A human should be able to inspect one question from the result and reconstruct what happened.
Recommended directory layout
rag-eval/
├── corpus/
│ ├── documents.jsonl
│ └── manifest.json
├── questions/
│ ├── questions.jsonl
│ └── labels.jsonl
├── configs/
│ ├── baseline.json
│ ├── hybrid.json
│ └── reranked.json
├── runs/
│ └── 2026-11-30-baseline.jsonl
└── scripts/
├── build_index.py
├── retrieve.py
└── score.py
The names are illustrative. The important property is that corpus, questions, labels, and settings have explicit versions.
Freeze the evaluation boundary
Do not change these between candidates unless the change itself is the subject of the experiment:
- question wording;
- document inclusion and exclusion rules;
- embedding model;
- generator model and temperature;
- system prompt;
- maximum retrieved passages;
- answer rubric;
- random seed, where the software supports one.
If you compare chunking strategies, rebuild the index from the same document snapshot and keep the rest of the retrieval and generation stack constant. If you compare embedding models, treat chunking as a controlled variable. If you change several layers at once, label the result as a system-level comparison rather than attributing the change to one component.
3. Create questions and relevance labels
A benchmark made only of easy, answerable questions often overestimates system quality. Include questions that exercise different retrieval behaviors:
| Question type | What it tests | Example shape |
|---|---|---|
| Direct lookup | Exact entity and value retrieval | “What is the default session timeout?” |
| Paraphrase | Semantic matching | “How long can an inactive session remain open?” |
| Lexical lookup | Identifiers, error codes, product names | “What causes error AUTH-204?” |
| Multi-hop | Combining evidence from multiple passages | “Which role can perform the action and under what condition?” |
| Temporal | Version and date handling | “What changed in the 4.2 policy?” |
| Unanswerable | Evidence sufficiency and abstention | “Which regions are supported?” when the corpus does not say |
Do not generate all questions from the same document template. That can create artificial regularities that favor one retriever without representing real usage.
Question record
{
"question_id": "q-017",
"text": "What is the default session timeout?",
"answerability": "answerable",
"reference_answer": "The default session timeout is 30 minutes.",
"required_facts": [
"default session timeout",
"30 minutes"
],
"source_scope": ["docs/authentication/session-policy.md"],
"type": "direct_lookup"
}
For an unanswerable question, keep reference_answer empty or replace it with an explicit statement such as “The corpus does not establish this.” Do not silently label an unanswerable question as wrong merely because a model produced a plausible answer.
Passage relevance labels
At minimum, label each question–passage pair with three levels:
0 = not relevant
1 = related, but insufficient to answer
2 = directly supports an answer
3 = necessary or highly useful for a complete answer
For a minimal benchmark, binary relevance is acceptable: relevant: true|false. Graded labels are more informative when the corpus contains background passages, partial evidence, and competing versions of a policy.
Keep the labels separate from the retrieved results. The evaluator should not be able to infer relevance from the candidate’s ranking or score.
Labeling protocol
- Give the labeler the question and the passage, but not the candidate system name.
- Ask whether the passage supports the answer as written, not merely whether it mentions the same topic.
- For versioned content, record whether the passage applies to the requested version or date.
- Mark disagreements and adjudicate them before comparing systems.
- Keep a small sample for a second review to detect inconsistent labeling.
The benchmark does not need a large number of questions to expose a serious regression, but it does need questions that represent the failure modes you care about. A small, carefully reviewed set is more useful than a large set of unverified synthetic labels.
4. Measure retrieval quality
Hit rate and Recall@k
For a question with at least one relevant passage, a hit occurs when the retrieved top k contains a relevant passage:
hit@k(q) = 1 if any relevant passage is in top k
= 0 otherwise
Recall@k = sum(hit@k(q)) / number of answerable questions
When each question has one known supporting passage, hit rate and Recall@k are equivalent. When multiple passages can support the answer, recall can be defined as the fraction of relevant passages retrieved:
Recall@k(q) =
relevant passages retrieved in top k
------------------------------------
relevant passages in the label set
Report the definition you use. “Recall@5” is ambiguous if the relevance set is not documented.
Mean Reciprocal Rank
Mean reciprocal rank rewards a relevant passage appearing near the top:
RR(q) = 1 / rank of the first relevant passage
MRR = average RR(q) over questions
MRR is useful when the generator sees only a small context window or when the first strong passage has disproportionate influence. It does not tell you whether all necessary passages were retrieved.
nDCG for graded relevance
When labels use grades such as 0–3, use normalized discounted cumulative gain (nDCG). It rewards highly relevant passages near the top while still accounting for partially useful passages.
The exact implementation should be fixed in the evaluator. A common form is:
DCG@k = sum((2^rel_i - 1) / log2(i + 1))
nDCG@k = DCG@k / ideal_DCG@k
Use a library implementation only after checking its indexing convention and behavior when the ideal score is zero. Record those choices in the benchmark README.
Context precision and context recall
Retrieval quality can also be described at the context level:
- Context recall: how much of the required evidence was retrieved.
- Context precision: how much of the retrieved context is relevant.
These metrics are especially useful when comparing a broad retriever with a reranker. A broad candidate set may raise recall while lowering precision. That is not automatically a regression if the reranker restores precision before generation.
Measure more than the mean
Always report distributional information:
- overall score;
- score by question type;
- score by corpus area or document family;
- number of questions improved;
- number of questions regressed;
- latency percentiles, if latency matters.
A small average improvement can hide a severe regression on error-code questions. Conversely, a small average decrease may be acceptable if the change fixes a high-risk class of queries. The benchmark should make those trade-offs visible.
5. Measure answer quality
Retrieval metrics answer “was the evidence available?” They do not answer “did the system use it correctly?” Evaluate answers separately.
Exact match and structured answers
Exact match is appropriate for constrained outputs such as:
- a version number;
- a status value;
- a list of permitted fields;
- a JSON object with a fixed schema.
Normalize only what is clearly irrelevant to correctness, such as case or surrounding whitespace. Do not normalize away distinctions such as units, dates, negation, or version numbers.
Rubric-based scoring
For explanatory answers, use a rubric with separate dimensions. One minimal rubric is:
| Dimension | Score 0 | Score 1 | Score 2 |
|---|---|---|---|
| Correctness | Incorrect | Partly correct | Correct |
| Completeness | Misses required facts | Some required facts | All required facts |
| Grounding | Unsupported claims | Mixed support | Claims supported by retrieved evidence |
| Instruction following | Ignores format or scope | Minor deviation | Follows requested format and scope |
Define in advance whether the dimensions are averaged, summed, or treated as gates. For a support-oriented assistant, it may be safer to require both correctness and grounding rather than allowing a fluent but unsupported answer to pass because it is complete.
Claim-level support
Whole-answer labels can hide one unsupported sentence inside an otherwise correct response. A stronger review decomposes the answer into atomic claims:
{
"claim": "The default session timeout is 30 minutes.",
"supported_by": ["chunk-042"],
"support": "supported"
}
For each claim, mark:
supported— the retrieved evidence entails the claim;partially_supported— the evidence supports only part of it;unsupported— the evidence does not establish it;contradicted— the evidence points to a different claim.
This is slower than a single pass/fail score, so use it for a representative sample or for questions where grounding is safety-critical.
Use model-based grading carefully
An evaluator model can help triage or scale a rubric, but it is not an independent fact source. Keep a human-reviewed sample, use a fixed grading prompt, save evaluator outputs, and inspect disagreements. Do not report a model-graded result as an objective measurement without describing the grader and its failure modes.
6. Compare chunking, search, and reranking
The experiment should change one meaningful factor at a time. A minimal sequence is:
- baseline chunking + dense retrieval;
- alternative chunking + dense retrieval;
- baseline chunking + hybrid search;
- hybrid search + reranking;
- the selected retrieval stack + abstention policy.
This sequence is not a universal order. It is a simple way to isolate common pipeline decisions.
Chunking variables
Record at least:
- chunk unit: characters, tokens, sentences, paragraphs, sections, or semantic boundaries;
- target chunk size;
- overlap size;
- minimum and maximum chunk size;
- whether titles and breadcrumb paths are prepended;
- whether tables, code blocks, and lists are kept intact;
- document version metadata.
Chunking is not just a size parameter. A 500-token chunk can be useful if it preserves a complete policy rule and harmful if it splits a table row from its heading. Store the original document identifier and character or token offsets so that every retrieved chunk can be traced back to its source.
Dense retrieval
Embeddings represent questions and passages as vectors. Dense retrieval is often useful for paraphrases and conceptually similar wording, but its behavior depends on the embedding model, corpus language, chunk construction, and distance function.
Record:
{
"retriever": "dense",
"embedding_model": "record-the-model-used",
"distance": "cosine",
"top_k": 20,
"query_normalization": "record-normalization-policy"
}
The value above is a configuration example, not a recommendation for a specific model.
Lexical retrieval and hybrid search
Lexical retrieval, commonly based on BM25 or a related term-matching method, can be strong for exact names, identifiers, error codes, and rare words. Hybrid search combines lexical and dense candidate generation or scores.
Do not compare hybrid search using an undocumented score blend. Save the component scores and the combination rule:
{
"retriever": "hybrid",
"lexical": {
"method": "BM25",
"top_k": 50
},
"dense": {
"top_k": 50
},
"fusion": {
"method": "reciprocal_rank_fusion",
"parameter": 60
},
"final_top_k": 20
}
Score scales from lexical and vector systems are usually not directly comparable. Rank-based fusion avoids assuming that their raw scores have the same meaning. If you use score interpolation instead, document normalization and weights.
Reranking
A reranker receives the question and a candidate passage list, then produces a new ordering. Evaluate it as a ranking layer, not as a replacement for candidate generation. If the relevant passage never enters the candidate set, no reranker can recover it.
candidates = retrieve(query, top_k=50)
ranked = rerank(query, candidates)
context = ranked[:8]
Compare at least:
- candidate recall before reranking;
- Recall@k after reranking;
- nDCG@k or MRR after reranking;
- answer accuracy with the same final context size;
- reranking latency and failure rate.
A reranker can improve top-rank precision while reducing recall at a larger cutoff if it compresses or filters candidates. Measure the cutoffs that correspond to your actual generator context.
Configuration manifest
{
"run_id": "hybrid-reranked-example",
"corpus_version": "corpus-2026-11-30",
"question_set_version": "questions-v3",
"chunking": {
"strategy": "section_aware",
"target_tokens": 450,
"overlap_tokens": 60,
"include_heading": true
},
"retrieval": {
"method": "hybrid",
"candidate_k": 50,
"final_k": 8
},
"reranking": {
"enabled": true,
"model": "record-the-model-used"
},
"generation": {
"model": "record-the-model-used",
"temperature": 0,
"max_output_tokens": 400
},
"abstention": {
"enabled": false
}
}
“Record the model used” is intentionally a placeholder for your own environment. A reproducible benchmark must replace it with the exact model identifier and relevant version information.
7. Run the minimal benchmark
The following command sequence is illustrative. Adapt the commands to your implementation, but preserve the order and the saved artifacts.
# 1. Validate the corpus and question files
python scripts/validate_data.py \
--corpus corpus/documents.jsonl \
--questions questions/questions.jsonl \
--labels questions/labels.jsonl
# 2. Build one index per chunking configuration
python scripts/build_index.py \
--config configs/baseline.json \
--corpus-version corpus-2026-11-30
python scripts/build_index.py \
--config configs/section-aware.json \
--corpus-version corpus-2026-11-30
# 3. Run retrieval and save every ranked result
python scripts/retrieve.py \
--config configs/baseline.json \
--questions questions/questions.jsonl \
--output runs/baseline-retrieval.jsonl
# 4. Generate answers from the frozen retrieved context
python scripts/generate.py \
--config configs/baseline.json \
--retrieval runs/baseline-retrieval.jsonl \
--output runs/baseline-answers.jsonl
# 5. Score retrieval and answers
python scripts/score.py \
--questions questions/questions.jsonl \
--labels questions/labels.jsonl \
--retrieval runs/baseline-retrieval.jsonl \
--answers runs/baseline-answers.jsonl \
--output runs/baseline-report.json
Each result record should include enough information for inspection:
{
"question_id": "q-017",
"retrieved": [
{
"rank": 1,
"chunk_id": "chunk-042",
"score": 0.81,
"source_id": "docs/authentication/session-policy.md"
}
],
"context_chunk_ids": ["chunk-042", "chunk-019"],
"answer": "The default session timeout is 30 minutes.",
"latency_ms": {
"retrieval": 18,
"reranking": 0,
"generation": 940
}
}
Do not save secrets, access tokens, private customer content, or unnecessary personal data in the run artifacts. Hash or redact identifiers when the source corpus is sensitive, while preserving stable identifiers for comparison.
Bootstrap confidence intervals
Aggregated metrics from a small question set can move because of a few questions. A simple uncertainty estimate is a bootstrap interval over questions:
for iteration in 1..N:
sample questions with replacement
compute metric on sampled questions
interval = chosen percentiles of bootstrap metrics
Bootstrap intervals are an aid to interpretation, not a guarantee that the benchmark represents production. If questions are clustered by document or user workflow, consider resampling at the cluster level so that near-duplicate questions do not dominate the estimate.
Paired comparison
Compare candidates question by question. For each question, record whether candidate B:
- improved the first relevant rank;
- added a required passage;
- removed a distracting passage;
- changed a correct answer to an incorrect one;
- changed an incorrect answer to a correct one.
Paired analysis is usually more informative than comparing two unconnected averages because it shows where the change helped and where it hurt.
8. Evaluate abstention
An answerable-only benchmark rewards systems that always answer. Real systems also receive questions for which the corpus has no adequate evidence. An abstention policy should therefore be evaluated on both answerable and unanswerable questions.
Define the decision
Make the output explicit:
{
"decision": "answer",
"confidence": 0.78,
"answer": "The default session timeout is 30 minutes.",
"evidence": ["chunk-042"]
}
Or:
{
"decision": "abstain",
"confidence": 0.21,
"answer": "I could not verify this from the available documents.",
"evidence": []
}
The abstention text is part of the product behavior. It should not imply that the fact is false when the system only knows that the available evidence is insufficient.
Coverage and selective accuracy
Let coverage be the fraction of questions for which the system answers:
coverage = answered questions / all questions
Selective accuracy is answer accuracy among answered questions:
selective_accuracy =
correct answered questions / answered questions
Plot or tabulate selective accuracy at different coverage levels by varying the abstention threshold. A system that answers fewer questions can appear more accurate; that may be desirable or unacceptable depending on the task. Report both values.
Four abstention outcomes
| Question | Decision | Outcome |
|---|---|---|
| Answerable | Answer | Correct answer: success |
| Answerable | Abstain | Missed opportunity |
| Unanswerable | Answer | Unsupported-answer error |
| Unanswerable | Abstain | Safe abstention |
Do not choose a threshold from the same questions used for the final report. Split the benchmark into development and evaluation subsets, or use cross-validation when the dataset is small. Otherwise the threshold is tuned to the test set.
Signals for abstention
Possible signals include:
- the score of the highest-ranked passage;
- the gap between the first and second passages;
- agreement among independent retrieval methods;
- claim-level evidence checks;
- an answer verifier that checks whether required facts are supported.
These signals are system-specific. Do not assume that a retrieval score is a calibrated probability. Calibrate and validate any threshold on held-out questions.
9. Concrete case: a policy assistant
Consider an imaginary assistant that answers questions about internal deployment policies. The corpus contains Markdown pages, tables, changelogs, and short troubleshooting notes.
The team observes that users often ask for exact error codes and also paraphrase policy language. They want to compare three configurations:
| Configuration | Chunking | Retrieval | Reranking |
|---|---|---|---|
| A | Fixed-size chunks | Dense | None |
| B | Section-aware chunks | Dense | None |
| C | Section-aware chunks | Hybrid | Cross-encoder or equivalent reranker |
The benchmark contains direct lookups, paraphrases, error-code questions, version-specific questions, multi-hop questions, and unanswerable questions. The team measures Recall@5, nDCG@8, answer correctness, claim support, latency, and abstention coverage.
The interpretation should follow the evidence:
- If B raises retrieval recall for multi-sentence policies but lowers recall for error codes, the chunk boundary change helped one query class and harmed another.
- If C improves nDCG but not candidate recall, the reranker is ordering existing evidence better; it is not solving corpus coverage.
- If C improves retrieval and answer correctness but increases unsupported answers on unanswerable questions, the abstention policy needs separate work.
- If retrieval improves while answer correctness does not, inspect the generator context, prompt, answer rubric, and claim-support behavior before changing retrieval again.
Those are interpretation patterns, not measured findings. The actual conclusion must come from the saved run data.
10. Common failure cases
The benchmark contains only answerable questions
Symptom: the best system is the one that answers everything.
Cause: unsupported answers are not represented in the score.
Fix: add unanswerable questions and report abstention outcomes separately.
Labels mark topical similarity as relevance
Symptom: retrieval scores look high, but users say answers are not supported.
Cause: passages mention the same subject without containing the required fact.
Fix: label whether a passage supports the answer, not whether it shares vocabulary.
Chunking and embedding changes are bundled together
Symptom: a better result cannot be attributed to a cause.
Cause: several variables changed in one candidate.
Fix: run controlled comparisons and then a final system-level comparison if needed.
Top-k is changed between candidates
Symptom: one candidate receives more context and appears more accurate.
Cause: context budget is confounded with retrieval method.
Fix: compare at the same final context size, then run a separate context-budget experiment.
Duplicate chunks inflate results
Symptom: several top results appear relevant, but all repeat the same text.
Cause: overlap, replicated documents, or version duplicates.
Fix: report document-level and passage-level metrics, and inspect duplicate concentration.
Stale documents are treated as equally relevant
Symptom: the system retrieves a correct-looking but obsolete instruction.
Cause: relevance labels ignore version, date, or document status.
Fix: include temporal validity in labels and evaluate version-specific questions.
The evaluator rewards fluent unsupported answers
Symptom: answer scores rise while evidence support falls.
Cause: correctness or style is scored without claim-level grounding.
Fix: add a separate support dimension and review disagreements manually.
Only averages are reported
Symptom: a small mean gain leads to a rollout despite critical regressions.
Cause: query-class and worst-case behavior are hidden.
Fix: report per-class metrics, paired changes, and representative failures.
11. Verification checklist
Before trusting a comparison, verify the following.
Data
- The corpus snapshot is identified and reproducible.
- Questions include both answerable and unanswerable cases.
- Question types cover the intended user behavior.
- Relevance labels are separate from system outputs.
- Version and date constraints are labeled where applicable.
Retrieval
- Every retrieved passage has a stable identifier.
- The evaluator records rank and score.
- Recall@k has a documented relevance definition.
- The final context size is fixed for answer comparisons.
- Hybrid fusion and reranking settings are recorded.
Generation
- The generator model and prompt are frozen across candidates.
- Answers are scored with a written rubric.
- Unsupported claims can be identified.
- Structured outputs use deterministic validation where possible.
- Human review covers a sample of successes and failures.
Analysis
- Results are compared question by question.
- Metrics are reported by query type.
- Latency and cost proxies are included when operationally relevant.
- Thresholds are selected without tuning on the final evaluation set.
- All reported improvements can be traced to run artifacts.
Minimal acceptance report
A concise report can contain:
candidate: C
corpus_version: corpus-2026-11-30
question_set_version: questions-v3
retrieval:
recall_at_5: ...
mrr_at_10: ...
ndcg_at_8: ...
answers:
correctness: ...
completeness: ...
support_rate: ...
abstention:
coverage: ...
selective_accuracy: ...
unanswerable_answer_rate: ...
latency_ms:
p50: ...
p95: ...
regressions:
question_ids: [...]
notes:
- Every value above is computed from saved run artifacts.
Replace the ellipses with measured values only. If a metric was not run, omit it or mark it as unavailable; do not infer it from another metric.
12. Limitations
No benchmark fully represents production behavior. A fixed question set can become familiar to the team. Human labels can be inconsistent. Model-based graders can share the same blind spots as the generator. Retrieval metrics may reward passage presence even when the context is too long or contradictory. Answer metrics may miss latency, usability, and the cost of a wrong answer.
For these reasons, treat the benchmark as a controlled instrument, not as a universal quality score. Refresh questions periodically, add real failure cases after privacy review, preserve historical versions, and distinguish regression detection from absolute quality certification.
Also separate offline and online evidence. Offline evaluation tells you how candidates behave on a fixed set. Online feedback can reveal query distributions, abandonment, clarification behavior, and failures that the benchmark did not anticipate. Do not combine those signals into one number without documenting the measurement design.
Conclusion
The most useful RAG evaluation is a chain of evidence. First verify that the corpus contains support. Then measure whether retrieval places that support in the candidate set. Next measure ranking quality at the context size the generator actually receives. Finally score answers, claim support, abstention, and operational constraints.
When a pipeline changes, the benchmark should let you say exactly what changed: chunking improved recall for one class of questions, hybrid search recovered exact identifiers, reranking improved top-rank precision, or abstention reduced unsupported answers at a stated coverage level. That level of attribution is what turns RAG tuning from intuition into an engineering process.
Continue with the Agent Lab Journal guides or look up unfamiliar terms in the glossary.