Ch.59: RAG System Design: The Right Source, the Wrong Answer

Outline

Transcript

0:00 An on-call engineer asks a runbook assistant if a service can restart during a database change. RAG builds that answer by finding documents and giving their passages to a language model. Retrieval-augmented generation. Search first, compose second, using a chosen library instead of relying only on the model's earlier training. Let's design that service, from ingesting runbooks to returning a checked answer, and see why a real citation can still accompany the wrong advice. My first thought is to trust a link more than confident prose.

0:31 But checking where advice came from isn't the same as checking whether to follow it. Now give that answer a path through the architecture. Workers prepare searchable runbooks in advance; each live question then goes through evidence selection, generation and checks. We'll return to this same architecture once a citation has made that whole trip. First, give the caller a promise worth checking. Before choosing components, our functional requirements start with an authenticated question. Search permitted runbooks, answer it, and attach citations that open the exact passages used.

1:03 And if those documents don't answer it, the API needs an insufficient-evidence result. Silence and an authoritative-looking guess aren't interchangeable outcomes. Yep. Return document versions too, so the caller can inspect the evidence and report a bad answer. This service can't execute a restart. I think that boundary matters here. An answer assistant and an operator with permission to change production are different products, even if their chat boxes look identical. So our first deliverable is a supported explanation or an explicit limit, not a completed operational action.

1:35 Now the non-functional requirements constrain that promise. Protect access to the document library before model input, preserve evidence identity, and bound query time and cost. For this fictional exercise, use 80,000 documents averaging 25 passages each, about two million passages, with 50 questions per second at peak. Let's target completed checks within 5 seconds for 95% of requests. That's a proposed load-test target, not performance we've measured. And the deadline includes checking, not just generating words.

2:07 If a check can't finish, we need a response that doesn't quietly drop that promise. Agreed. Keep the deadline fixed while we decide which work belongs before a question arrives and which work must happen during it. Here's our specific case. Checkout's writer saves checkout records, and a schema migration changes database structure. Our engineer needs restart advice because guessing could interrupt that process. The assistant says yes and cites a real routine-restart guide. Open it, and the instruction says restart only when no migration is active.

2:38 Oh, man. It supplied the evidence for the opposite advice. The page isn't missing, and nobody changed permissions underneath the request. Both guides are current and allowed. The original RAG paper combines retrieval and generation; it doesn't make those separate steps infallible. Source links are in the description. Then let's follow the evidence before either step runs. The next failure can happen while we're preparing a document, before a model sees it. First, document ingestion prepares that evidence.

3:07 Queue approved updates, parse the text, and store versioned passages with headings and their positions inside the original document. Splitting a document into passages is chunking. Suppose the instruction lands in one chunk and “only when no migration is active” falls across the boundary. Then a perfectly retrieved fragment can omit the qualification. Is making every chunk larger enough to fix that? Not by itself. Keep the heading and condition together, or fetch the adjacent passage when needed.

3:36 Bigger chunks also carry more irrelevant text and cost more to process. Yeah. Passage size controls spending, not the meaning of an instruction. Keep that condition attached rather than treating the limit as a safe cut point. Next, give that intact passage a versioned identity. Store its document, revision and text positions, then prepare both keyword and meaning-based search indexes. The preparation workers run outside live requests, so 50 callers aren't all reparsing the same runbook. How does the citation survive a document update?

4:08 By referring to the version actually supplied, not whichever text happens to be current when the link opens. A new version gets a new passage identity. A stored guide isn't necessarily searchable yet. Track which revision each index has finished processing; otherwise the migration guide can sit in storage while every question misses it. And displaying an old version doesn't override access controls. The source viewer still checks whether this caller may open it now. Once those passages are searchable, an exact keyword route helps find Checkout and particular error names.

4:42 A meaning-based route helps when the question uses different wording. For example, “recycle the writer” might need the restart guide. What does the meaning route compare without matching that exact verb? It turns text into learned numerical representations, called vectors, then looks for nearby representations. That can connect “recycle” to a restart passage even without the same verb. So the route offers a candidate, not an interpretation of its conditions. An item label and a description can both help find it; neither establishes whether using it is safe.

5:14 Yes. Elastic's hybrid-search docs combine those routes. We'd compare the result against keyword-only search rather than assuming another index must improve our questions. But those search routes return candidates, not a finished answer. Suppose each supplies 40 passages. Merge and deduplicate their lists before paying for closer examination. Wait, if the scores use different scales, how do we combine them without pretending they're the same measurement? Use list positions. Take a miniature: the routine guide comes first on keyword search.

5:44 The migration guide is second there and first on meaning search. And keyword's winner is absent from the meaning results. Higher positions contribute more, and the migration document earns a contribution from each route, without comparing raw scores. Exactly. Elastic's reciprocal rank fusion puts the migration guide ahead here. Why run another model after we've combined those rankings? Then a second model examines each shortlisted passage alongside the question more closely. That's reranking. At most 80 candidates here, instead of the whole library.

6:14 Oh, right. Spend closer attention on selected candidates instead of the entire library. Ranking can't fix evidence that isn't in the shortlist. Then the ranked shortlist competes for the generator's input space. Select up to six useful, nonredundant passages inside an illustrative 4,000-token evidence budget. Tokens are pieces of text the model counts. Couldn't a larger input let us skip this selection and send the whole shortlist? I'd rather avoid dropping the one paragraph we need. Sometimes more context helps.

6:45 It also costs time and can bury useful conditions among distractors. The Lost in the Middle paper found position effects in the models it tested in 2023. So test our current model with the same evidence reordered, instead of declaring that every modern model must fail in the middle. Exactly. Keep the migration precautions intact, with their heading and source identity. An input limit isn't a target we have to fill. With that packet selected, pin its passage versions and record which model and prompt revisions received them.

7:17 This is the evidence for one particular answer. Otherwise a reviewer can open today's guide and conclude the answer ignored a sentence that wasn't even in yesterday's input. That's a miserable debugging session. Yep. A replay needs the supplied text, not just its current URL. Keep sensitive replay material protected rather than putting every runbook in normal logs. What about caching the result? Two engineers can ask the same words and have access to different runbooks. Then a cache keyed only by question can cross a privacy boundary.

7:49 Include the document collection's revision and access scope instead of assuming identical words imply identical evidence. Now the generator consumes that frozen evidence and returns factual sentences associated with supplied source IDs. It doesn't get to invent the destination URL. Application code resolves each ID to its passage and version. For our example, the routine guide has the label R 17 and the migration precautions have M 29. First reject an unknown source label, or a text span outside its stored passage.

8:22 Those identity checks can be exact. But the wrong answer used an existing label. Let's unpack this: how can unchanged evidence accompany a reversed instruction? Finding the page clearly isn't the whole check. So take that failed answer apart. It says restarting during an active migration is safe. Its cited routine passage permits restart only outside a migration. The source ID hasn't changed, and the link still opens. The meaning went wrong when the answer dropped the condition. Right. Provenance tells us where text came from; support asks whether that text warrants this sentence.

8:57 A valid parcel address doesn't establish what's inside the box. Yeah, and opening the box is a different check from reading its address. With citations, the contents we're inspecting are the passage's actual conditions. So a semantic checker compares claim and evidence for contradictions and missing qualifications. It can flag this reversal rather than trusting a valid label, but its judgment remains fallible. But if that semantic checker is another model, aren't we moving the uncertainty into a second answer when we ask it whether the first followed the document?

9:31 We are adding a fallible check, yes. I wouldn't describe it as truth verification. Test it against human-reviewed contradictions, especially negations like our migration condition. Sure. The checker needs evidence of its own reliability on this workload, and a policy for errors or timeouts. Agreement between models isn't enough. It isn't. And even perfect agreement with a bad runbook would faithfully repeat bad advice. Source quality remains a separate responsibility. That limit helps me place the checker.

10:01 We'd measure which unsupported answers it catches, without treating its approval as authority to release anything. But support checking leaves another gap. Suppose a separate test supplies a description saying the writer persists checkout records. The answer faithfully repeats that fact. Every word can be supported while the engineer still doesn't know whether to restart. The reply passed a different test from the one the caller needed. The citation-evaluation paper linked in the description measures citation quality separately from correctness.

10:31 Microsoft's evaluation docs also distinguish search success, support from context, relevance and completeness. Yeah. In our case, usefulness means addressing the restart decision, including its conditions, rather than returning a perfectly cited description of the process. I was treating missing citations as the visible defect. A supported non-answer can be harder to spot because nothing in it has to be false. That unanswered decision leads to our missing-evidence test. Suppose the migration precautions never reach the packet, but the routine guide does.

11:03 We know routine restart requires no active migration. We don't have the migration-specific procedure. The model shouldn't manufacture one just because the caller expects steps. Correct. Return that known condition and say the available evidence doesn't establish how to restart during this migration. A scoped partial answer is an explicit result. Could we search again for the missing precautions before giving up, instead of making the first retrieval pass our only chance? Sure, if a bounded expansion improves measured misses within the deadline.

11:35 Repeating search or generation until something sounds confident can spend the whole budget without adding evidence. Now take a pair of current guides with opposite restart steps. We found both sources, but their instructions don't agree. The language model could choose the more confidently written paragraph, but confidence of wording isn't our source-precedence policy. Who gets to settle that conflict? The product needs a documented authority rule, such as an explicitly designated operations guide, if the organization has one.

12:04 Without it, surface the conflict instead of silently voting. Got it. The original example had consistent guides and a wrong answer. This case has conflicting guides, so fixing generation alone can't create an agreed procedure. And citation support still doesn't establish real-world truth. We can show where both instructions came from without pretending they've become compatible. So those refusal and conflict results affect the response path. Suppose a product manager says, “Show words immediately; waiting through another check makes our assistant feel slow.” That's a real tradeoff.

12:36 For a low-stakes drafting tool, early streaming may be reasonable. For this operational-answer service, buffer the recommendation until our selected checks finish. So we're deliberately paying in latency. If the checker times out, do we release the answer anyway with a small warning underneath? No. Return unavailable or evidence links without the unchecked generated recommendation. A warning arriving after someone has acted doesn't restore the promise. Yeah, that changes the API outcome, not just a status badge.

13:05 We required those checks inside the deadline, and sometimes the result is no answer within it. The checking path also needs a security boundary. For instance, a retrieved paragraph might say to ignore earlier instructions or fetch another team's private runbook. That's document content, not authority. Code limits which documents the caller may search and fetch, and we recheck access before any text reaches the model. Even if a support checker agrees that the paragraph contains that instruction, agreeing with it doesn't grant the service permission to follow it.

13:39 Absolutely. Our answer-only API has no operational tools, and document text can't add them. Security policy stays outside the model's judgment about meaning. Now test the pipeline with questions whose answers we've checked. A stopwatch measures speed, not whether our restart answer preserved the migration condition. What would you inspect first? Let's hear it through the trace. If the needed guide never entered the candidate list, we'd be debugging search, not asking generation to remember the missing procedure.

14:08 Retrieval quality. Measure how often the needed evidence is found. If the guide reaches the final packet but the answer reverses it, inspect generation and support checking instead. And if it says pause the migration but omits waiting for the lock, the answer is incomplete despite including part of the procedure. Yep. Candidate IDs, selected spans and output expose different failures. One overall answer score would send us tuning the wrong component. Now make that test harder. Ask whether it's safe to cycle that process, then remove the migration guide.

14:40 Same decision, different wording, missing evidence. And track refusals alongside answered-question quality. Refusing everything could look wonderfully accurate if the dashboard counts only the answers it chose to give. Hold on. Would that dashboard really hide the unanswered engineer if it only scores the questions we answered? It would. Reserve test examples we didn't use while tuning, and have people review disagreements with the automated judge. Its grades need checking too. Then a model or retrieval change earns rollout by improving the cases we care about, without hiding a new failure inside the average.

15:16 Now use those evaluation failures to design the request trace. Tomorrow's engineer reports bad advice; start with the exact document revisions supplied. And follow the request back to its candidates, selected passages and output, not just yesterday's latency chart. Did we miss the guide or misread it? If the right guide reached the model, compare the stored answer with that packet and the exact prompt and model revision. Now we can investigate the actual failure. Protected replay evidence may include sensitive text, so its access and retention need explicit controls.

15:49 Ordinary latency logs shouldn't quietly become another copy of confidential runbooks. And measure every stage against that total deadline. Retrieval, generation and checking can each look healthy on separate charts while their combined wait still misses it. Finally, return to the same architecture map. The ingestion path keeps a restart instruction with its condition and version. The question path retrieves candidates and selects the actual evidence. Generation proposes an answer; code binds its citations; the support check tests the condition instead of celebrating a valid link.

16:22 Missing evidence or a failed check changes the response. And the evaluation branch separates a passage we never found from a qualification we dropped. We can improve the responsible stage without claiming the whole system became infallible. That's what I like about following one citation across the map. Its identity stays concrete while the questions we ask about it get more demanding. So for our fictional migration, the answer is no restart while it remains active. The migration guide says to pause and wait for its database change lock to release first. With that guide missing, don't invent those steps.

16:59 Say what the available routine instruction establishes and what the service cannot determine. Finding evidence, following it faithfully, and answering the question each need attention. A citation helps us inspect that work; its existence alone doesn't finish it. Thanks for listening to Learning Podcasts.