Sub topic 16
Diagnosing Common Failures
This chapter assumes you can build the basic pipeline from earlier chapters: chunking, embeddings, top-k retrieval, prompt assembly, and the recall_at_k metric. It also assumes you know basic Python. The goal is to find which stage of the pipeline broke when an answer is wrong, and to fix that stage instead of guessing.
Why failures need a method
A wrong answer from a RAG system has many possible causes. The document may never have been ingested. A chunk may have split the key sentence in half. The retriever may have missed the right passage. The model may have ignored a good passage. If you only read the final answer, all of these look the same.
The method is to check the stages in order, from the data toward the answer. A later stage cannot be fixed by tuning an earlier one, and an earlier failure makes every later check meaningless.
Build a trace first
You can only diagnose what you can see. Log one record per query that holds every intermediate result. Keep the record as plain JSON so you can search it later.
import json
import time
def traced_answer(question, retrieve, build_prompt, generate, k=5):
"""Run one RAG query and return the answer plus a full trace."""
t0 = time.time()
hits = retrieve(question, k) # list of (score, text) pairs
passages = [text for _, text in hits]
prompt = build_prompt(question, passages)
answer = generate(prompt)
trace = {
"question": question,
"hits": [{"score": round(s, 4), "text": t[:200]} for s, t in hits],
"prompt_chars": len(prompt),
"answer": answer,
"seconds": round(time.time() - t0, 3),
}
print(json.dumps(trace))
return answer, traceThe function takes retrieve, build_prompt, and generate as arguments, so you can pass in the functions you wrote in earlier chapters or test doubles. With the trace in hand, each failure below becomes a question you can answer by reading one record.
Failure 1: the fact never reached the index
Symptoms: the system says "I don't know," or answers with general knowledge instead of your data.
Check by searching the raw chunks for a distinctive phrase from the expected answer. If the phrase is absent, the problem is upstream of retrieval.
Common causes:
- The loader skipped the file type, such as scanned PDFs with no text layer.
- Cleaning removed too much, for example stripping tables or code blocks as "boilerplate."
- The index is stale and the document was added after the last build.
- Text extraction scrambled column order, so sentences run together across columns.
Fix the loader or the cleaning step and re-ingest. Do not raise k or change the embedding model, because the data is simply not there.
Failure 2: poor chunking
Symptoms: the right document is retrieved, but the passage lacks the detail needed. Answers are vague or partly wrong.
Check by printing the chunk that should have held the answer. Look for three patterns:
- Split fact. The question and the answer fall on opposite sides of a boundary. Overlap in
chunk_textreduces this but does not remove it. - Orphaned reference. The chunk says "it was increased to 30 days" and nothing in the chunk says what "it" is.
- Diluted chunk. A large chunk holds many topics, so its embedding is an average that matches no single question well.
Fixes depend on the pattern. Split on structure, such as headings and paragraphs, before falling back to fixed windows. Prepend the document title and section heading to each chunk so references have context. Shrink chunks that mix topics. Each change requires re-embedding the whole corpus, so test on a small sample first.
Failure 3: retrieval misses the right chunk
Symptoms: the chunk exists and contains the answer, but it is not in the top-k.
Measure this directly. For a set of questions where you know the relevant chunk ids, compute recall at k.
def recall_at_k(retrieved_ids, relevant_ids, k):
relevant = set(relevant_ids)
if not relevant:
return 0.0
hits = set(retrieved_ids[:k]) & relevant
return len(hits) / len(relevant)
cases = [
{"retrieved": ["c9", "c2", "c4", "c1", "c7"], "relevant": ["c1"]},
{"retrieved": ["c3", "c5", "c8", "c6", "c0"], "relevant": ["c2"]},
]
for k in (1, 3, 5):
avg = sum(recall_at_k(c["retrieved"], c["relevant"], k) for c in cases) / len(cases)
print(f"recall@{k} = {avg:.2f}")This prints recall@1 = 0.00, recall@3 = 0.00, and recall@5 = 0.50. The first case finds its chunk at rank 4, and the second never finds it.
Look at what the missed chunks have in common:
| Pattern | Likely cause | Typical fix |
|---|---|---|
| Query uses an exact code, name, or error string | Embeddings blur rare tokens | Add keyword search and fuse with reciprocal rank fusion |
| Query is short or vague | Little signal to match on | Query rewriting or expansion |
| Right chunk is at rank 6 to 20 | Ranking is coarse | Retrieve more, then rerank |
| Query and document use different wording | Embedding model is weak for the domain | Try another embedding model and compare recall |
| Results are right topic, wrong version or team | No metadata filter | Filter on version, date, or source |
Approximate indexes can also lose results. To check, run the exact top_k brute-force search on a sample of queries and compare with the index. If the exact search finds the chunk and the index does not, raise the index's search effort setting or rebuild with different parameters.
Failure 4: good chunks lost during assembly
Symptoms: the trace shows the right chunk in the hits, but the answer ignores it.
Check prompt_chars and the order of passages. Two causes are common:
- Truncation. The prompt exceeds the context limit and the tool cuts the end. If your best passage is last, it disappears first.
- Burying. Models often use passages at the start and end of a long context more reliably than those in the middle. Ten loosely related passages can hide one important one.
Fixes: count tokens before sending, pass fewer and better passages, and place the strongest passages first. Reranking helps here because it makes the top few passages the most relevant ones, so you can lower k in the prompt.
Failure 5: unsupported answers
Symptoms: the answer contains claims that no retrieved passage supports. This is often called hallucination, but in RAG it has more specific causes.
- The context lacks the answer and the prompt did not allow the model to say so. The
build_promptinstruction to say "I don't know" addresses this. - The retrieved passages are close but not exact, so the model fills the gap from memory.
- The passages conflict, for example an old and a new policy, and the model blends them.
- The model cites a passage number that does not support the claim.
Check by reading each claim in the answer and finding its supporting passage. A cheap automated check is to confirm every cited number exists in the passage list.
import re
def check_citations(answer, n_passages):
"""Return cited numbers that do not match any passage."""
cited = {int(m) for m in re.findall(r"\[(\d+)\]", answer)}
return sorted(c for c in cited if c < 1 or c > n_passages)
print(check_citations("Refunds take 30 days [1]. Fees apply [4].", 3))This prints [4], a citation to a passage that was never supplied. It catches invented citations but not real citations attached to false claims. For that you need a human review or a second model call that judges whether the passage supports the claim.
Fixes: tighten the instruction, lower the generation temperature, remove conflicting stale documents or add dates to chunks, and return "no answer" when the best retrieval score falls below a threshold you have tuned on your own data.
Failure 6: the test itself is wrong
Sometimes the system is right and the expectation is wrong. The reference answer may be outdated, or the question may be ambiguous. Before changing the pipeline, confirm with the source document. Fixing a correct system to match a bad test set makes it worse.
A repeatable debugging loop
- Collect failing queries with their traces. Aim for at least 20 so one odd case does not drive decisions.
- Label each failure with one stage from the decision path above.
- Count labels. Fix the most common stage first.
- Change one thing at a time and rerun the same query set.
- Add every fixed case to a regression set, so a later change cannot silently bring it back.
Exercise
A user asks "What is the timeout for error E4012?" The trace shows the correct chunk exists in the index, and it contains the string "E4012". It is ranked 14th by vector search, and you pass the top 5 to the model, which answers with a general statement about timeouts. Which stage failed, and name two fixes.
Show answer
Retrieval failed, because the chunk exists but is not in the top-k. The exact error code is a rare token that embeddings represent poorly. Fixes: add keyword (BM25) search and merge it with the vector ranking using reciprocal rank fusion, so the exact match rises. Alternatively, retrieve more candidates (for example 30) and rerank them before keeping 5. A metadata filter or a query rewrite that keeps the code intact can also help.
Exercise
The trace for a query shows the right passage as the fifth of five, the prompt is 2,000 characters over the model's limit, and the answer is missing the key detail. Which failure is this, and what would you change first?
Show answer
This is an assembly failure from truncation, since the over-limit text is cut from the end and the best passage was last. First, count tokens and trim the prompt to fit by sending fewer passages. Then put the strongest passages first, ideally after reranking.