Debugging RAG Retrieval: Why It Returns Garbage
When RAG answers go sideways, the model usually isn't the problem. Here's the top-to-bottom checklist we run to find where retrieval actually breaks.
Key takeaways
- When RAG returns garbage, the retriever is usually handing the model the wrong chunks.
- Check in order whether the answer is in the corpus, whether chunking split it, whether the embedding model fits your domain, and whether metrics, filters or a stale index hide it.
- Dump the top 20 chunks with scores for every bad answer.
On this page
RAG returns garbage when retrieval hands the model the wrong chunks, not because the model is weak. Debug top to bottom: confirm the answer exists in the corpus, check chunk boundaries, test embedding fit, then verify distance metric, metadata filters, index freshness and top-k. Dump the top 20 retrieved chunks with scores for every bad answer.
Verified against
pgvector 0.8.7 distance operators and the Sentence Transformers retrieve-and-rerank docs, plus the HyDE paper (Gao et al., arXiv 2212.10496). Checked October 2026.
The user asks a question, the answer comes back wrong, and the first instinct is to blame the model. So people swap in a bigger model, rewrite the system prompt, and nothing changes. If the wrong chunks reach the model, no amount of prompt tuning fixes the output. Retrieval failures are quiet. They don't throw. They just hand the model bad context and let it improvise.
The fix is to stop guessing and walk a checklist. Retrieval has a small number of failure points, and they stack in a predictable order. Go top to bottom, prove each layer works before moving down, and the bug usually surfaces in minutes instead of an afternoon.
Start at the corpus, not the query
Before anything else: is the answer even in your data? I have watched teams tune similarity thresholds for a week over a fact that was never ingested. Grep the raw source for a keyword you'd expect in the answer. If it isn't there, retrieval is working perfectly and your ingestion pipeline is the bug.
If the text is present but retrieval still misses it, the next suspect is chunking. A 300-token chunk window loves to split an answer across a boundary. The definition lands in chunk 7, the example that makes it findable lands in chunk 8, and neither chunk alone scores high enough to surface. Pull the raw chunks around your answer and read them like a human. If the answer is fragmented, widen the window or add overlap before touching anything else; our RAG chunking strategies comparison covers which splitter to reach for.
Embedding model and the query/document gap
The embedding model has to actually understand your domain. General-purpose embeddings trained on web text do fine on plain prose and fall apart on legal clauses, medical shorthand, or internal SKU codes. If your corpus is full of jargon the model never saw, semantically related passages land far apart in vector space. A quick tell: embed two passages you know are about the same thing and check their similarity. If it's low, the model is wrong for the domain.
Then there's asymmetry. A query is five words. The matching document is four hundred. Those live in different regions of the vector space even when they mean the same thing, and short-to-long matching is where a lot of recall quietly dies. Two cheap fixes: expand the query with a few likely synonyms, or use HyDE (Hypothetical Document Embeddings, Gao et al.), where you have the LLM draft a hypothetical answer and embed that instead. A fake answer sits much closer to the real document than the terse question does.
Metrics, filters, and stale indexes
Distance metric and normalization bugs are the silent killers. If your vectors aren't normalized and you're using cosine similarity, or you mixed cosine and dot-product between indexing and query time, the scores are noise. Confirm the metric matches on both sides and that vectors are unit length if the metric assumes it. In pgvector, for example, <=> is cosine distance and <#> returns the negative inner product, so sorting the wrong way or forgetting the sign flips your ranking.
Metadata filters are the next trap. A source_type = 'faq' filter looks harmless until the ingestion job wrote that field as 'FAQ', and now every candidate gets excluded before scoring even runs. Filters fail closed and silent. Temporarily strip every filter and see if the right chunk reappears.
Index staleness bites after updates. You reindexed the documents but the vector store still serves the old build, or the upsert half-completed. If a freshly added document never retrieves, query the store directly by its ID and confirm the vector is actually there.
Finally, top-k. If you retrieve the top 3 and the right chunk sits at rank 6, you'll never see it. Bump k to 20 during debugging so you can tell "not retrieved at all" from "retrieved but ranked too low." Those are different bugs with different fixes.
Look at the actual chunks and scores
Most of this collapses into one habit: dump what retrieval returned, with scores, every time. Stop reasoning about the vector store in the abstract and read what it handed back.
# debug_retrieve.py
def debug_retrieve(query, k=20):
results = store.search(query, k=k)
print(f"query: {query!r}\n")
for rank, r in enumerate(results, 1):
preview = r.text[:120].replace("\n", " ")
print(f"[{rank:2d}] score={r.score:.4f} id={r.id}")
print(f" source={r.metadata.get('source')} "
f"type={r.metadata.get('source_type')}")
print(f" {preview}...\n")
return results
Run that against a query you know the answer to. If the correct chunk is nowhere in twenty results, the problem is upstream: ingestion, chunking, or embedding. If it's there at rank 12 with a low score, the problem is ranking: metric, asymmetry, or reranking. The score distribution tells you which. Scores clustered tight around one value mean the embeddings aren't separating anything, which points back at model fit.
Once you have a handful of known-answer queries, turn them into a recall check so a regression can't sneak back in.
# recall_check.py
def recall_at_k(cases, k=10):
hits = 0
for c in cases:
ids = {r.id for r in store.search(c["query"], k=k)}
if c["expected_id"] in ids:
hits += 1
else:
print(f"MISS: {c['query']!r} -> expected {c['expected_id']}")
print(f"recall@{k}: {hits}/{len(cases)} = {hits/len(cases):.2%}")
# cases = [{"query": "how do refunds work", "expected_id": "doc_412#c3"}, ...]
Twenty labeled cases catch more than a fancy eval harness you never finish building. Keep them in the repo and run them on every ingestion or embedding change. When twenty cases stop being enough, grow them into an offline retrieval evaluation harness.
The debugging loop
The repeatable loop is short: log the query, dump the retrieved chunks with their scores, compare against the chunk you expected. If the expected chunk is missing, walk up the checklist from corpus to embedding. If it's present but ranked low, walk down from metric to reranking, and check whether a cross-encoder reranker earns its latency for your corpus. Fix one layer, rerun the recall check, repeat. This same discipline is the foundation of retrieval-augmented generation that people actually trust, because retrieval quality caps every answer above it.
Questions people ask
Why does my RAG return irrelevant results?
Usually because the right chunk never reaches the model. The answer may be missing from the corpus, split across a chunk boundary, embedded by a model that doesn't understand your domain, excluded by a metadata filter, or ranked below your top-k cutoff. Print the top 20 retrieved chunks with scores for a known question; where the right chunk is (or isn't) tells you which layer broke.
How do I tell a retrieval bug from a generation bug?
Log what retrieval returned for the bad answer. If the correct passage is not in the context the model saw, it is a retrieval bug and prompt changes won't help. If the passage was there and the model still answered wrong or ignored it, it is a generation or prompting bug. Most "the LLM is wrong" reports turn out to be the first kind.
What top-k should I use when debugging RAG?
Use a wide k, around 20, while debugging even if production uses 3 to 5. A wide k separates "not retrieved at all" (an ingestion, chunking or embedding problem) from "retrieved but ranked too low" (a metric, query asymmetry or reranking problem). Those need different fixes, and a narrow k hides the difference.
The call we'd make
Instrument retrieval before you tune anything. A logger that prints the top-20 chunks with scores and metadata, plus twenty labeled recall cases, catches nearly every "RAG returns garbage" report faster than swapping models ever will. Build those two things first, and treat every bad answer as a retrieval bug until the dump proves otherwise.
Sources
Cite this article
Kiril Urbonas (2026). Debugging RAG Retrieval: Why It Returns Garbage. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/debugging-rag-retrieval-why-it-returns-garbage
[Debugging RAG Retrieval: Why It Returns Garbage](https://www.devopsness.com/blog/debugging-rag-retrieval-why-it-returns-garbage) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from AI
Explore more articles in this category
vLLM vs SGLang vs TGI vs TensorRT-LLM: Which LLM Server in 2026
Hugging Face TGI is archived and read-only, so the real 2026 choice is vLLM, SGLang or TensorRT-LLM. A feature table, a launch command for each, and the one we default to.
Monitoring ML Models in Production: Data, Concept and Prediction Drift, With Code
Three kinds of drift, two tests that catch most of it, one Prometheus exporter, and the alert rules that do not page you every Monday morning.
MLOps Tools in 2026: 7 Platforms Compared, and the Stack We'd Pick
MLflow, Kubeflow, Weights & Biases, SageMaker, Vertex AI, ZenML and Metaflow compared on tracking, registry, pipelines, serving, self-hosting and pricing, with a default stack for each team size.
You might have missed
Evergreen posts worth revisiting.