Designing a Quality Gate for a Permission-Aware Document Q&A Assistant
Machine LearningModel answerLast updated
Design an offline and online evaluation system for a retrieval-based enterprise assistant, covering retrieval, faithfulness, citations, abstention, access control, freshness and cost.
Scenario
Your company is rolling out a chat assistant that lets employees ask questions about internal material: engineering specs, financial reports, HR policies and customer contracts. People will make real decisions from its answers, so invented facts, outdated information and exposure of documents a user should not see are all serious failures.
You must design the evaluation framework used to gate releases, monitor production and drive improvement of this retrieval-augmented generation (RAG) assistant.
Assumptions
- Corpus: 10 million documents in several access tiers, updated incrementally every day.
- Traffic: peak of 50 queries per second, with a p95 end-to-end latency target under 2.0 s.
- Budget: average inference cost under $0.02 per query.
- Labels: 5,000 expert-curated (query, context, answer) examples exist for regression testing. You may also generate synthetic evaluation data.
What your design must cover
- Component-level evaluation
- Retrieval quality for dense and hybrid retrievers, measured independently of the generator.
- Generation quality: faithfulness to the retrieved context, relevance to the question, and completeness.
- Claim-level attribution: do the inline citations really support the specific claims they are attached to?
- Enterprise safety constraints
- Abstention and negative testing (out-of-scope questions, missing evidence, contradictory sources).
- Permission enforcement: how to test that users cannot obtain content outside their role or attributes.
- Freshness: how to detect regressions when documents change version or contradict earlier snapshots.
- Online monitoring
- Implicit signals (source clicks, dwell time, follow-up behavior) and explicit signals (ratings, corrections).
- Production guardrails: latency, token budgets, and sampled drift and hallucination checks.
Deliverables
- A flow or diagram contrasting the offline evaluation harness with online telemetry.
- How you would build and maintain the evaluation dataset (human-labeled vs. synthetic).
- Metric definitions, how you would calibrate an LLM judge, and which checks can be deterministic.
- The trade-offs between evaluation depth, speed and cost in a CI/CD pipeline.
Hints
Hint 1
Evaluate retrieval and generation separately. One useful trick is to run the generator once with retrieved context and once with the known-correct context, then compare the outcomes to see where the fault lies.
Hint 2
Split requirements into hard gates (permission leakage, fabricated numbers) that must be exactly zero and soft quality metrics you try to improve. Do not average the two together.
Hint 3
Do the arithmetic on volume and cost: 50 QPS is on the order of a million or more queries a day, so judging with an LLM on every request is unaffordable and must be sampled or done offline. Inline checks need to be deterministic or tiny models.
Hint 4
Every label must be tied to a document version, otherwise daily updates will silently make your gold set wrong.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
- Failure attribution: you can tell whether a bad answer came from retrieval or generation.
- Gates vs. goals: security and factual integrity are pass/fail; relevance and completeness are tuned.
- Budget realism: the design fits 50 QPS, 2 s p95 and $0.02 per query.
1. Scale and risk framing
- 50 QPS peak is roughly 1-2M queries a day. Judging all of them with an LLM at about $0.005 each would consume a quarter of the per-query budget, so online judging is sampled (1-5%, stratified by domain and tier). At 1%, that is 10-20k judgments a day, or about $50-100.
- Inline guardrails must add under about 100 ms, so only deterministic rules and small classifiers sit in the request path.
- Zero-tolerance: unauthorized content exposure and fabricated figures in finance or contracts. They block a release.
- Optimization targets: relevance, completeness, style, latency.
2. Architecture
Offline harness (CI and nightly): gold, synthetic and adversarial sets run against a frozen snapshot of the index (pinned versions). The retriever is scored on its own. The generator is then run on retrieved context and on oracle (gold) context. Claims are split, checked by NLI or a judge plus deterministic rules, and results roll into a scorecard with release gates. Failures found online are mined back into the test sets.
Online telemetry: query goes through permission-filtered retrieval, the LLM, and inline guardrails (citation exists, ACL re-check, schema and PII checks). A trace is logged with doc IDs and versions, prompt, answer, latency breakdown, tokens and cost. A sample goes to an async judge; feedback events go to a triage queue for human review.
Oracle-context diagnosis:
| Retrieved context | Gold context | Diagnosis |
|---|---|---|
| Wrong answer | Right answer | Retrieval failure |
| Wrong answer | Wrong answer | Generation failure |
3. Metrics
Retrieval (cheap, no LLM):
- Recall@K at the real context size (e.g. K=10): the generator cannot use evidence it never saw.
- MRR for the first relevant chunk, NDCG@10 with graded relevance.
- Context precision (share of retrieved chunks that matter), which affects token cost and distraction.
- Report dense, BM25 and hybrid separately, sliced by domain and access tier.
Generation:
- Groundedness = supported claims / total claims.
- Answer relevance via a judge.
- Completeness = fraction of gold atomic claims covered.
Claim-level attribution:
- Split the answer into atomic claims.
- For each cited claim, run NLI with the cited span as premise and the claim as hypothesis (entail, neutral, contradict).
- Citation precision = citations that entail their claim / all citations. Citation recall = factual claims with a supporting citation / all factual claims.
- A contradiction on a number, date or amount is a severity-1 failure.
Deterministic checks: cited chunk is in the retrieved set; numbers and dates in the answer appear verbatim in the cited span; every cited document passes the user's ACL; schema is valid; no PII patterns.
4. Safety and enterprise constraints
Abstention: treat it as a classifier with its own labels (answer, abstain, deny). Report abstention precision (refusals that were right) and recall (unanswerable queries correctly refused), plus the over-refusal rate on answerable queries. Negative sets include out-of-scope queries, queries whose gold document was removed from the index, and conflicting sources (expected: flag the conflict, not pick silently).
Access control: persona-based probes target documents above the persona's tier, including paraphrases, multi-turn extraction and aggregation attacks (combining permitted fragments to infer restricted facts). Check both retrieval logs and final text. The target is exactly zero leakage; any single leak fails the build. Also test prompt injection placed inside documents.
Freshness and version drift: every eval record pins doc_id@version. The ingestion change feed triggers re-validation of affected items. Include temporal tests (new policy supersedes old) and check that the answer cites the current version. Alert when the share of citations to superseded versions rises.
5. Dataset methodology
- Human gold set (5k): expert-written, stratified by domain and difficulty, used as the calibration anchor. Retire roughly 5% per quarter and refill with mined production failures.
- Synthetic set: generate questions from sampled chunks, filter with round-trip checks (source chunk retrievable, answer entailed), and have humans spot-check about 10%. It scales coverage but skews toward easy extractive questions, so never gate a release on synthetic data alone.
- Adversarial set: the negative and security cases above, always curated by humans.
- Record schema: query, persona, gold docs@version, gold spans, gold answer, atomic claims, expected behavior, category, timestamps.
6. LLM-judge calibration
- Use a rubric with discrete scores and require the judge to quote the evidence.
- Calibrate against a human-labeled subset: report agreement (Cohen's kappa) and per-class precision and recall, and re-check on every judge or prompt change.
- Mitigate position and verbosity bias, use a different model family from the generator, and keep the judge's version pinned.
- Use deterministic checks wherever possible; the judge handles only what rules cannot.
7. Online monitoring
- Implicit: source clicks, dwell time, reformulated or repeated queries, negative follow-up sentiment.
- Explicit: thumbs and user corrections, which feed the triage queue and later the gold set.
- Guardrails: p50/p95/p99 latency by stage, token usage and cost per query against the $0.02 ceiling, citation-validity rate, abstention rate, and sampled hallucination rate with alert thresholds. Watch for embedding or query-distribution drift.
8. CI/CD trade-offs
| Stage | Contents | Cost / time |
|---|---|---|
| Per commit | Deterministic checks, retrieval metrics, small smoke set | Minutes, near zero |
| Pre-release | Full 5k gold set, adversarial and ACL suites, judge-scored | Tens of minutes, moderate |
| Nightly | Synthetic sets, freshness re-validation, judge recalibration | Hours, higher |
Use paired comparisons and confidence intervals to avoid chasing noise. Hard gates (leakage = 0, no severity-1 numeric contradictions, no latency or cost regression) block; soft metrics must not regress beyond a tolerance.
Common mistakes
- Reporting only end-to-end answer quality, which hides whether retrieval or generation is at fault.
- Averaging security failures into an overall score.
- Putting an LLM judge in the request path.
- Letting gold labels go stale because they are not tied to document versions.
- Trusting an uncalibrated judge or relying only on synthetic data.