By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A RAG system is a pipeline, and a pipeline should be tested layer by layer before you test the whole. Otherwise a wrong answer tells you nothing about where it went wrong.
| Layer | Test | Deterministic? | Catches |
|---|---|---|---|
| L1 Ingestion / index | Document count, no empty chunks, metadata present, freshness probe | Yes | A broken crawl, a missing document, stale policy |
| L2 Retrieval | For labelled questions, is the expected source in top-k? | Yes | Wrong policy served, bad chunking, weak embeddings |
| L3 Context assembly | Token budget respected; highest-ranked chunks survive truncation | Yes | Right document retrieved then dropped from the prompt |
| L4 Generation | Faithfulness, relevancy, rule compliance | No (judge) | Hallucination, dodged answers, rule breaks |
The first three layers are deterministic, cheap and fast. Test them first, always. When L4 fails, you will already know whether the cause was upstream.
def retrieval_hit(case: dict, retrieved_ids: list[str]) -> bool:
"""True when every expected source appears in the retrieved set."""
return set(case["expected_sources"]).issubset(set(retrieved_ids))
def retrieval_rank(case: dict, retrieved_ids: list[str]) -> int | None:
"""1-based rank of the first expected source, or None."""
for i, doc_id in enumerate(retrieved_ids, start=1):
if doc_id in case["expected_sources"]:
return i
return None
# A failing run tells you exactly what to fix:
# q_007 uk-returns expected at rank 1, found at rank 4 -> rerank
# q_019 uk-returns not retrieved at all -> embeddings / chunkingRetrieve ten chunks, keep the top four to fit the token budget, and you have created a failure mode where the right document is fetched and then thrown away. Test it explicitly:
def assert_budget_keeps_top_chunks(chunks, max_tokens, approx=lambda s: len(s) // 4):
kept, used = [], 0
for chunk in chunks: # already ranked, best first
cost = approx(chunk["text"])
if used + cost > max_tokens:
break
kept.append(chunk["id"])
used += cost
assert kept, "budget too small to keep even one chunk"
assert kept[0] == chunks[0]["id"], "best chunk was dropped"
return keptOnly at the last layer do you invoke a judge, and you feed it exactly what the model saw: the retrieved chunks, not the whole corpus. Grounding against the corpus would let an answer be 'supported' by a document the model never received.
| Test | Layer | Runs | Cost |
|---|---|---|---|
| Index document count and required metadata | L1 | Nightly | Free |
| Freshness probe for 5 known-changed documents | L1 | Nightly | Free |
| Retrieval hit@k on all golden questions | L2 | Every PR | Free (no model call) |
| Truncation keeps the top chunk | L3 | Every PR | Free |
| Faithfulness on golden answers | L4 | Every PR (smoke) / nightly (full) | Judge calls |
| Correct refusal on unanswerable questions | L4 | Every PR | Judge or rule |
Key takeaways
Test RAG in layers: index, retrieval, context assembly, then generation.
Layers 1–3 are deterministic and free; run them before spending judge calls.
Retrieval hit@k is the single fastest test you can write.
Judge grounding against the chunks the model actually received, not the whole corpus.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.