Production troubleshooting of a RAG assistant giving confident wrong answers: tracing a bad answer through retrieval, chunks and prompt, separating retrieval failures from generation failures, fixing chunking (split tables and clauses), hybrid search, reranking, relevance thresholds, grounding and citation rules, and preventing recurrence with evaluation and monitoring.
Treat it as a pipeline bug, not a model mystery. Take the reported cases and use traces to replay each one: the question, the retrieved chunks with scores, the exact prompt and the answer. Then classify: was the right chunk not retrieved (retrieval), retrieved but cut or stripped of context (chunking), or retrieved and clear but misused (prompt/generation)? "Right document, wrong clause" usually means chunking split a clause from its conditions, or retrieval ranked a similar clause higher.
Fix the layer at fault: structure-aware chunking, hybrid search plus a reranker, version filters, a relevance threshold with refusal, and stricter grounding and per-claim citations. Add every case to the golden set and gate the fix in CI. The trade-off: stricter grounding means more "I can't find that" answers, which is better than confident wrong ones.
"First I'd stop guessing and get the evidence. We log, under privacy controls, the question, the retrieved chunk ids with scores, the prompt version, the model version and the answer, linked by trace id. So I'd collect the reported cases, around [30] in this example, replay each one and classify it. Is the right chunk missing from the top k? That's retrieval. Is it there but cut off, a clause without its 'unless' paragraph, a table flattened into nonsense? That's chunking. Is it there, complete, and the model still got it wrong or added things? That's the prompt or the model.
For example, on [a policy assistant at an Australian organisation], when I did this the split was roughly [60% chunking, 25% retrieval, 15% generation]. The chunker split on a fixed 512-token window, so clause 4.2's exception landed in the next chunk; the model quoted 4.2 faithfully and was wrong. Retrieval failures were mostly queries with clause numbers, which pure vector search handles badly, plus superseded versions of the same policy ranking above current ones. I [rebuilt chunking on the document structure, keeping each clause with its sub-clauses and the heading path], added hybrid search with a reranker and a 'current version' filter, and set a relevance threshold below which the assistant says it can't find the answer. On the generation side, the prompt now requires a citation per claim and quoting the clause text. Wrong answers on the regression set dropped from [about 22% to about 4%].
The mistake I see is jumping straight to prompt tweaks or a bigger model. That hides retrieval and chunking bugs, and costs more. Fix the data path first, measure each layer, and make every user-reported failure a permanent test case. Confident wrong answers are usually a retrieval bug wearing a generation costume."
| Symptom in trace | Layer | Typical fix |
|---|---|---|
| Correct chunk not in top k | Retrieval | Hybrid search, reranker, query rewriting, better metadata |
| Correct chunk retrieved but missing its conditions | Chunking | Structure-aware chunks, keep clause + sub-clauses, heading path |
| Old and new versions both retrieved | Data / metadata | Version and effective-date filters; delete superseded content |
| Low scores on all chunks but the model answers anyway | Prompt / thresholds | Relevance threshold, refusal path |
| Right chunk, model paraphrases wrongly or adds facts | Generation | Quote-then-answer, per-claim citations, lower temperature |
| Correct answer, user still marks wrong | UX / expectations | Show sources and effective dates; clarify scope |
After the fixes, on [the policy assistant] wrong answers on [a 300-case] regression set dropped from [about 22%] to [about 4%], the refusal rate rose from [3%] to [7%] (acceptable, as most refusals were truly out of scope), and thumbs-down on policy questions halved within [a month].
Checks that the candidate can debug a production RAG system methodically and fix the right layer.
Green flags
Red flags
question ─► [query understanding] ─► [retrieval] ─► [chunks] ─► [prompt] ─► [generation] ─► answer
│ │ │ │ │
ambiguous, follow-up missed / wrong split, stale weak rules hallucinated,
without context ranking flattened misread
Each stage needs its own evidence. That is why traces must record retrieval details, not just the final prompt.
| Field | Purpose |
|---|---|
| Trace id, prompt version, model version | Reproduce exactly |
| Retrieved chunk ids, scores, ranks, filters | Diagnose retrieval |
| Chunk text (or a pointer to it) | Diagnose chunking |
| Answer and citations | Diagnose generation |
| User feedback | Find failures |
Use pointers to chunk ids instead of copying content where possible, redact personal information, and keep retention short.
Add every reported failure (de-identified) to the golden set with expected chunk ids. Gate on recall@5, groundedness and a per-category wrong-answer rate. Re-index into a new index and swap aliases, so you can roll back.
Structure-aware chunking that keeps a clause with its sub-clauses and heading path, plus retrieval logging for diagnosis.
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
namespace Policies.Ingestion;
public sealed record Chunk(string Id, string DocumentId, string HeadingPath, string Text, DateOnly EffectiveFrom);
public static partial class ClauseChunker
{
// Splits markdown policy text at top-level numbered clauses ("4.2 "), keeping sub-clauses
// ("4.2.1", "(a)") with their parent so exceptions stay attached to the rule.
public static IEnumerable<Chunk> Split(string documentId, string title, string markdown, DateOnly effectiveFrom)
{
var section = title;
var current = new StringBuilder();
string? clause = null;
var index = 0;
foreach (var line in markdown.Split('\n'))
{
if (line.StartsWith("## ")) { section = $"{title} > {line[3..].Trim()}"; continue; }
var match = TopLevelClause().Match(line);
if (match.Success)
{
if (clause is not null) yield return Make();
clause = match.Groups[1].Value;
current.Clear();
}
current.AppendLine(line);
}
if (clause is not null) yield return Make();
Chunk Make() => new(
Id: $"{documentId}:{index++}",
DocumentId: documentId,
HeadingPath: $"{section} > {clause}",
Text: $"{section} > {clause}\n{current.ToString().Trim()}", // heading path improves retrieval
EffectiveFrom: effectiveFrom);
}
[GeneratedRegex(@"^(\d+\.\d+)\s")] private static partial Regex TopLevelClause();
}
public static class RetrievalTelemetry
{
private static readonly ActivitySource Source = new("Policies.Retrieval");
// Record ids and scores (not content) so a bad answer can be replayed and classified.
public static void Record(string question, IReadOnlyList<(string ChunkId, double Score)> hits, string promptVersion)
{
using var activity = Source.StartActivity("rag.retrieve");
activity?.SetTag("rag.prompt_version", promptVersion);
activity?.SetTag("rag.hit_count", hits.Count);
activity?.SetTag("rag.top_score", hits.Count > 0 ? hits[0].Score : 0);
activity?.SetTag("rag.chunk_ids", string.Join(',', hits.Select(h => h.ChunkId)));
}
}
A KQL query to find answers produced from weak retrieval:
dependencies
| where name == "rag.retrieve"
| extend topScore = todouble(customDimensions["rag.top_score"]), version = tostring(customDimensions["rag.prompt_version"])
| summarize total = count(), weak = countif(topScore < 0.5) by version, bin(timestamp, 1d)
| extend weakPct = 100.0 * weak / total
Make the pipeline debuggable before it goes live: per-request retrieval traces, versioned prompts, pinned models and a golden set. With those, a vague "it's wrong" becomes a classification exercise that takes an afternoon. Without them, teams spend weeks rewriting prompts.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Structure-aware re-chunking | Policies, contracts, manuals | Re-index time | Short unstructured snippets (FAQs) |
| Hybrid + reranker | Clause numbers, codes, similar clauses | Extra latency (~100–300 ms), cost | Tiny corpora where flat search is enough |
| Refusal threshold | Any high-stakes Q&A | More "can't find" answers | Creative or brainstorming features |
| Bigger model | Generation errors persist after retrieval is fixed | Higher cost per answer | As the first response to wrong answers |
Measure per layer (recall@k, chunk completeness, groundedness) and per topic; a single accuracy number hides where the pipeline is failing.
RAG is two pipelines. Ingestion (offline): extract text, chunk it on headings into a few hundred tokens, embed each chunk with IEmbeddingGenerator, and upsert it with metadata (source, heading, URL, permissions) into a vector store through Microsoft.Extensions.VectorData. Query (online): embed the question, run a hybrid, permission-filtered search for the top 5–8 chunks, then call the chat model with a grounding prompt: numbered sources, "answer only from these", "say you don't know", and cite [n].
You check the citations in code and show source links. You measure retrieval recall and answer groundedness on a labelled set. The trade-off: more chunks raise recall but add cost, latency and noise that can distract the model.
An embedding is a fixed-length vector of floats produced by an embedding model, such that texts with similar meaning land close together. Vector search embeds the query with the same model and returns the stored vectors nearest to it, usually by cosine similarity. At scale you use an approximate index (HNSW) rather than comparing against every vector.
You chunk documents into passages of a few hundred tokens because one vector for a 40-page PDF blurs everything together. For stores: Azure AI Search gives hybrid keyword-plus-vector search and reranking; SQL Server 2025 / Azure SQL has a native VECTOR type when the data already lives there; Cosmos DB and pgvector suit apps already on those. The trade-off: vectors find meaning, but miss exact codes and names unless you add keyword search.
You can't unit-test an LLM into correctness, so you measure it. Build a golden set of real cases with expected sources or reference answers, including out-of-scope and adversarial ones. Measure retrieval (recall@k) separately from answers (groundedness, relevance, completeness). Run deterministic checks first (valid JSON, valid citations, refusals), then LLM-as-judge evaluators such as those in Microsoft.Extensions.AI.Evaluation, calibrated against human grades.
Treat prompts, model versions and retrieval settings as code: every change runs the suite in CI against thresholds. In production, track feedback and add new failures to the set. The trade-off: a bigger, richer evaluation set catches more regressions but costs more tokens and expert time to build and run.
How to tell it (STAR)
**S:** After we launched our [policy assistant], staff reported confident wrong answers about leave and expenses, often citing the right policy. **T:** I [owned the retrieval pipeline] and had to find the cause rather than patch prompts. **A:** I replayed [30] reported cases from traces and classified them: most were chunking, where exceptions landed in the next chunk, then retrieval misses on clause numbers and old versions. I re-chunked by structure into a new index, added hybrid search with reranking and a version filter, set a refusal threshold and tightened grounding, and gated it all on a [300-case] golden set. **R:** Wrong answers on the regression set fell from [about 22% to 4%], and thumbs-down on policy questions halved within [a month].
Last updated 23 Nov 2026.