Quality Assurance Pipeline for a Compliance-Grade RAG Assistant
Machine LearningModel answerLast updated
Design how to measure, gate, monitor, and debug a retrieval-augmented assistant that serves regulated, multi-tenant content, including root-cause triage of bad answers.
Scenario
A fintech platform runs a question-answering assistant built on retrieval-augmented generation. It answers developer, compliance, and enterprise-customer questions using fast-changing API documentation, regulatory guidance, and per-tenant integration rules. A wrong or invented answer could cause a security flaw or a compliance violation, and tenant access boundaries are strictly enforced.
Design the quality-assurance stack for this assistant. It should keep answers faithful to sources, block regressions before they ship, and let on-call engineers diagnose bad answers quickly.
Requirements
Functional
- Staged evaluation: score retrieval quality (recall, precision, ranking) separately from generation quality (faithfulness, relevance, citation correctness).
- Offline gating: build an automated suite with a golden dataset and LLM-judge scoring that can block deployments.
- Live monitoring: observe real queries, explicit and implicit feedback (thumbs, rephrased retries), latency, token spend, semantic drift, and safety violations.
- Root-cause localization: provide a structured way to decide whether a bad answer came from retrieval failure (missing or noisy chunks), context truncation, or model hallucination.
- Privacy and tenancy: evaluation data and telemetry must honor tenant isolation and have PII and secrets redacted.
Non-functional
- About 100,000 queries per day.
- The offline suite must finish within 20 minutes on a pull request.
- Zero cross-tenant leakage in telemetry, embeddings, and judge runs.
What to cover
- Metrics, and how to build and maintain a golden dataset (including synthetic expansion).
- Architecture: how telemetry flows from live traffic to evaluators, the offline harness, and alerts.
- A root-cause framework (decision tree or classifier) for triaging reported problems, for example using the context relevance / groundedness / answer relevance triad.
- Trade-offs between LLM-judge cost and latency versus heuristic or embedding-based checks.
Hints
Hint 1
Convert 100K queries/day into QPS and judge-token cost first. It shows why you cannot LLM-judge everything online and motivates tiering and sampling.
Hint 2
Measure recall at several points in the pipeline (retriever top-K, after reranking, after context packing). A drop between stages tells you which component is at fault.
Hint 3
For triage, walk the trace in order: was the gold evidence retrieved, did it survive packing, was the answer supported by the context, did it address the question? Each yes/no points at one component.
Hint 4
For a 20-minute CI gate, run cheap deterministic checks on the full set and the LLM judge on a risk-weighted sample, then use paired comparison against the baseline rather than absolute thresholds.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem with numbers
- Traffic: 100K/day is roughly 1.2 QPS average, perhaps 5-10 QPS at peak. Evaluation throughput is trivial, so judge tokens are the real cost.
- Judge cost: one judge call is about 3-5K tokens (query, context, answer, rubric). Judging every request on three metrics is on the order of 1B tokens/day, which is not sensible.
- Policy: run cheap heuristics on 100% of traffic. Run the LLM judge on a ~5% stratified sample plus all flagged traces (thumbs-down, retries, safety hits). That is ~6-8K judged traces/day, around 30M tokens.
- Clarifying questions: what changes per PR (prompt, retriever, chunker, model)? Do tenants permit their traffic to be used for evaluation? What faithfulness floor applies to compliance answers versus general developer questions?
2. Metrics
Retrieval (needs gold chunk labels):
- Context recall@K: fraction of required evidence chunks in the top K.
- Context precision and nDCG@K: relevant chunks ranked high, little noise.
- MRR for single-fact lookups.
- Post-packing recall: recall after reranking and truncation to the context window. Many failures happen here, not in the retriever.
Generation:
- Faithfulness: decompose the answer into atomic claims, check each is entailed by the supplied context; score = supported / total.
- Answer relevance: does it address the question asked?
- Completeness: coverage of a reference key-facts list.
- Citation accuracy: does each cited chunk support the sentence it is attached to?
- Refusal correctness: abstain when evidence is absent, answer when present.
3. Golden dataset
- Seed (~500): written by SMEs (support, compliance). Each item has a query, gold chunk IDs pinned to a document version, a reference answer, key facts, category, difficulty, and risk tier.
- Synthetic (~1,500): an LLM generates questions from sampled chunks, including multi-hop, paraphrased, near-miss (deprecated endpoints), and unanswerable ones. Keep an item only if retrieval recovers its source chunk and an independent model answers it correctly. Humans spot-check ~10%.
- Production mining: triaged thumbs-down traces become regression cases after redaction and rewriting into synthetic tenants.
- Maintenance: invalidate labels when a source document changes; regenerate when the chunker changes; version the dataset with the code.
4. Architecture
- The inference service emits a span per stage (rewrite, retrieve, rerank, pack, generate).
- A redaction gateway runs before persistence: regex for keys and account numbers plus an NER model, replacing values with typed placeholders. Raw text never leaves the tenant boundary.
- A tenant-partitioned trace store with per-tenant encryption keys and row-level ACLs. Judge jobs run under tenant-scoped identities.
- Online evaluator: heuristics on all traffic (citation overlap, answer-context embedding similarity, refusal detector, latency, cost); async LLM judge on the sample.
- Drift and alerting: per-tenant query-embedding centroid shift and out-of-distribution rate, retrieval score distributions, rolling faithfulness, and retry rate (same user rephrasing within ~60 s). Alert on SLO burn (e.g., compliance faithfulness below 0.95) and route pages by component.
- Offline harness replays golden sets against a candidate config using synthetic tenants with mocked authorization.
- RCA service attaches a diagnosis to each trace and feeds a triage dashboard.
Each trace stores: redacted query and embedding, retrieved chunk IDs with retriever/reranker scores and doc versions, which chunks were packed versus truncated, prompt tokens, model and prompt versions, answer and citations, per-stage latency, cost, feedback, and safety flags.
5. CI gating in 20 minutes
- Tier 0 (~3 min, all ~2,000 items): deterministic retrieval metrics against a prebuilt index snapshot, no LLM.
- Tier 1 (~5 min, all items): heuristic generation checks: key-fact matching, lightweight NLI, citation validity, format and refusal checks.
- Tier 2 (~8 min): LLM judge on ~400 risk-weighted items (compliance and past regressions emphasized). 400 items x 3 metrics = 1,200 calls; at 50 concurrent and ~5 s each that is 2-3 minutes, leaving room for retries. Cache by
hash(query, context, answer, judge_version). - Gate rules: hard fail on any safety or cross-tenant test failure, or a compliance faithfulness drop above 1 point. Soft fail on other drops that are significant under a paired bootstrap versus baseline. With ~400 samples, absolute thresholds are too noisy (±2-3 points), so compare paired.
- After merge: full judge suite nightly, then a 5% canary with online metric comparison before full rollout.
- Tenancy tests: plant canary documents belonging to tenant B; if any appear in tenant A's retrieval or answer, fail the build.
6. Root-cause triage
Walk the trace in order:
- Was gold evidence in the retriever's top-K? No: retrieval failure. Sub-diagnose as chunking problem, embedding or query-rewrite miss, stale index, or ACL over-filtering.
- Was it in the top-K but lost after rerank/packing? Yes: reranker or truncation failure; fix budget or ordering.
- Was the context relevant but the answer unsupported? Low groundedness with good context: generation hallucination; fix prompt, model, or add citation enforcement.
- Grounded but not answering the question? Low answer relevance: query understanding or prompt issue.
- Evidence absent and the model answered anyway? Refusal-policy failure.
Without gold labels (live traffic), use the RAG triad as proxies: context relevance (judge or reranker score), groundedness (claim entailment), answer relevance. Low context relevance points at retrieval; high context relevance with low groundedness points at generation. A small classifier or rules engine can output the label with its evidence, exposed as a diagnosis endpoint per trace.
7. Trade-offs
| Approach | Cost/latency | Strength | Weakness |
|---|---|---|---|
| Heuristics, embeddings, NLI-lite | Cheap, ms | Full coverage, stable | Misses subtle unsupported claims |
| LLM judge | Seconds, tokens | Nuanced, claim-level | Noisy, biased, drifts with judge version |
Use heuristics as a wide, cheap screen and the judge as a precise, sampled audit. Calibrate the judge against ~200 human labels, pin its version, and re-calibrate when it changes.
Common mistakes
- Reporting only end-to-end answer quality, so failures cannot be localized.
- Judging all traffic online, or using absolute thresholds on small samples.
- Ignoring post-packing recall and stale gold labels after document updates.
- Logging raw queries before redaction, or sharing judge caches and embeddings across tenants.
- Treating the judge as ground truth without human calibration.