Sub topic 13
Measuring whether rewriting helps
This chapter assumes you have read the earlier chapters on rewriting techniques, rank fusion and iterative retrieval. It also assumes you can read Python and know what top-k retrieval returns. The chapter covers how to tell whether a rewriting step made retrieval better, and what to look at when it didn't.
Why rewriting needs its own measurement
A rewriting step feels like an improvement because the rewritten queries read better. Readability is not the goal. The goal is that the right passages appear in the top k results more often than before, and that the final answers improve.
Rewriting can also make things worse:
- A condensed question can drop a constraint such as a product version.
- A multi-query expansion can pull in off-topic passages that push good ones out of the top k.
- A HyDE answer can confidently describe the wrong thing, and the search then finds text that resembles the wrong answer.
You can only see these effects by comparing against a baseline on the same labeled questions.
Build a small labeled test set
A test case needs three things:
- The user question, plus the conversation history if the question is a follow-up.
- The IDs of the passages or documents that contain the answer.
- A tag for the kind of difficulty, such as
follow_up,multi_part,vocabulary_mismatchorsimple.
Sources for questions, best first:
- Real queries from logs, labeled by a person who can read the corpus.
- Questions written by domain experts.
- Questions generated by a model from a passage. These are cheap, but each question tends to reuse the wording of its source passage. That favors plain keyword search and hides the vocabulary mismatch you want to fix.
Aim for at least 100 cases. Include the easy ones. Without simple cases you can't detect a rewriter that damages questions that already worked.
Split the set in two. Use one part to develop prompts and choose parameters. Keep the other part untouched until a final check. If you tune on every case, your reported gain will be too optimistic.
Choose retrieval metrics
Use metrics that match how the retrieved passages are consumed.
| Metric | What it measures | Use it when |
|---|---|---|
| Recall@k | Fraction of the relevant documents found in the top k | The generator sees all k passages, and answers need several documents |
| Hit rate@k | Whether at least one relevant document is in the top k | One passage is enough to answer |
| MRR | Average of 1/rank of the first relevant document | Order matters, for example when you truncate context |
| nDCG@k | Rank-aware score that supports graded relevance | You have labels like "partly relevant" |
For multi-part questions, recall@k is the key metric. Decomposition and multi-query expansion exist to find the documents a single query misses. Hit rate hides this, because one found document counts as a success even if the second half of the question has no evidence.
Fix k to the number of passages your generator actually receives. A rewriter that improves recall@20 but not recall@5 gives you nothing if only five passages go into the prompt.
Compare a baseline and a rewriting system
Score each system per case, then compare the scores case by case. A paired comparison is much more sensitive than comparing two averages, because every case acts as its own control.
The code below is a complete harness. It uses a toy lookup in place of a real search so that you can run it as shown. In practice you would replace baseline and rewritten with functions that call your pipeline.
import random
from typing import Callable
Case = dict
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
if not relevant:
return 0.0
return len(set(retrieved[:k]) & relevant) / len(relevant)
def reciprocal_rank(retrieved: list[str], relevant: set[str], k: int) -> float:
for rank, doc_id in enumerate(retrieved[:k], start=1):
if doc_id in relevant:
return 1.0 / rank
return 0.0
def score_system(
cases: list[Case],
retrieve: Callable[[Case], list[str]],
k: int,
) -> list[float]:
return [recall_at_k(retrieve(c), set(c["relevant"]), k) for c in cases]
def paired_bootstrap(
base: list[float],
new: list[float],
n_resamples: int = 2000,
seed: int = 0,
) -> tuple[float, float, float]:
rng = random.Random(seed)
diffs = [n - b for b, n in zip(base, new)]
means = []
for _ in range(n_resamples):
sample = [rng.choice(diffs) for _ in diffs]
means.append(sum(sample) / len(sample))
means.sort()
low = means[int(0.025 * n_resamples)]
high = means[int(0.975 * n_resamples) - 1]
return sum(diffs) / len(diffs), low, high
cases = [
{"id": 1, "tag": "follow_up", "question": "what about its pricing?", "relevant": ["pricing"]},
{"id": 2, "tag": "simple", "question": "reset password", "relevant": ["reset"]},
{"id": 3, "tag": "multi_part", "question": "compare plan A and plan B limits", "relevant": ["planA", "planB"]},
{"id": 4, "tag": "simple", "question": "what is the refund window", "relevant": ["refunds"]},
]
baseline_results = {
1: ["intro", "faq", "limits"],
2: ["reset", "faq", "intro"],
3: ["planA", "faq", "intro"],
4: ["refunds", "faq", "intro"],
}
rewritten_results = {
1: ["pricing", "intro", "faq"],
2: ["reset", "faq", "intro"],
3: ["planA", "planB", "faq"],
4: ["general", "faq", "intro"],
}
def baseline(case: Case) -> list[str]:
return baseline_results[case["id"]]
def rewritten(case: Case) -> list[str]:
return rewritten_results[case["id"]]
base_scores = score_system(cases, baseline, k=3)
new_scores = score_system(cases, rewritten, k=3)
mean_diff, low, high = paired_bootstrap(base_scores, new_scores)
print(f"recall@3 change: {mean_diff:+.3f} 95% interval: [{low:+.3f}, {high:+.3f}]")
for case, b, n in zip(cases, base_scores, new_scores):
verdict = "win" if n > b else "loss" if n < b else "tie"
print(case["id"], case["tag"], verdict)The mean change is +0.125. With only four cases, the bootstrap interval is wide and includes zero, so you could not claim an improvement. The per-case listing is just as informative. Case 4 is a loss on a simple question, which means the rewriter damaged a query that already worked.
Report by slice, not only the average
A single average hides which questions got better and which got worse. Group the paired differences by tag and report the win, tie and loss counts for each group.
Typical patterns:
- Large gains on
follow_upandmulti_part, and small losses onsimple. This pattern points to adding a router that skips rewriting for self-contained questions. - Gains on vocabulary mismatch with HyDE, but losses on questions that contain exact identifiers such as error codes. A hypothetical answer usually paraphrases an identifier and loses it.
- No change anywhere. Often the original query was already good, or your retriever's top k was already saturated.
Measure the answer, not just the retrieval
Better recall does not always give better answers. The generator may ignore the new passages, or extra passages may distract it. Run a second evaluation on the final answers:
- Answer correctness against a reference answer.
- Faithfulness, meaning whether each claim in the answer is supported by the retrieved passages.
- Abstention, meaning whether the system says it doesn't know when the evidence is missing.
An LLM can grade these. Treat it as a noisy instrument. Fix the grader prompt and model, spot-check a sample of its grades by hand, and compare systems with the same grader in the same session. A grader's scores should not be compared with the scores from a different grader.
Count the cost next to the gain
Every rewriting step adds model calls and searches. Record these for both systems on the same cases:
- Median and 95th-percentile latency per question. Sequential steps such as iterative retrieval add latency to every question, so their tail matters.
- Model calls and tokens per question.
- Search calls per question.
A gain of 0.02 in recall@5 for three extra model calls may not justify the cost. A gain of 0.15 on the questions that fail today may justify it, especially if a router applies the expensive path only to those questions.
Common errors
- Comparing different k values. Change only one thing at a time. Fusion returns a different number of unique documents from a single search, so cut every system to the same k before scoring.
- Letting rewrites vary between runs. Model output at nonzero temperature changes the results. Set temperature to 0 where you can, and cache the rewrite for each case so you can separate the retriever's behavior from the rewriter's.
- Judging on too few cases. Differences of a few points on 30 cases are noise. Use the bootstrap interval.
- Tuning on the test set. Prompts and thresholds adjusted by looking at the failures will fit those cases. Keep a held-out set.
- Ignoring the corpus. Labels refer to document IDs. If you re-chunk the index, the labels point to different text, and the old results stop being comparable.
- Reporting only wins. Always list the cases where rewriting made things worse, and read a few of them. Query drift shows up there, as rewrites that answer a different question than the user asked.
A practical decision rule
Keep a rewriting technique when all of these hold on held-out data:
- The paired difference on its target slice, such as
follow_upfor condensing, is positive with an interval that excludes zero. - The loss on the
simpleslice is small, or a router avoids it. - Answer quality does not drop.
- The latency and cost increase fits your budget.
If only the first condition holds, add routing before you give up on the technique.
Exercise
Your rewriting system improves mean recall@5 from 0.62 to 0.66 on 40 test cases, but the paired bootstrap interval for the difference is [-0.03, +0.11]. It also wins on 9 follow-up cases and loses on 6 simple cases. What do you conclude, and what do you do next?
Show answer
The data does not support a claim of improvement, because the interval includes zero and 40 cases is small. The slice breakdown suggests that rewriting helps follow-up questions and hurts simple ones. Next, add more labeled cases, especially for the follow_up and simple slices. Then try a router that rewrites only questions that depend on conversation history or contain several parts, and re-run the paired comparison on a held-out set. Also read the six losses to see what the rewriter changed.