CoverageCheck / src /coveragecheck /web /architecture.py
TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
27.8 kB
# ruff: noqa: E501 (a content file: its long lines are prose sentences, kept whole)
"""Step 9d: the content of the Architecture page (web/public/data/architecture.json).
Redesigned after the owner's review (2026-11-24: "very confusing, not easy to read"),
from public guidance on presenting systems:
- one level of detail per diagram (C4 model): an overview strip of 5 steps, then one
chapter per step, each with its own small diagram (3-7 boxes, no crossing lines);
- compare designs side by side (small multiples): System A | B | C as aligned columns,
the same steps on the same rows, an empty slot where a system has no such step;
- text drives the diagram (explorable explanations, scrollytelling): each chapter is a
list of steps, and the boxes a step talks about light up;
- plain language: every step leads with its point in one short sentence, then two or
three short sentences (tests enforce at most 15 and 25 words); the numbers, a real
example and what was tried sit behind "Details".
Every number is computed from the tables, config, runs and question files (or quoted
from SPEC as a measurement), so the page cannot drift from the data. Layout is the
frontend's job (web/src/pages/ArchitecturePage.tsx); this file says what the boxes ARE.
Local only (reads evals/runs): `uv run python -m coveragecheck.web.export`.
"""
import json
from collections import Counter
from pathlib import Path
import pandas as pd
from coveragecheck import config
from coveragecheck.index.store import load_table
EXAMPLE = "H016" # the held-out question the examples follow (also on the Evals page)
VERIFY_EXAMPLE = "H070" # a held-out run where C's quote check made it retry
def n(value: int | float) -> str:
"""A count as people write it: 1,247."""
return f"{value:,}"
def clip(text: str, limit: int = 420) -> str:
"""At most `limit` characters on one line, cut at a word."""
text = " ".join(str(text).split())
return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0] + " ..."
def box(title: str, sub: str = "") -> dict:
return {"title": title, "sub": sub}
def step(id_, point, body, highlight, numbers=(), example=None, tried=(), files=()):
"""One step of a chapter: its point (one short sentence), the body (two or three
short sentences), the boxes it lights up, and its details."""
return {
"id": id_,
"point": point,
"body": body,
"highlight": list(highlight),
"details": {
"numbers": [{"label": label, "value": value} for label, value in numbers],
"example": example,
"tried": list(tried),
"files": list(files),
},
}
def example(title: str, body: str) -> dict:
return {"title": title, "body": body}
def run_row(path: Path, qid: str) -> dict:
frame = pd.read_parquet(path)
row = frame[frame.question_id == qid].iloc[0].to_dict()
row["trace"] = json.loads(row.get("trace_json") or "{}")
return row
def build(runs: dict[str, Path], evals: dict) -> dict:
"""The page: an overview of 5 steps and one chapter per step. runs: the held-out run
files (a, b, c); evals: the Evals page's data (evals_data)."""
chunks = load_table(config.INDEX_DIR / "chunks.parquet")
sections = load_table(config.INDEX_DIR / "sections.parquet")
windows = load_table(config.INDEX_DIR / "naive_chunks.parquet")
xrefs = load_table(config.INDEX_DIR / "xrefs.parquet")
manifest = pd.read_csv(config.DATA_DIR / "manifest.csv", dtype=str).fillna("")
heldout = [
json.loads(x)
for x in config.HELDOUT_PATH.read_text(encoding="utf-8").splitlines()
if x.strip()
]
draft = [x for x in config.QUESTIONS_PATH.read_text(encoding="utf-8").splitlines() if x.strip()]
probes = [
x
for x in (config.EVALS_DIR / "dev_probes.jsonl").read_text(encoding="utf-8").splitlines()
if x.strip()
]
review = config.EVALS_DIR / "heldout_review" / "verdicts.json"
verdicts = json.loads(review.read_text(encoding="utf-8"))["verdicts"] # keep / fix / drop
a, b, c = (run_row(runs[s], EXAMPLE) for s in "abc")
retried = run_row(runs["c"], VERIFY_EXAMPLE)["trace"]["verify"]
forms = manifest.form_id.str.startswith(("OAP", "OPCF"))
opcf = int(manifest.form_id.str.startswith("OPCF").sum())
laws = int((~forms).sum())
pdfs = int(manifest.filename.str.lower().str.endswith(".pdf").sum())
dated = int((manifest.effective_from != "").sum())
status = Counter(xrefs.status)
sabs = manifest.set_index("doc_id").loc[["SABS-2025", "SABS-2026"]]
chunk = chunks.set_index("chunk_id").loc["OPCF44R-2026#4:0"]
window = windows.iloc[int((windows.doc_id == "OPCF44R-2026").idxmax()) + 1]
xref = xrefs[(xrefs.status == "resolved") & (xrefs.target_source_id == "INSACT-2026#268")].iloc[
0
]
sys_ = evals["systems"]
evidence = {e["label"]: e for e in evals["evidence"]}
two_docs = next(g for g in evals["by_docs"] if g["group"] == "2")
categories = Counter(q["category"] for q in heldout)
written = sum(verdicts.values())
accuracy = {s: f"{sys_[s]['accuracy']:.0%}" for s in "abc"}
seconds = {s: f"{sys_[s]['latency_p50_ms'] / 1000:.0f} s" for s in "abc"}
overview = [
{"id": "documents", "title": "Documents", "line": f"{len(manifest)} public forms and laws"},
{"id": "prepare", "title": "Prepare", "line": "parse, split by section, link references"},
{"id": "evidence", "title": "Find the evidence", "line": "three designs: A, B and C"},
{"id": "answer", "title": "Answer & check", "line": "same model, every quote verified"},
{"id": "measure", "title": "Measure", "line": "a blind test, paired statistics"},
]
documents = {
"id": "documents",
"title": "The documents",
"lead": "Every answer comes from public documents only, so anyone can check it.",
"diagram": {
"kind": "documents",
"boxes": {
"oap": box("OAP 1", "the standard owner's policy"),
"opcf": box(f"{opcf} OPCF forms", "endorsements that change the policy"),
"laws": box(f"{laws} Ontario laws", "accident benefits, Insurance Act, ..."),
"corpus": box(f"{len(manifest)} documents", "each pinned by its fingerprint"),
},
},
"steps": [
step(
"what",
f"Answers come only from {len(manifest)} public documents.",
f"The standard Ontario auto policy, its {opcf} change forms, and {laws} laws they rely on. All are public, so anyone can check an answer.",
["oap", "opcf", "laws"],
[
("Documents", n(len(manifest))),
("PDF forms / laws", f"{pdfs} / {len(manifest) - pdfs}"),
],
files=["data/manifest.csv", "data/CORPUS.md"],
),
step(
"pinned",
"Every file is pinned, and nothing is scraped.",
"The regulator's sites block automated downloads. So the files were saved by hand, and each one is checked against its fingerprint (SHA-256).",
["corpus"],
files=["src/coveragecheck/ingest/download.py"],
),
step(
"dates",
"Dates matter: some laws exist in two versions.",
f"Accident benefits (SABS) changed on {sabs.loc['SABS-2026', 'effective_from']}. The same question can have two answers, one per version. Only {dated} of the {len(manifest)} documents state their dates.",
["laws"],
[("Documents with stated dates", f"{dated} of {len(manifest)}")],
example(
"Two versions of one law",
f"SABS 2025: in force {sabs.loc['SABS-2025', 'effective_from']} to {sabs.loc['SABS-2025', 'effective_to']}\nSABS 2026: in force from {sabs.loc['SABS-2026', 'effective_from']}",
),
),
step(
"left-out",
"Some documents are left out on purpose.",
"Change forms the regulator does not publish (OPCF 8, 13C, 39) are not here. Questions about them must be declined: a test of honesty.",
["corpus"],
tried=[
"The rest of the Insurance Act: about insurers in general, only noise",
"The Statutory Conditions regulation: already word for word in OAP 1",
],
),
],
}
prepare = {
"id": "prepare",
"title": "Preparing the documents",
"lead": "Structure is kept, so every passage knows its section and can be cited exactly.",
"diagram": {
"kind": "prepare",
"boxes": {
"docs": box(f"{len(manifest)} documents"),
"parse": box("Parse", "headings, sections, pages"),
"sections": box(
f"{n(len(sections))} sections", f"{n(len(chunks))} chunks, for B and C"
),
"refs": box(
f"{n(len(xrefs))} cross-references",
f"{n(status['resolved'])} linked to their section",
),
"windows": box(f"{n(len(windows))} windows", "fixed size, for A"),
"index": box("Search indexes", "exact words + meaning"),
},
},
"steps": [
step(
"parse",
"Each document is read with its structure kept.",
"A parser (Docling) turns each PDF into headings, paragraphs, tables and pages. The laws come as Word files whose styles mark each section.",
["docs", "parse"],
example=example(
"A heading path kept from the structure",
sections.set_index("source_id").loc["SABS-2026#31", "heading_path"],
),
tried=[
"Detecting tables of contents from text alone: it dropped real fill-in lines"
],
files=["src/coveragecheck/ingest/parse.py"],
),
step(
"sections",
"B and C split documents by section, never across one.",
"A rule only makes sense under its heading. So every chunk stays inside one section and can be cited by its number.",
["sections"],
[
("Sections", n(len(sections))),
("Chunks", n(len(chunks))),
("Typical chunk", f"{n(int(chunks.text.str.len().median()))} characters"),
],
example(
f"A chunk ({chunk.name})", f"{chunk.heading_path}\n{clip(chunk.text, 280)}"
),
files=["src/coveragecheck/ingest/chunk.py"],
),
step(
"refs",
"Every cross-reference is linked to the section it names.",
f'Policy text often says "subject to section 268". Each such reference is found and linked: {status["resolved"] / len(xrefs):.0%} reach a section in the corpus.',
["refs"],
[
("References found", n(len(xrefs))),
("Linked to a section", n(status["resolved"])),
("Outside the corpus", n(status["out_of_corpus"])),
],
example(
"A linked reference",
f'"{xref.match}" in {xref.chunk_id}\n-> {xref.target_source_id}',
),
files=["src/coveragecheck/ingest/xref.py"],
),
step(
"windows",
"System A gets plain windows, as in a basic tutorial.",
f"A cuts each document into {config.NAIVE_CHUNK_CHARS}-character windows and ignores headings. It is the baseline that shows what structure is worth.",
["windows"],
[
("Windows", n(len(windows))),
(
"Size / overlap",
f"{config.NAIVE_CHUNK_CHARS} / {config.NAIVE_CHUNK_OVERLAP} characters",
),
],
example(
f"A window ({window.chunk_id}): it starts mid-sentence", clip(window.text, 260)
),
),
step(
"index",
"Two search indexes: one for exact words, one for meaning.",
'Keyword search (BM25) finds exact terms like "OPCF 44R". Meaning search finds paraphrases like "my client\'s son". B and C use both.',
["index"],
[
("Meaning model", config.EMBED_MODEL),
("Search time (measured, SPEC 3d)", "7 to 12 ms"),
],
tried=["A vector database: the 906 chunks fit in memory"],
files=["src/coveragecheck/index/hybrid.py"],
),
],
}
judge = c["trace"].get("judge", {})
evidence_ch = {
"id": "evidence",
"title": "Finding the evidence: three designs",
"lead": "The three systems differ only here: how they find the passages the answer will use.",
"diagram": {
"kind": "grid",
"columns": {
s: {"title": f"System {s.upper()}", "name": sys_[s]["name"]} for s in "abc"
},
"rows": [
{
"id": "question",
"label": "Question",
"cells": {s: box("Question + policy date") for s in "abc"},
},
{
"id": "search",
"label": "Search",
"cells": {
"a": box("Meaning search", f"top {config.NAIVE_TOP_K} windows"),
"b": box(
"Words + meaning",
f"{config.CANDIDATE_K} + {config.CANDIDATE_K} candidates",
),
"c": box("Words + meaning", f"top {config.JUDGE_DEPTH} kept"),
},
},
{
"id": "date",
"label": "Date filter",
"cells": {
"a": None,
"b": box("Versions in force", "on the policy date"),
"c": box("Versions in force", "on the policy date"),
},
},
{
"id": "pick",
"label": "Pick the best",
"cells": {
"a": None,
"b": box("Reranker", f"a small model keeps {config.RERANK_TOP_K}"),
"c": box("LLM judge", "lists the facts needed"),
},
},
{
"id": "again",
"label": "Search again",
"cells": {
"a": None,
"b": None,
"c": box("Second search", "for any missing fact"),
},
},
{
"id": "cited",
"label": "Add cited sections",
"cells": {
"a": None,
"b": box("Cited sections", f"up to {config.MAX_XREF_EXPANSION} more"),
"c": box("Cited sections", f"up to {config.MAX_XREF_EXPANSION} more"),
},
},
],
"results": {s: {"accuracy": accuracy[s], "time": seconds[s]} for s in "abc"},
},
"steps": [
step(
"question",
"All three get the same question and policy date.",
"In the chat, a follow-up is first rewritten into a complete question. Then each system answers it exactly as it was tested.",
["question"],
example=example(
"A follow-up, rewritten (live test)",
'"And what is the most it will pay?"\n-> "Under OPCF 44R, what is the most the insurer will pay if the at-fault driver has no insurance at all?"',
),
files=["src/coveragecheck/web/followup.py"],
),
step(
"search",
"A searches by meaning only; B and C also match exact words.",
'Insurance questions mix exact terms ("OPCF 44R") with everyday wording. Combining both kinds of search covers each one\'s blind spot.',
["search"],
[("Passages fused by rank", f"Reciprocal Rank Fusion, k = {config.RRF_K}")],
example(
f"{EXAMPLE}: the windows A read", "\n".join(list(a["retrieved_chunk_ids"]))
),
files=["src/coveragecheck/retrieve/naive.py", "src/coveragecheck/index/hybrid.py"],
),
step(
"date",
"B and C only search versions in force on the policy date.",
"A policy dated October 2025 must use the 2025 accident benefits, not the 2026 reform. System A is only told the date.",
["date"],
example=example(
"A policy date of 2025-10-01",
f"SABS 2025 (in force {sabs.loc['SABS-2025', 'effective_from']} to {sabs.loc['SABS-2025', 'effective_to']}): searched\nSABS 2026 (from {sabs.loc['SABS-2026', 'effective_from']}): excluded",
),
),
step(
"pick",
"B reorders the passages; C reads them and lists what the answer needs.",
"B's reranker scores each passage against the question. C's judge, a language model, writes down each fact the answer needs and which passage states it.",
["pick"],
[
(
"B: passages reranked / kept",
f"{config.RERANK_DEPTH} / {config.RERANK_TOP_K}",
),
("C: facts listed at most", str(config.MAX_REQUIREMENTS)),
],
example(
f"{EXAMPLE}: the facts C looked for",
"\n".join(
("found: " if r["stated_by"] else "missing: ") + r["need"]
for r in judge.get("requirements", [])
),
),
tried=[
f"Reranking every candidate: worse and slower than the top {config.RERANK_DEPTH} (tuned on the practice questions)"
],
files=[
"src/coveragecheck/retrieve/structured.py",
"src/coveragecheck/agent/judge.py",
],
),
step(
"again",
"Only C searches again when a needed fact is missing.",
f"If no passage states a fact, C searches for it and reads the new passages. On questions needing two documents, C is right {two_docs['c']['accuracy']:.0%} of the time, B {two_docs['b']['accuracy']:.0%}.",
["again"],
[
(
"Second searches on the final test",
f"{evidence['second search']['n']} of {len(heldout)} questions",
),
("Searches at most", str(config.MAX_SUBQUERIES)),
],
example(
f"{EXAMPLE}: C's second search",
"\n".join(c["trace"].get("research", {}).get("queries", [])) or "not needed",
),
files=["src/coveragecheck/agent/graph.py"],
),
step(
"cited",
"B and C also fetch the sections their passages cite.",
f'When a passage says "subject to section 268", that section is added too. At most {config.MAX_XREF_EXPANSION} passages are added this way.',
["cited"],
tried=[
f"Adding very long sections (over {n(config.XREF_MAX_TARGET_CHARS)} characters): measured useless"
],
),
],
}
answer = {
"id": "answer",
"title": "Answering and checking",
"lead": "The same answer step for all three systems, then every quote is checked.",
"diagram": {
"kind": "answer",
"boxes": {
"passages": box("The selected passages"),
"answer": box("Answer", "Claude Haiku, same prompt for all"),
"check": box("Quote check", "every quote, word for word"),
"retry": box("Retry once", "System C only"),
"reply": box("Answer with sources", 'or "can\'t determine"'),
},
},
"steps": [
step(
"same",
"All three answer with the same model and instructions.",
"Claude Haiku answers from the passages only and quotes each claim. So any difference comes from what each system found.",
["passages", "answer"],
[
("Model", "Claude Haiku 5.5"),
("Re-asks after an invalid reply", str(config.LLM_MAX_REASKS)),
],
example(f"{EXAMPLE}: C's answer", clip(c["answer"], 320)),
tried=["Gemini: too slow and often unavailable in the benchmark"],
files=["src/coveragecheck/agent/answer.py"],
),
step(
"decline",
"When the documents can't answer, it says so.",
f'It replies "can\'t determine" and lists what a broker would need to find out. On the {categories["unanswerable"]} unanswerable test questions, C declined every one.',
["reply"],
[
(f"Correctly declined: {s.upper()}", f"{sys_[s]['abstention']:.0%}")
for s in "abc"
],
),
step(
"check",
"Every quote is checked word for word against its source.",
'Numbers and words like "not" must match exactly. A quote with one digit changed never passes.',
["check"],
[
(
f"Quotes not word for word: {s.upper()}",
f"{sys_[s]['citations']['not_exact']:.1%} of {n(sys_[s]['citations']['count'])}",
)
for s in "abc"
],
tried=["A fuzzy match alone: it accepted every quote with one number changed"],
files=["src/coveragecheck/verify/citations.py"],
),
step(
"retry",
"System C checks its own quotes before replying.",
"If a quote fails, C is told why and answers again, once. Quotes that still fail are dropped, and its confidence is lowered.",
["check", "retry"],
example=example(
f"{VERIFY_EXAMPLE}: C caught its own quotes",
"\n".join(retried["failed_first"])
+ f"\n-> answered again; {retried['dropped']} quote dropped",
),
files=["src/coveragecheck/agent/verify.py"],
),
],
}
measure = {
"id": "measure",
"title": "Measuring honestly",
"lead": "The final test was written blind, after the systems were frozen.",
"diagram": {
"kind": "measure",
"boxes": {
"tuning": box(
"Practice questions", f"{len(probes)} probes + {len(draft)} development"
),
"heldout": box("Final test", f"{len(heldout)} blind questions"),
"grading": box("Grading", "an AI grader, blind"),
"stats": box("Statistics", "paired, with intervals"),
"results": box("Results", " / ".join(f"{s.upper()} {accuracy[s]}" for s in "abc")),
},
},
"steps": [
step(
"tuning",
"Every setting was tuned on separate practice questions.",
f"{len(probes)} probes and {len(draft)} development questions were used to tune. None of them is in the final test.",
["tuning"],
files=["evals/dev_probes.jsonl", "evals/questions.jsonl"],
),
step(
"heldout",
"The final test was written blind, after the systems were frozen.",
f"Separate AI writers saw only the documents, never the systems. Reviewers kept {verdicts['keep']}, fixed {verdicts['fix']} and dropped {verdicts['drop']} of {written} questions.",
["heldout"],
[
(
"Single / multi / date / unanswerable",
" / ".join(
str(categories[k]) for k in ("single", "multi", "date", "unanswerable")
),
)
],
example(
EXAMPLE, clip(next(q for q in heldout if q["id"] == EXAMPLE)["question"], 320)
),
files=["evals/heldout.jsonl", "evals/heldout_review/"],
),
step(
"grading",
"An AI grader marked every answer, blind to the system.",
"Claude Opus compared each answer with the reference answer. No human expert checked the grades: a stated limitation.",
["grading"],
[("Grader", ", ".join(evals["question_set"]["graders"]))],
tried=[
f"Hand grading {n(3 * len(heldout))} answers: no time; checking 30 against an expert is the next step"
],
files=["evals/llm_grading/README.md"],
),
step(
"stats",
"The systems are compared on the same questions.",
"Counting answers fixed and broken, question by question, is fairer than comparing averages. The main comparisons were declared in advance.",
["stats"],
[
(
"C vs B",
next(
f"{p['fixed']} fixed, {p['broken']} broken"
for p in evals["pairs"]
if p["new"] == "c" and p["base"] == "b"
),
)
],
files=["src/coveragecheck/evals/metrics.py"],
),
step(
"results",
f"C is right {accuracy['c']} of the time, B {accuracy['b']}, A {accuracy['a']}.",
f"C gains most on questions needing two or more documents. Its cost is time: about {seconds['c']} per answer against {seconds['b']} for B.",
["results"],
[
(f"System {s.upper()}", f"{accuracy[s]} correct, {seconds[s]} typical time")
for s in "abc"
],
files=["evals/report_heldout/report.md"],
),
],
}
return {
"example": EXAMPLE,
"overview": overview,
"chapters": [documents, prepare, evidence_ch, answer, measure],
}