Module: L2-M06 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L03 · Next: L05
1. Introduction
L02 measures retrieval and L03 measures the answer; this lesson puts them side by side to answer the question a tester meets every day: why is this answer wrong, and where do we fix it. There are two jobs: failure attribution with explicit rules and one rerun with oracle context, and test set design aimed on purpose at retrieval misses and unsupported claims, instead of a pile of easy questions.
The system in the lab is simulated: the generator is not a model, and each question is assigned a behavior in data/runs.json in advance. So the distribution of labels below reflects the lab's configuration, not the failure frequency of a real system. The output of the lesson: a test set with a lint, with question groups for each failure mode, and an attribution table with a proposal for what to fix first.
2. Learning objectives
- List the failure modes of RAG and point to which check from L01 to L03 catches each one. Practice: §4.1, §8.2 part B.
- Attribute a case to retrieval or generation with a priority rule and a rerun with oracle context, and read the
bothresult. Practice: §8.2 part B, §8.3, §9 (TODO 1). - Choose what to fix first from the table of label counts and read why counting is not enough (§5.3). Practice: §9 (TODO 2).
- Design a test set by group, run the test-set lint and add questions for a group that is short. Practice: §8.2 part A, §9 (TODO 3).
- State what the attribution rules and the lint do not guarantee. Practice: §6.1, §8.3.
3. Prerequisites and tools
- L2-M02-L02 and L2-M02-L03: the coverage matrix (dataset coverage, not the "coverage" of a confidence interval), the edge case and the borderline case. L2-M05-L04: classifying failures. L2-M06-L01 to L03. The code lab
code-labs/l2-m06. - "Context" in this lesson is the retrieved context (L01 §3). Oracle context is a context made only of the evidence chunks, not to be confused with the test oracle (the mechanism that decides pass or fail, L1-M01-L01). The labels in this lesson are attribution labels, not precision or recall.
4. Concepts
4.1 Failure modes and the checks that catch them
TruLens says the three checks of the RAG triad catch three different kinds of error: irrelevant context "woven" into a made-up answer, a model that exaggerates or embellishes into something that sounds plausible, and an answer that does not address the question [R1]. The table below is the lab's classification, not a complete list from a source:
| Failure mode | Sign | Check that catches it |
|---|---|---|
| Retrieval misses completely / partly | No (or one missing) evidence span in the top-k | missing_evidence (this lesson), recall@k (L02) |
| The right chunk is buried or drowned out by noise | It is in the top-k but the generation step picks another sentence | Oracle re-run (§4.2) |
| Outdated or contradictory document | The answer is supported but wrong | answer_correct, evidence labels |
| Ignores the context | The answer comes from memory, with no citation | groundedness, L03 |
| Adds a claim that is not in the context | One unsupported claim |
claim_supported, L03 |
| Wrong or missing citation | Status uncited, not_retrieved... |
groundedness, L03 |
| Refuses despite having evidence | The fixed refusal sentence | is_refusal + the retrieved evidence |
| Answers a question that has no answer in the corpus | Does not refuse | answered_unanswerable |
| Follows an instruction injected into a chunk | A strange answer from the advertising chunk | Scan the chunks, L01 §5.2 |
4.2 Attribution: the priority order and a rerun with oracle context
attribute assigns one label per case in a fixed order: (1) a question with no answer: correct_refusal or answered_unanswerable; (2) a question with an answer: if no grade-2 evidence span is in the context then retrieval_miss, if one is partly missing then retrieval_partial; (3) the evidence is complete and yet it refuses: refused_with_evidence; (4) a claim that no chunk supports: unsupported_claim; (5) every claim is supported but the citation is missing or wrong: citation_error; (6) every claim is grounded but a required phrase is missing: wrong_answer_supported; (7) otherwise: ok. Retrieval is considered first because the generation step cannot be blamed before it has seen the evidence.
That order is an assumption. attribute_with_oracle tests it: it reruns the same case with the context set to the evidence chunks (the oracle), then gives a verdict: none (the case was already fine), retrieval (the case failed but an ideal context fixes it), generation (the original label is not a retrieval one, and the oracle run still fails), both (the label is a retrieval one and the oracle run still fails), unanswerable. retrieval means supply the right context and the error goes away, not necessarily that recall is low (§5.1, case Q09).
4.3 A test set with a purpose
A useful test set is made of groups aimed at each failure mode: direct (many words in common with the evidence), paraphrase (few words in common, tests keyword retrieval), number, multi_chunk (needs two evidence spans), unanswerable (no answer in the corpus), stale (the corpus has an old contradictory version), duplicate (the corpus has a copy), injection (a chunk contains an instruction). Evidence is recorded as (document, sentence) as in L02, and a grade-2 evidence span is required. lint_testset checks the structure and the minimum number of questions per group; that is a guard so the test set does not shrink bit by bit into all easy questions.
5. Technical deep dive
5.1 Running 25 cases and reading the labels
With BM25, a context of k = 5, each case runs with the behavior in runs.json. Labels: ok 9, wrong_answer_supported 6, unsupported_claim 3, refused_with_evidence 2, citation_error 2, answered_unanswerable 2, correct_refusal 1. Oracle verdicts: generation 11, none 9, unanswerable 3, retrieval 2. The named cases:
Q10(answers from memory, "một tấn bằng 100 tạ", one tonne equals one hundred quintals) andQ12(adds a claim "luôn nhanh hơn mọi cách khác", always faster than every other way) areunsupported_claim;Q19(follows an injected instruction) is too.Q13(cites a chunk that does not contain the sentence) andQ14(no citation) arecitation_error: the claim is right according to the context, the source is recorded wrongly.Q20refuses despite enough evidence;Q23answers with a grounded sentence, but one that belongs to a different question (wrong_answer_supported).Q09(two facts from two documents) at k = 5 has enough evidence in the context but the generator picks a distracting sentence instead of the second one: labelwrong_answer_supported, oracle verdictretrieval(supply exactly the two chunks and it is fine). At k = 3 the label isretrieval_partial.
Lowering k to 2 moves the errors to retrieval: retrieval_miss 2, retrieval_partial 1, and the verdict both on 2 cases. Q06 (a paraphrase about numbers ending in 8) at k = 2 has the context D01-c3 and D09-c1, with no chunk of D08: retrieval_miss, and with the ideal context the generator still refuses because few words match: both. Fixing retrieval alone is not enough.
5.2 Test-set lint
The 25-question set passes the lint: direct 11, paraphrase 3, multi_chunk 3, unanswerable 3, duplicate 2, number 1, stale 1, injection 1. The lint checks: duplicate ids, a valid group, evidence that points to a sentence that exists, a question with an answer has a reference and required phrases, a question with no answer has no evidence, at least one grade-2 evidence span, two questions do not share the same set of content words, a question may not be a verbatim sentence of the corpus, a paraphrase question shares at most 1/2 of its content words with the evidence (the lab's three: 1/3, 2/7, 2/7), and the minimum number of questions per group. Remove the injection group and the lint reports category injection: 0 questions, need at least 1; change a question to the verbatim "6 nhân 4 bằng 24." (six times four equals twenty-four) and the lint reports the question is a sentence of the corpus. A question that shares only most of its words with the evidence still passes: the lint does not measure real difficulty.
5.3 Reading the count table to choose what to fix
Among the 15 failing cases at k = 5 (25 minus 9 ok and 1 correct_refusal), wrong_answer_supported is the most common (6), but counting by label is not enough to choose. Three reasons: the cases have different consequences (following an injected instruction is worse than picking the wrong sentence); one case can have two errors; and each label is itself produced by the simulation's configuration. Use the count table to pick candidates, then look at each case (L2-M05-L04) and assign a risk level (L2-M01-L02). OpenAI describes the score_threshold parameter of search: a high value keeps fewer but more relevant chunks, and can drop useful chunks [R2]; this trade-off is measured by the retrieval_* and wrong_answer_supported labels above.
6. The QA perspective
6.1 What the attribution rules and the lint do not prove
- Labels depend on the checker.
unsupported_claimorcitation_errorrest onclaim_supported, so they inherit the blind spots of L03 (swapped roles, antonyms, paraphrases). - The priority order is an assumption, tested with an oracle on a simulated generator; with a real model the oracle must be rerun.
- One label per case hides the case with several errors.
- A verbatim duplicate counts as a chunk that was retrieved when looking at evidence (
missing_evidence); a near-duplicate does not. answer_correctis a required phrase, and passes if every phrase is listed.- Each group has only a few questions (the
stalegroup has one): not enough to state a rate, only enough to see whether there is an error. - The instruction scan is a phrase pattern (L01): a sentence worded differently is not caught.
- One person wrote the evidence; the reliability of the labels has not been measured (L2-M05).
6.2 From label to fix
retrieval_*: chunking, k, retriever, documents; unsupported_claim, refused_with_evidence: prompt and model; citation_error: citation format and a post-generation citation check; answered_unanswerable: the refusal rule; wrong_answer_supported with an old document: corpus management. Each fix comes with a regression case in the test set (L2-M05-L04: keep the cases you found).
7. Real-world scenarios
Scenario 1 (fictional): "Same symptom, two causes". HocVui saw a two-fact question answered with one half missing at two values of k. Attribution for Q09 at k = 3: retrieval_partial; at k = 5: the evidence is enough but drowned out by noise, verdict retrieval because a compact context fixes it. The team did not raise k blindly but reduced noise first.
Scenario 2 (fictional): "A test set of all easy questions". A draft test set copied sentences from the textbook as questions and every retriever scored high. The lint reported the verbatim questions and the missing paraphrase and unanswerable groups; the team wrote more and the retrieval misses showed up.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l2-m06
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 80 passed
8.2 Run the demo
python -m lab.demo l04
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions give identical output). The generator is simulated:
A. testset lint: [] categories: {'direct': 11, 'stale': 1, 'duplicate': 2, 'paraphrase': 3, 'number': 1, 'multi_chunk': 3, 'unanswerable': 3, 'injection': 1}
B. k=5 labels: {'answered_unanswerable': 2, 'citation_error': 2, 'correct_refusal': 1, 'ok': 9, 'refused_with_evidence': 2, 'unsupported_claim': 3, 'wrong_answer_supported': 6}
k=5 oracle verdicts: {'generation': 11, 'none': 9, 'retrieval': 2, 'unanswerable': 3}
B. k=2 labels: {'answered_unanswerable': 2, 'citation_error': 2, 'correct_refusal': 1, 'ok': 10, 'refused_with_evidence': 1, 'retrieval_miss': 2, 'retrieval_partial': 1, 'unsupported_claim': 3, 'wrong_answer_supported': 3}
k=2 oracle verdicts: {'both': 2, 'generation': 8, 'none': 10, 'retrieval': 2, 'unanswerable': 3}
C. chunks with an instruction aimed at the assistant: ['D11-c1']
D. stale note: contexts D10-c1, D03-c2, reply from D10 -> wrong_answer_supported
Reading the output: A is the test-set lint (empty) and the number of questions per group; B is the labels and oracle verdicts at k = 5 and k = 2; C is the chunk caught by the instruction scan; D is the stale-document case: the context has both D10-c1 and D03-c2, and the answer taken from D10 is supported but wrong.
8.3 Try it yourself
Save this as try_l04.py in the lab's root folder (next to lab/), run python try_l04.py, then delete the file:
from collections import Counter
from lab import attribute as A, corpus as C, data, retrieve as R, testset as TS
corpus = data.load_json("corpus.json")
chunks = C.chunk_sentences(corpus)
queries = data.load_jsonl("queries.jsonl")
runs, memory = data.load_json("runs.json"), data.load_json("memory.json")
bm = R.BM25(chunks)
q6 = queries[5]
r = A.run_case(q6, bm.search, chunks, 2, runs, memory)
print(r["context_ids"], r["reply"])
print(A.attribute_with_oracle(q6, bm.search, chunks, 2, runs, memory))
print(A.attribute_with_oracle(queries[8], bm.search, chunks, 5, runs, memory))
print(A.attribute_with_oracle(queries[8], bm.search, chunks, 3, runs, memory)["label"])
print({q["id"]: str(TS.evidence_overlap(q, corpus)) for q in queries if q["category"] == "paraphrase"})
print(TS.lint_testset([q for q in queries if q["category"] != "injection"], corpus))
bad = dict(queries[0], text="6 nhân 4 bằng 24.")
print(TS.lint_testset([bad], corpus, {})[:2])
Output (Python 3.14.6 and 3.12.14 identical):
['D01-c3', 'D09-c1'] Em chưa tìm thấy điều này trong sách.
{'label': 'retrieval_miss', 'oracle_label': 'refused_with_evidence', 'verdict': 'both'}
{'label': 'wrong_answer_supported', 'oracle_label': 'ok', 'verdict': 'retrieval'}
retrieval_partial
{'Q05': '1/3', 'Q06': '2/7', 'Q16': '2/7'}
['category injection: 0 questions, need at least 1']
['Q01: the question is a sentence of the corpus']
Reading: lines 1 and 2: Q06 at k = 2 is retrieval_miss and both. Line 3: Q09 at k = 5 is wrong_answer_supported and the oracle fixes it (retrieval). Line 4: the same case at k = 3 is retrieval_partial. Line 5: the word overlap of the three paraphrased questions with their evidence (1/3, 2/7, 2/7). Line 6: removing the injection group makes the lint report it as missing. Line 7: a question copied verbatim is caught (the two minimum parameters are left empty so that only this error shows). What the lab does not check: the labels of a system that uses a real model.
8.4 Run the lesson's tests
python -m pytest tests/test_l04_failures_testset.py -v
Result: 13 passed. Read test_retrieval_is_judged_before_generation, test_grounded_is_not_correct_the_stale_note and test_testset_lint_catches_each_mutation. The tests run on the lab's simulated data and configuration.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
KeyError when calling system_config |
The question id is not in runs.json and there is no default |
Keep the default entry in runs.json |
The lint reports needs at least one grade-2 evidence span |
Every piece of evidence has grade 1 | Give grade 2 to the sentence that contains the answer |
9. Independent exercise
Problem: From a log of 12 cases run at k = 2, attribute the failures, choose what to fix first, and add questions to a thin test set.
Requirements: complete exercises/test_l04_failures_testset.py:
- TODO 1:
LABELS: a dictionary from question id to the label fromattribute. - TODO 2:
FIX_FIRST: the failing label with the largest number of cases, with no tie (leave outokandcorrect_refusal). - TODO 3:
NEW_QUERIES: a list of new questions (idsN1,N2...) such thatlint_testset(THIN + NEW_QUERIES, CORPUS, MIN)is empty; thestalequestion has evidence inD03, theinjectionquestion has evidence inD11, theunanswerablequestion has no evidence; at most 6 questions.
Test data: exercises/ex_logs.jsonl (12 simulated cases), exercises/ex_thin_testset.jsonl (6 of the lab's questions).
Deliverable: the three variables above, in exercises/test_l04_failures_testset.py itself.
Acceptance criteria: python -m pytest exercises/test_l04_failures_testset.py passes (3 tests): the labels are recomputed with attribute, FIX_FIRST is the label with exactly one largest value, and the lint is empty. The test does not check whether your new questions are good or actually hard for a retriever.
Hints: TODO 1: find the question's record in QUERIES. TODO 2: collections.Counter. TODO 3: run the lint first to see which group is still short, then read data/queries.jsonl to learn which fields are required.
10. Knowledge check
0/16 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
The lint function below is meant to check "a question with no answer must not have evidence" but reports wrongly. Find the bug.
def lint_one(q):
problems = []
if q["answerable"] and not q["evidence"]:
problems.append("answerable needs evidence")
if q["answerable"] and q["evidence"]:
problems.append("unanswerable must not have evidence")
return problemsP08 · Short answer
For T1, the context holds Y3-c1 (the old printed edition) and Y1-c1, and the answer is "Tổng ba góc của tam giác bằng 360 độ [Y3-c1]." (Vietnamese: the sum of the three angles of a triangle equals three hundred sixty degrees). attribute gives wrong_answer_supported and the oracle verdict is retrieval. So what should be fixed, and why is "give the right context and the error disappears" not enough as the fix direction?
P09 · Essay
Write 5-8 sentences: a draft test set (fictional) has 12 questions, of which 10 copy a sentence of the corpus verbatim and 2 are direct questions; there is no unanswerable question, no stale, no injection. Every retriever tried scores high. Explain why, what the lab's lint will report, and what needs to be added.
P11 · Recall
Lesson: L2-M02-L02P12 · Recall
Lesson: L2-M05-L04P13 · Multiple choice
P14 · True or false
P15 · Select all that apply
P16 · Fill in the blank
11. Summary
- Concepts: the failure modes of RAG; attribution in a priority order and tested with an oracle; the verdicts
retrieval,generation,both; a test set by group with a lint. - Skills: attributing one case, reading a count table, choosing what to fix, writing questions for a group that is short.
- Traps: treating simulated labels as real frequencies, one label hiding several errors, a test set of questions copied from the textbook, a group with too few questions to state a rate.
- You can now: hear "the RAG answered wrong" and bring one case, one label, one oracle verdict, and a fix with a regression case.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | The RAG Triad | TruLens | https://www.trulens.org/getting_started/core_concepts/rag_triad/ | 2026-11-04 | WebFetch (automatic summary) |
| R2 | Retrieval guide | OpenAI | https://developers.openai.com/api/docs/guides/retrieval | 2026-11-04 | WebFetch (automatic summary): score_threshold |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Failure attribution | Quy lỗi: gán nguyên nhân chính cho một ca hỏng |
| Oracle context | Ngữ cảnh lý tưởng: chỉ chứa chunk bằng chứng |
| Retrieval miss / partial | Truy xuất trượt / trượt một phần |
| Unanswerable question | Câu hỏi không có đáp án trong kho |
| Stale document | Tài liệu cũ, mâu thuẫn với bản hiện hành |
| Test-set lint | Lint bộ test |