Sub topic 12
Error analysis: turning failures into improvements
A pass rate says how often your application fails. It does not say why. Error analysis is the work of reading failed cases, grouping them by cause, and ranking those causes so you fix the one that matters most. This chapter covers that process.
I assume you can run the evaluation harness from the earlier chapter, which returns a pass rate and a list of per-case results. I also assume your cases carry metadata such as a category or source, and that you know basic Python.
Why a score is not enough
Suppose your pass rate is 62%. The 38% that fail could be one bug that affects many cases or forty unrelated problems. A new prompt, a larger model, or a better retriever could each help, and the score gives you no way to choose between them.
Reading failures answers the question the score cannot. It tells you which change is worth making first. It also shows you when the evaluation itself is wrong. Sometimes a "failure" is a correct answer that the scorer rejected.
The error analysis loop
The process is a cycle, not a one-off audit.
Step 1: Collect full traces
You cannot diagnose a failure from the final answer alone. For each failed case, keep everything the system saw and produced:
- The input and the expected output or grading criteria.
- The final output and the score, plus the judge's reason if a judge was used.
- Intermediate material: the prompt as sent, retrieved documents, tool calls, and model parameters.
If your harness stores only id, output, and passed, extend it first. A failed RAG case where you cannot see the retrieved passages is unreadable. You would have to guess whether retrieval or generation broke.
Step 2: Read and annotate
Read failures yourself. Start with 30 to 50 of them, or all of them if there are fewer. For each one, write a short free-text note about what went wrong, in plain words and without a predefined category: "answer cites a refund window that is not in the context", "output is valid but wrapped in markdown fences", "model refused a harmless question".
Writing notes before choosing categories keeps you from forcing every failure into labels you invented in advance. This is often called open coding. It surfaces failure types you did not expect.
Two habits make the notes more useful:
- Record the earliest point where things went wrong. If retrieval returned the wrong document, the generation step is not the root cause, even though the final answer is wrong.
- Mark cases where the system output is acceptable and the test case or scorer is at fault. These are evaluation bugs, and they get their own tag.
Step 3: Build a failure taxonomy
After you have 30 or more notes, group similar ones and name each group. This is your failure taxonomy. Keep it small, with five to ten tags. Each tag should describe a cause you could act on:
| Tag | Meaning | Typical fix |
|---|---|---|
| `retrieval_miss` | The needed document was not retrieved | Chunking, embeddings, query rewriting |
| `unsupported_claim` | Answer adds facts not in the context | Prompt constraints, lower temperature |
| `format_error` | Output breaks the required schema or style | Structured output, a repair step |
| `wrong_refusal` | Model declines a valid request | Prompt wording, policy tuning |
| `eval_bug` | Output was fine; scorer or label was wrong | Fix the test case or scorer |
A tag like "bad answer" is too vague to help. If you cannot name a likely fix for a tag, split it or sharpen it.
Decide whether a case gets one tag or several. A single primary tag, the earliest root cause, makes counts easy to read. Multiple tags show more but make percentages harder to interpret. Choose one convention and keep to it.
Step 4: Count and rank
Once cases are tagged, count them. This turns a pile of anecdotes into a priority list.
from collections import Counter
# One primary tag per failed case, assigned while reading traces.
failure_tags = [
"retrieval_miss", "retrieval_miss", "unsupported_claim", "format_error",
"retrieval_miss", "unsupported_claim", "wrong_refusal", "retrieval_miss",
]
counts = Counter(failure_tags)
total = len(failure_tags)
cumulative = 0.0
for tag, n in counts.most_common():
share = n / total
cumulative += share
print(f"{tag:<20}{n:>3}{share:>7.1%}{cumulative:>7.1%}")This prints:
retrieval_miss 4 50.0% 50.0%
unsupported_claim 2 25.0% 75.0%
format_error 1 12.5% 87.5%
wrong_refusal 1 12.5% 100.0%The cumulative column is a Pareto view. Here, two causes account for 75% of the failures. A few tags usually dominate, so fixing the top one often moves the pass rate more than several small fixes together.
Frequency is not the only input. A rare failure that is harmful, such as leaking private data, can outrank a common cosmetic one. Weigh each tag by count and by severity, using the severity levels you defined in your success criteria.
Step 5: Slice by metadata
Tags describe why a case failed. Slicing describes where. Group results by the metadata you stored with each case: category, language, input length, source, difficulty. An overall pass rate can hide a weak segment.
from collections import defaultdict
results = [
{"id": "c01", "category": "billing", "passed": True},
{"id": "c02", "category": "billing", "passed": True},
{"id": "c03", "category": "billing", "passed": False},
{"id": "c04", "category": "billing", "passed": True},
{"id": "c05", "category": "shipping", "passed": True},
{"id": "c06", "category": "shipping", "passed": True},
{"id": "c07", "category": "shipping", "passed": True},
{"id": "c08", "category": "returns", "passed": False},
{"id": "c09", "category": "returns", "passed": True},
{"id": "c10", "category": "returns", "passed": False},
]
def pass_rate_by(results, key):
groups = defaultdict(list)
for r in results:
groups[r[key]].append(r["passed"])
rows = [(name, sum(v), len(v)) for name, v in groups.items()]
return sorted(rows, key=lambda row: row[1] / row[2])
for name, passed, n in pass_rate_by(results, "category"):
print(f"{name:<10}{passed}/{n} {passed / n:.0%}")The output is:
returns 1/3 33%
billing 3/4 75%
shipping 3/3 100%The returns slice stands out, but it has only three cases. Treat small slices as leads to investigate, not conclusions. If a slice matters, add more cases to it before you act. Then check whether the dominant failure tag in that slice differs from the overall one. A slice that fails for its own distinct reason often points to a data or prompt gap specific to that area.
Step 6: Fix one thing, then re-measure
Pick the top-ranked cause and make one targeted change. Then re-run the full evaluation, not only the failed cases. A fix for retrieval_miss might break cases that used to pass, and only the full run shows that.
Compare the before and after runs case by case:
- Cases that flipped from fail to pass are the fixes you intended.
- Cases that flipped from pass to fail are regressions. Read them as carefully as you read the original failures.
- Cases that did not change in the target tag mean your fix did not address the cause you thought it did.
Because outputs vary between runs, judge the overall change with the confidence intervals from the earlier chapter on statistical rigor. Do not trust a gain of a few points on a small set.
Common mistakes
- Fixing from one example. A single vivid failure is not a pattern. Count first.
- Overfitting to the dev set. If you read and tune against the same cases every time, the pass rate rises without the real quality rising. Keep a held-out set that you do not read during analysis, and check your final changes against it.
- Never revisiting the taxonomy. After a few fixes the dominant tags change and new ones appear. Re-read a fresh sample each cycle and update the tags.
- Trusting the scorer blindly. A noticeable share of
eval_bugtags means your metric or labels need repair before you change the application. Fix these first, since they make every other number unreliable. - Skipping the passes. Occasionally read a sample of passing cases too. Judges and loose metrics sometimes pass bad answers, and you only find that by looking.
Feeding production back in
The same process works on real traffic. Failures you find in production, through user complaints or monitoring, should become new test cases with the tag you assigned. Over time the dataset grows toward the problems your users actually hit, and the regression suite stops the same failure from returning.
Exercise
Your RAG application scores 70% on 100 cases. You read all 30 failures and tag them: 14 retrieval_miss, 9 unsupported_claim, 4 format_error, 3 eval_bug. A teammate wants to start by rewriting the generation prompt to reduce unsupported_claim. What do you recommend, and what do you do about the eval_bug cases?
Show answer
Start with retrieval_miss, which is 14 of 30 failures (about 47%) and the largest cause. If the right document is not retrieved, a better generation prompt cannot fix those answers, and it may push the model toward unsupported claims. Fix the 3 eval_bug cases first, by correcting the labels or scorer, because they mean the true failure count is 27 and the pass rate is understated. Then change retrieval, re-run the full set, and compare per case to confirm that the fixes landed and nothing regressed.