Build a Playbook-Driven Contract Review Pipeline with Citations
System DesignModel answerLast updated
Design an asynchronous service that checks contracts against versioned rule sets, cites exact text spans, proposes edits, assigns a risk tier, and lets reviewers override results.
Problem
A company's legal department wants software that reviews incoming contracts and policy documents against its internal review guidelines (a "playbook"). For each uploaded document, the service should:
- assign an overall risk tier: Approved, Acceptable with Deviations, or High Risk / Escalate;
- propose precise edits (redlines) for clauses that deviate from the playbook;
- tie every finding to the rule that produced it and to the exact passage of the document it concerns;
- combine the opinions of several domain specialists (for example IP, liability, data privacy) and settle cases where they disagree;
- let human reviewers accept, reject, or change any finding or the final tier, and keep those corrections.
Requirements
Functional
- Ingestion: accept PDF and DOCX and keep exact character offsets plus visual coordinates for every piece of text.
- Rules: support both deterministic checks (regex, clause present or absent, date limits, numeric limits) and judgment-based checks done by a model (such as indemnity exposure or whether a non-compete is reasonable).
- Traceability: each finding, score and suggested edit points to an immutable rule ID and version and to an exact span in the source.
- Specialists: run domain specialists in parallel and reconcile conflicting findings.
- Human review: reviewers can override results; all corrections are stored for audit and for later model evaluation.
Non-functional
- 10,000 documents per day, peaking at 1,200 per hour.
- Average length about 25 pages (roughly 16k tokens), maximum 150 pages.
- P95 latency under 30 seconds for typical documents, delivered via polling or webhook.
- At least 99.5% of citations must be correct. Invented quotes or broken offsets are unacceptable.
What to cover
- Schemas for
Rule,DocumentSpan,FindingandEvaluationReport, plus the main API calls. - The pipeline from parsing and offset generation, through deterministic pre-checks and specialist model runs, to conflict resolution and tier assignment.
- How you keep results reproducible when rules change over time.
- How you reconcile specialists that disagree (a priority matrix, an adjudicator model, or both).
- How you would measure quality offline: span accuracy, rule adherence, and edit quality.
Hints
Hint 1
Do the capacity math first. About 0.33 documents per second is small; the real challenge is correctness, so figure out where token cost and the 150-page tail actually bite.
Hint 2
Never let a model emit character offsets. Give it span IDs in the prompt and have a validator check any quoted text against the parser's canonical text before a finding is published.
Hint 3
Make rules and playbooks immutable and content-hashed, pin the version at submission time, and store raw model outputs plus a manifest of parser, model and prompt versions.
Hint 4
For conflicts, order the resolution steps from most to least trustworthy: verified deterministic facts, rule owner, higher severity, then an adjudicator model with human escalation. Compute the final tier with plain code.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
- Throughput: 10k per day is small. The peak of 1,200 per hour is about 0.33 documents per second, so with a 30 s budget only 10 to 15 documents are in flight at once. Quality, not QPS, is the hard part.
- Tokens: a 16k-token document should not be sent whole to every specialist. If a clause router sends each specialist only its relevant sections (about 6 to 10k tokens), four specialists plus an adjudicator cost roughly 50k tokens per document. That is about 500M tokens per day and a peak near 17k tokens per second, so plan for provider rate limits and per-tenant budgets.
- Long tail: a 150-page contract (around 100k tokens) cannot finish in 30 s if processed serially. Split by section, fan out in parallel, and stream partial results. Agree on a looser SLA for oversized documents.
- Core principle: the model is never the source of truth for offsets. The parser owns them; the model only references them.
Also confirm multi-tenancy (each customer has its own playbook), data residency, and whether reviewers need PDF highlight boxes. Assume yes to all.
2. Data model and API
Rule {
rule_id, version (immutable), playbook_id,
type: DETERMINISTIC | SEMANTIC,
domain: IP | LIABILITY | PRIVACY | ...,
severity: BLOCKER | MAJOR | MINOR,
spec: {regex | clause_presence | numeric_limit | date_bound}
| {prompt_template_id, rubric, examples},
preferred_text, fallback_text,
content_hash, author, created_at
}
DocumentSpan {
span_id, doc_id, doc_hash, parser_version,
char_start, char_end, // into canonical normalized text
page, bboxes[],
section_path, node_type
}
Finding {
finding_id, eval_id, rule_id, rule_version,
span_ids[], quote, verdict: PASS|DEVIATION|FAIL|NOT_APPLICABLE,
severity, rationale, confidence,
source: {agent, model_id, prompt_hash} | {engine_version},
suggestion: {span_id, start, end, new_text} | null,
status: PROPOSED|ACCEPTED|REJECTED|MODIFIED,
overrides[]
}
EvaluationReport {
eval_id, doc_id, doc_hash, playbook_version (pinned),
tier, tier_rationale, findings[], resolved_conflicts[],
manifest {parser, models, prompts, rule_hashes}, status
}
API: POST /evaluations returns an eval_id; GET /evaluations/{id} or a webhook returns the result; POST /findings/{id}/override and POST /evaluations/{id}/tier-override record human decisions. Overrides are append-only, so history is never overwritten.
3. Pipeline
- Parse. Read DOCX through its XML tree; for PDFs use layout extraction with OCR fallback. Produce one canonical text and an AST of sections, clauses and tables, each with character ranges and bounding boxes. Store immutably under
(doc_hash, parser_version). - Segment and route. A cheap classifier tags clauses (indemnity, liability cap, governing law, data processing). Each specialist receives only its clauses, cutting tokens by 3 to 5x.
- Deterministic engine. Runs regexes, presence checks, numeric limits and date bounds in milliseconds, emitting findings with exact spans. It also extracts facts (for example "liability cap = $2M") that are passed to the model specialists.
- Specialists in parallel. Prompts contain clauses with inline span IDs such as
[S-0412] ..., the relevant rules, and the extracted facts. Output is schema-constrained JSON: rule ID, verdict, span IDs, verbatim quote, rationale, suggested edit. - Grounding validator (a hard gate, below).
- Conflict resolution (below).
- Tier computation as code, for example: any failed BLOCKER rule gives High Risk; any MAJOR deviation gives Acceptable with Deviations; otherwise Approved. Keeping this out of the model makes it auditable.
- Storage and UI. Postgres for findings, overrides and the audit log; object storage for documents and ASTs; a queue (SQS or Kafka) between stages with workers autoscaling on queue depth.
4. Deep dives
Span grounding
- Models cite span IDs, never offsets.
- Validation: (1) the quote must be an exact substring of the cited span after whitespace and quote normalization using a reversible offset map; (2) otherwise attempt a fuzzy match (edit distance under about 2%) confined to that span, snap to the true text and flag it; (3) otherwise re-prompt once with the error; (4) if it still fails, move the finding to a "needs review" bucket and never publish it as grounded.
- Redlines are applied to verified sub-ranges and exported as tracked changes in DOCX.
- Result: published citations are correct by construction, so the 99.5% target becomes a recall question (did we find everything?) rather than a hallucination question.
Versioning and reproducibility
- Rules are immutable and content-hashed; an edit creates a new version. A playbook version is a manifest of
(rule_id, version)pairs. - Each evaluation pins the playbook version and records parser version, model IDs, prompt hashes and temperature (0).
- Raw model outputs are stored, so any past report can be replayed exactly from storage. Re-running the models gives only a close reproduction, since LLMs are not bit-deterministic.
Conflict resolution
Flag a conflict when findings overlap in span or rule area but differ in verdict or severity. Resolve in order:
- Deterministic veto: a code-verified fact beats a model opinion.
- Domain ownership: the specialist that owns the rule wins.
- Severity precedence: otherwise take the higher severity. This is deliberately conservative, since a false "Approved" costs more than an unnecessary escalation.
- Adjudicator model: only for leftover semantic disputes; it must cite spans, and low-confidence results go to a human.
Log each resolution and its reason.
5. Evaluation and QA
- Golden set: a few hundred contracts annotated by attorneys with expected findings, spans, tiers and acceptable edits. Refresh it regularly and stratify by contract type and length.
- Span metrics: exact-quote match rate (should be 100% post-validator), span-level precision and recall, and IoU against annotated ranges.
- Rule adherence: per-rule precision and recall, with extra weight on BLOCKER rules; track tier confusion matrix, especially false "Approved".
- Suggestion quality: does the edit apply cleanly, does it match the playbook's preferred or fallback language, and do attorneys accept it? Use rubric-based LLM grading calibrated against human ratings.
- Online: reviewer acceptance, rejection and modification rates become labeled data; sample audits of auto-approved documents; regression-test every rule, prompt or model change against the golden set before rollout.
6. Trade-offs and common mistakes
- Letting the model produce offsets or quotes without verification is the most common failure.
- Sending the full document to every specialist inflates cost and latency with little accuracy gain.
- Using an LLM to decide the final tier makes outcomes hard to audit.
- Updating rules in place breaks reproducibility.
- Optimizing for average latency while ignoring the 150-page tail.
- Not isolating tenant playbooks and data.