Building a Permission-Aware Document Q&A Assistant with Citations
Machine LearningModel answerLast updated
Design a retrieval-augmented question-answering assistant over internal company documents, with ML detail on each stage, document-level access control, grounded cited answers and failure handling.
Problem
Your company wants a chat assistant that lets employees ask questions about internal knowledge: policies, wiki pages, design specs, support tickets and PDFs. The assistant should use retrieval-augmented generation, so answers come from retrieved passages rather than from the model's memory alone.
The discussion should concentrate on modeling and training decisions, not on generic infrastructure.
Constraints to assume
- Each user may only see documents they are authorized to read.
- Answers must be grounded in retrieved passages and carry citations.
- If the documents do not support an answer, the assistant should say so rather than guess.
What to cover
- Propose an end-to-end design split into three parts:
- a retriever that produces candidate passages,
- an evaluator that reranks, verifies or filters them,
- a generator that writes the cited answer.
- For each part, explain:
- the model architecture and why you chose it,
- the training objective or loss,
- the optimizer and training recipe (batching, negatives, schedule, precision),
- how you prepare training data (labels, weak supervision, synthetic data, privacy),
- how you evaluate it offline, with humans, and in production.
- Explain how your design handles the typical failure modes: hallucination, outdated content, contradictory sources and very long documents.
State your scale and latency assumptions up front and justify them.
Hints
Hint 1
Start by fixing assumptions (users, corpus size, latency budget, hard constraints) and then walk the pipeline: ingest and chunk, hybrid retrieve, rerank and verify, generate, then check citations.
Hint 2
Think about where the permission filter belongs. Applying it before ranking, inside the index, avoids leaking information through scores or snippets, and caches must be keyed by access group.
Hint 3
For each stage, pair a loss with a data source: contrastive loss with hard negatives for the retriever, listwise loss for the reranker, supervised fine-tuning plus preference tuning with deliberately unanswerable examples for the generator.
Hint 4
Map every failure mode to a concrete mechanism: abstention training for hallucination, version and recency handling for stale content, conflict-aware training examples for contradictions, structure-aware chunking for long documents.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions
- About 50k employees, roughly 50 QPS at peak, p95 latency under 4 s and first token under 1.5 s.
- About 10M documents, which at roughly 20 chunks each is around 200M chunks, with about 1% daily churn.
- Hard requirements: document-level ACLs, a citation for every factual claim, abstention when evidence is missing, and data staying inside the company boundary.
- Success metrics: answer correctness, faithfulness (share of claims supported by the cited text), citation precision and recall, abstention accuracy, and ticket deflection.
2. Pipeline overview
Ingestion: connectors per source, layout-aware parsing for PDFs and tables, structure-aware chunking (300-500 tokens, each chunk prefixed with title and section path), near-duplicate and version collapse, embedding, and ACL sync on every update. Each chunk stores doc_id, version, updated_at, is_latest, source_type, owner and acl_principals.
Query path: rewrite the query (resolve coreference, expand acronyms), run hybrid retrieval, rerank, verify answerability, generate with citations, then run a post-hoc claim check.
Permissions: apply the ACL filter inside the index search, before ranking. Post-filtering leaks through scores, counts and snippets. Key caches by the user's group set, and run leakage tests using synthetic users with known visibility.
3. Retriever
Architecture: a bi-encoder of about 300M parameters (E5/BGE class), mean pooling, 768-d output. Train with Matryoshka objectives so 256-d vectors can be stored cheaply. Keep BM25 alongside it, because internal text is full of ticket IDs, error codes and codenames where lexical match wins. Merge the two lists with reciprocal rank fusion into about 200 candidates.
Loss: InfoNCE with in-batch plus mined hard negatives, temperature around 0.02-0.05. Add distillation from the cross-encoder (KL over candidate score distributions or MarginMSE) to transfer reranker quality into the cheap stage.
Recipe: AdamW, lr about 2e-5, 5% warmup, linear decay, bf16. Contrastive learning benefits from large batches (4k-16k effective), so use gradient caching. Mine hard negatives from BM25 and the previous checkpoint and refresh each epoch. Filter false negatives (anything the teacher scores highly), since wikis contain many near-duplicates.
Data:
- Synthetic questions: an LLM writes 3-5 questions per chunk, kept only if the chunk is retrieved in top-k for its own question (round-trip consistency).
- Weak labels: ticket title to resolution doc, search clicks, clicked citations.
- A human-labeled golden set of about 2k queries for evaluation.
Privacy: train and generate inside the tenant, scrub PII before any external labeling, and prefer per-tenant adapters (LoRA) over pooling data into shared weights, since memorization can leak restricted content.
Evaluation: Recall@100 (what the reranker depends on) and nDCG@10, sliced by source type and freshness. Online, track how often final answers cite retrieved material and how often "no relevant docs" triggers abstention.
4. Evaluator
Reranker: a cross-encoder of 0.5-1B parameters over [query; section_path; chunk], optionally with recency, authority and owner features. It scores 200 candidates and keeps about 8, which fits the budget with GPU batching.
- Loss: listwise softmax cross-entropy with 1 positive and about 15 hard negatives; alternatively distill graded 0-3 labels from an LLM judge with KL.
- Recipe: AdamW lr 1e-5, 32 queries x 16 docs per batch, bf16, 1-2 epochs (cross-encoders overfit fast).
- Labels: LLM-judge relevance, calibrated against about 1k human-graded pairs, reporting judge-human agreement (Cohen's kappa).
Answerability verifier: a small classifier predicting P(answerable | query, top-k). Train with BCE, including examples where the gold chunk was deliberately removed. Calibrate with temperature scaling and pick the threshold to trade coverage against hallucination risk.
Claim-support checker: an NLI-style model run after generation that tests each sentence against its cited chunk and drops or flags unsupported claims.
Evaluation: nDCG@10 and P@5 for reranking; AUROC and expected calibration error for the verifier; abstain precision (when it abstains, was the answer really absent?).
5. Generator
Architecture: an instruction-tuned long-context LLM. Use a frontier model with prompting, or a fine-tuned open model if cost or residency demands. Pass chunks with IDs, titles and updated_at so the model can cite and reason about recency.
SFT (RAFT-style): examples of (query, gold chunks + distractors) to an answer with [n] citations. About 20% have no gold chunk and the target is a calibrated abstention. Include conflict examples where the answer cites both sources and prefers the newer or more authoritative one, saying so. Loss is token cross-entropy on answer tokens only.
Preference tuning: DPO (beta about 0.1) with chosen = fully supported and correctly cited, rejected = hallucinated, uncited, mis-cited or conflict-ignoring. Alternatively RL with reward = faithfulness + citation precision/recall - length penalty.
Recipe: LoRA at lr 1e-4 or full fine-tuning at 1e-5, cosine schedule, bf16, sequence packing, gradient checkpointing. Train on context lengths matching production to avoid "lost in the middle" behavior.
Data: teacher-LLM-drafted Q&A from real chunks, filtered by the claim checker and spot-audited by humans; synthetic distractors and removed-evidence cases; all kept inside the tenant.
Evaluation: human and LLM-judge scoring of correctness, faithfulness and citation quality on the golden set; red-team sets for permission leakage and prompt injection from document content.
6. Failure modes
| Failure | Mitigation |
|---|---|
| Hallucination | Abstention-trained SFT, verifier threshold, DPO on unsupported answers, post-hoc claim check |
| Stale content | is_latest and version collapse, recency feature in reranker, updated_at shown to generator, fast re-indexing of changed docs |
| Conflicting docs | Conflict training examples, authority features, answer states the disagreement and which source it prefers |
| Long documents | Structure-aware chunks with section-path prefixes, retrieve then expand to neighbor chunks, parent-document context for the generator |
7. Production monitoring and feedback
Log thumbs up/down and flagged citations, sample answers for weekly human grading, and track faithfulness, abstention rate and ACL-leak canaries. Use feedback to mine new hard negatives and preference pairs, with periodic retraining and regression runs on the golden set before release.
Common mistakes
- Filtering by permission after ranking.
- Training the retriever without false-negative filtering on duplicate-heavy corpora.
- Dropping BM25 and losing exact-identifier queries.
- Never training on unanswerable cases, so the model always answers.
- Evaluating only answer fluency, not faithfulness and citation correctness.
- Using one uncalibrated LLM judge without human agreement checks.