RAG 示範看似正常,正式上線前要測試的 7 種失效情況
Your RAG Demo Works. Test These 7 Failure Modes Before Production
文章提出一套 RAG 正式上線前的測試計劃,涵蓋檢索、生成、拒答、引用與文件時效,以及負載下的系統表現。建議以 20–50 條真實問題建立版本化評測集,分開測試檢索和生成,並檢查系統能否在無答案時拒答、引用是否有依據及文件是否過時。負載測試則分階段記錄延遲、逾時、佇列深度、tokens 和每個成功答案的成本,並將生產問題納入回歸測試。
A RAG demo can look excellent with three hand-picked questions.
The answer sounds confident. The citations look plausible. The latency is fine. Everyone in the room nods.
Then a real user asks about a policy that changed last month. The retriever returns an old PDF, the model blends two conflicting passages, and the answer is still beautifully written.
That is the uncomfortable thing about retrieval-augmented generation: a fluent answer is not evidence that the system retrieved the right evidence or used it correctly.
This is also why RAG reliability is getting more attention than another round of prompt tweaking. A recent DEV.to discussion about a RAG system under load drew dozens of comments around the trade-off between verification, throughput and queueing. The engineering question is bigger than “does it answer?” It is “what does it do when the evidence is missing, stale, ambiguous or expensive to retrieve?”
Here is a small test plan you can adapt before putting a RAG feature in front of users.
1. Build a tiny evaluation set from real questions
Do not start with a benchmark of a thousand synthetic prompts.
Start with 20–50 questions that represent what people actually ask. Include:
- questions with a clear answer in one document;
- questions that need more than one source;
- paraphrases of common questions;
- questions about information that is not in your corpus;
- questions where old and new documents disagree.
Keep the expected source IDs and whether the question is answerable next to each case. Version this file with your code.
For example:
[
{
"id": "refund-window",
"question": "Can I return an item after 30 days?",
"answerable": true,
"expected_source_ids": ["returns-policy-v3"]
},
{
"id": "international-fee",
"question": "What do you charge for an international wire?",
"answerable": false,
"expected_source_ids": []
}
]
The second case is important. A system that always produces an answer can look productive while being unreliable.
2. Test retrieval separately from generation
When an answer is wrong, you need to know which component failed.
Did the retriever miss the correct policy? Did it return the right passage but the model ignore it? Did the model invent a detail that was never present?
Expose retrieval results in your application response or trace:
- document ID and version;
- chunk ID;
- retrieval score;
- rank in the result list;
- source metadata.
Then make retrieval a testable contract.
Here is a deliberately small pytest example. Adapt ask() and the result fields to your application:
from dataclasses import dataclass
import pytest
@dataclass(frozen=True)
class Case:
name: str
question: str
answerable: bool
expected_source_ids: frozenset[str]
CASES = [
Case(
"refund-window",
"Can I return an item after 30 days?",
True,
frozenset({"returns-policy-v3"}),
),
Case(
"international-fee",
"What do you charge for an international wire?",
False,
frozenset(),
),
]
@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name)
def test_rag_contract(case):
result = ask(case.question) # Your production RAG entry point
retrieved = set(result.retrieved_source_ids)
if not case.answerable:
assert result.abstained is True
return
assert case.expected_source_ids & retrieved
assert result.citations
assert set(result.citations) <= retrieved
This does not prove the answer is factually correct. It catches several useful failures early: missing expected evidence, failure to abstain, and citations that point to sources the retriever never returned.
3. Test abstention, not just successful answers
Create questions that your corpus cannot answer.
Examples:
- Ask for a product feature that is not documented.
- Ask about a date outside the available policy.
- Ask for a private account detail that is not in the retrieved context.
- Ask a question that sounds related to a document but is not answered by it.
The expected behavior should be explicit: say that the available sources do not contain enough information, ask for clarification, or route the question to a person.
Do not treat an empty retrieval result as proof that the corpus lacks the answer. It may mean the retriever failed. Track corpus coverage separately from retrieval success.
That distinction is especially useful when debugging search systems: “the source does not exist” and “we failed to find the source” are different incidents.
4. Check citations and document freshness
A citation is not decoration. It is a claim that the answer can be traced to evidence.
Test that:
- every citation refers to a chunk or document actually retrieved;
- the cited passage supports the associated claim;
- the source is still valid for the question;
- an archived version does not silently outrank the current one.
For policies, pricing, product documentation and internal runbooks, store version or effective-date metadata. Add a test where an old and a new document contain conflicting values. The system should follow your documented precedence rule, not whichever chunk happens to score higher.
A valid URL attached to an unsupported sentence is still a bad citation.
5. Try paraphrases and awkward questions
Users do not write like benchmark datasets.
Take one known question and create a few realistic variants:
- different wording;
- a typo;
- an abbreviation;
- a vague reference such as “that plan”;
- two questions combined into one;
- a follow-up that depends on previous context.
The goal is not to force every wording to return identical text. The goal is to check that the system retrieves the right evidence and handles ambiguity safely.
If a question has two possible meanings, asking a short clarification can be better than confidently choosing one.
6. Test the system under load
A RAG request is a pipeline, not a single model call.
Measure the stages separately:
- query embedding;
- retrieval;
- reranking;
- context construction;
- generation;
- citation or answer verification;
- queue wait time.
Record p50 and p95 latency, timeout rate, queue depth, tokens and cost per successful answer. An acceptable average can hide a terrible tail.
Also test repeated identical questions arriving together. Caching or single-flight request coalescing may reduce duplicate work, but make sure cache keys include the relevant tenant, corpus version and permission scope. A fast answer from the wrong user's cache is a security bug, not an optimization.
Set limits for queue length, request deadlines and maximum context size. Decide what should happen when the system is overloaded: wait, return a clear busy response, or fall back to a safe path.
7. Keep a regression set and review failures
Every production bug should become a test case.
When you change the prompt, embedding model, chunking strategy, reranker, corpus ingestion or base model, run the same evaluation set again.
Track at least four groups of results:
| Area | Useful question |
|---|---|
| Retrieval | Did the expected evidence appear in the top results? |
| Answer | Was the answer relevant and supported by the retrieved context? |
| Safety | Did the system abstain when evidence was insufficient? |
| Operations | Did latency, timeout rate or cost get worse? |
Metrics such as context relevance, faithfulness and answer relevance are useful ways to organize evaluation. The ARES paper describes an evaluation framework around these dimensions.
But do not collapse everything into one magic score. A 2026 empirical study of RAG for ESG documents reported that retrieval metrics and generation quality varied separately, with factual correctness remaining a challenge even when retrieval measures looked stronger. That is a useful reminder that a better retriever does not automatically produce a trustworthy answer. Read the study.
Tools such as Ragas can help once your evaluation set grows. You do not need a framework to begin, though. A versioned file of real questions, expected sources and a few honest tests is already much better than judging quality from a demo.
A practical CI workflow
I would split the checks into two speeds:
On every relevant pull request
- deterministic retrieval and citation tests;
- answerable and unanswerable cases;
- stale-document and permission-boundary checks;
- basic latency or token-budget smoke tests.
On a schedule or after model/corpus changes
- broader paraphrase sets;
- LLM-judge metrics as signals, not unquestionable truth;
- human review of a sample of answers and failures;
- comparison against the previous evaluation run.
Store the model, prompt, embedding, corpus and dataset versions with every result. Otherwise, a score change is difficult to explain.
The goal is not to prove that a RAG system never makes a mistake. It is to make failures visible, reproducible and less likely to reach users unnoticed.
If you could add only one test to your RAG pipeline tomorrow, which would it be: retrieval coverage, citation validity, safe abstention, document freshness or production latency? And what failure have you actually seen?
來源:DEV Community · dev.to