📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your RAG assistant is live, and users report confident answers that are wrong, sometimes quoting the right document but the wrong clause. How do you investigate whether the problem is retrieval, chunking or the prompt, and how do you fix it?

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.

Senior RealWorldScenario Advanced ai chunking debugging evaluation observability rag

🎯 Key points

  • Reproduce with traces: question, retrieved chunk ids and scores, the exact prompt version, model version, answer (OpenTelemetry gen_ai spans plus app-level retrieval spans)
  • Log safely: chunk ids and scores rather than content, redacted questions, short retention and restricted access, because traces are a copy of user data
  • Classify each failure: right chunk not retrieved (retrieval), retrieved but cut or ambiguous (chunking), retrieved and clear but misused (generation/prompt)
  • Chunking bugs are common: clauses split mid-sentence, tables flattened, headings lost, so the 'right document' arrives without its qualifying context; structure-aware chunking fixes it
  • Fix retrieval with hybrid search (keyword for clause numbers), a reranker, metadata filters (current version), and a relevance threshold with refusal
  • Fix generation with grounding rules, quoting the clause, citing per claim, and lower temperature; don't let the model fill gaps
  • Turn reported failures into golden-set cases run by the CI evaluation suite (xUnit + Microsoft.Extensions.AI.Evaluation) and gate fixes on recall@k and groundedness
  • Mitigate first (show sources and effective dates), re-index blue/green behind an alias, and monitor groundedness on sampled traffic, weak-retrieval rate and thumbs-down by topic

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Triage table

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

Production example

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].

🔍 What the interviewer is checking

Checks that the candidate can debug a production RAG system methodically and fix the right layer.

Green flags

  • Starts from traces with retrieval details, not hunches
  • Classifies failures into retrieval, chunking and generation
  • Explains why "right document, wrong clause" points to chunking or ranking
  • Uses hybrid search, reranking, version filters and refusal thresholds
  • Turns failures into regression tests and monitors after the fix

Red flags

  • "I'd improve the prompt" or "use a bigger model" as the first step
  • No logging of what was retrieved
  • Fixes cases one at a time without measurement
  • Ignores stale or superseded documents

📚 Learn in depth

1. The RAG failure taxonomy

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.

2. What to log (safely)

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.

3. Why "right document, wrong clause" happens

  • Fixed-size chunking splits a clause from its conditions; the model faithfully answers from half a rule.
  • Similar clauses (e.g. full-time vs part-time entitlements) embed close together; without a reranker the wrong one may rank first.
  • Tables flattened to text lose which number belongs to which row.
  • Superseded versions remain in the index.

4. Fixes by layer

  • Chunking: parse document structure (headings, numbered clauses, tables). Keep a clause with its sub-clauses; prefix the heading path ("Leave Policy > 4 Annual leave > 4.2"). Represent tables as markdown or one row per chunk with headers repeated.
  • Retrieval: hybrid BM25 + vector with RRF; semantic reranker on the top 50; filters for current version and audience; query rewriting for follow-ups ("what about part-timers?").
  • Thresholds: tune a minimum reranker score on the golden set; below it, refuse or ask a clarifying question.
  • Generation: "quote the relevant clause, then answer"; one citation per claim; forbid unsupported statements; temperature low.

5. Verifying the fix

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.

Try it yourself

  1. Take a policy document with numbered clauses and exceptions; chunk it at fixed 512 tokens and by structure; compare which chunk contains each exception.
  2. Ask ten clause-number questions with vector-only and hybrid search; compare recall@5.
  3. Log retrieval scores for 50 questions and plot correct vs incorrect answers to choose a refusal threshold.
  4. Change the prompt to quote-then-answer and compare groundedness scores.
  5. Build a blue/green index swap with an alias in Azure AI Search.

💻 Code

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

⚠ Common mistakes

  • Mistake: Tweaking the prompt or upgrading the model first. Why it is wrong: it hides retrieval and chunking bugs and raises cost. Instead: classify failures by layer using traces, then fix the layer at fault.
  • Mistake: Logging only the final prompt and answer. Why it is wrong: you can't see what was retrieved, with what scores and filters. Instead: log chunk ids, scores, filters, prompt and model versions per request.
  • Mistake: Fixed-size chunking for structured documents. Why it is wrong: clauses lose their conditions and tables lose their structure. Instead: structure-aware chunking with heading paths.
  • Mistake: Leaving superseded documents in the index. Why it is wrong: old and new versions compete and the model may pick the wrong one. Instead: version metadata, effective-date filters and delete sync.
  • Mistake: No refusal threshold. Why it is wrong: with weak retrieval the model answers from general knowledge, confidently. Instead: a tuned minimum relevance score with an "I can't find that" path.
  • Mistake: Fixing reported cases one by one without tests. Why it is wrong: fixes regress silently. Instead: add each case to the golden set and gate in CI.
  • Mistake: Re-indexing in place. Why it is wrong: a bad re-index takes the assistant down or makes it worse with no rollback. Instead: build a new index and swap an alias.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate refers to ingestion or the grounding prompt Why: Checks the underlying pipeline design they are debugging
    How to answer

    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.

  2. When: Candidate mentions chunking or hybrid search Why: Checks depth on chunking, hybrid search and reranking
    How to answer

    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.

  3. When: Candidate mentions the golden set or CI gating Why: Checks how they prove the fix worked and keep it from regressing
    How to answer

    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.

🛠 Real-world problems: how you handle them

Policy assistant quoting clauses without their exceptions
Situation
[An internal policy assistant] for [about 1,500 staff] at [an Australian organisation], answering from [about 6,000 pages] of HR and finance policy. After launch, staff reported confident wrong answers on leave and expense entitlements, sometimes citing the right policy.
Signals
[About 30] user reports and a rise in thumbs-down on leave and expenses topics; sampled groundedness scores on live traffic dropped to [3.8]; KQL showed [about 18%] of answers produced with a top retrieval score below 0.5.
Investigation
Replayed each reported case from traces (chunk ids, scores, prompt and model versions); classified them: [about 60%] chunking (clause exceptions in the next chunk, flattened tables), [25%] retrieval (clause-number queries, superseded versions ranking first), [15%] generation (unsupported additions). Confirmed with recall@5 and groundedness on a new [300-case] golden set.
Resolution
Mitigated by showing source clauses and effective dates prominently. Then re-chunked by document structure with heading paths into a new index swapped by alias, added hybrid search with semantic reranking and a current-version filter, set a tuned refusal threshold, and changed the prompt to quote the clause and cite per claim.
Prevention
Reported failures become golden-set cases; CI gates on recall@5 and groundedness; weekly dashboard of weak-retrieval percentage, refusal rate and thumbs-down by topic; ingestion validation that flags split numbered clauses.

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].

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me