File size: 16,315 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""Step 9b: write the JSON the web app shows without asking a model (committed under
web/public/data/, so the deployed app needs no eval runs, grades or LLM cache).

    uv run python -m coveragecheck.web.export      # local only: needs evals/runs + .cache

- systems.json: each system's held-out headline (accuracy + CI, latency, tokens), for
  the system picker. Numbers come from evals.metrics, never typed into the frontend.
- examples/index.json + examples/<id>.json: recorded held-out questions. Each system's
  answer is REPLAYED through the app's own Engine.events from the evals' disk cache (a
  client that refuses every call: a cache miss fails loudly, it never spends credit),
  checked equal to the run's recorded answer, then given the run's recorded timings
  (`at_ms` = when each event happened in the real run), so the app replays the real
  pace. Each carries the grade (LLM grader) and the reference answer.

Examples are chosen by a fixed rule (pick), not by hand: the first question id in each
group (owner, 9b): all three right / only C right (single, two multi, date) / all
three correctly decline / C wrong (multi, date). C's wrong answers are shown on purpose.
"""

import json
from datetime import date
from pathlib import Path

import pandas as pd

from coveragecheck import config
from coveragecheck.web.engine import timings

SYSTEMS = {
    "a": "Naive RAG",
    "b": "Structure-aware hybrid RAG",
    "c": "Agent (LangGraph)",
}
# (label, category, the systems that must be right (True) or wrong (False), how many)
GROUPS = [
    ("All three right", "single", {"a": True, "b": True, "c": True}, 1),
    ("Only C right", "single", {"a": False, "b": False, "c": True}, 1),
    ("Only C right", "multi", {"a": False, "b": False, "c": True}, 2),
    ("Only C right", "date", {"a": False, "b": False, "c": True}, 1),
    ("All three decline", "unanswerable", {"a": True, "b": True, "c": True}, 1),
    ("C wrong", "multi", {"c": False}, 1),
    ("C wrong", "date", {"c": False}, 1),
]


class NoCalls:
    """An Anthropic client stand-in that refuses every call: the export only replays
    the evals' disk cache, so a miss (a changed prompt, another date) fails loudly
    instead of spending API credit."""

    def __init__(self):
        self.messages = self

    def create(self, **params):
        raise RuntimeError("cache miss: the examples export never calls the API")


def replay_llm():
    """The evals' LLM settings and disk cache, with NoCalls as its client."""
    from coveragecheck.llm import LLM, DiskCache

    return LLM(
        NoCalls(),
        config.llm_model(),
        DiskCache(config.LLM_CACHE_DIR),
        effort=config.LLM_EFFORT,
        max_tokens=config.LLM_MAX_TOKENS,
        max_reasks=config.LLM_MAX_REASKS,
        api_retries=0,
        retry_base_s=config.LLM_RETRY_BASE_S,
        retry_max_s=config.LLM_RETRY_MAX_S,
    )


def pick(rows: list[dict], groups=GROUPS) -> list[tuple[str, str]]:
    """(question id, group label) per group: the first ids (in id order) whose category
    matches and whose systems are right/wrong as the group says. rows: {"id",
    "category", "correct": {system: bool}}. A question is used once."""
    chosen, used = [], set()
    for label, category, wanted, count in groups:
        found = [
            r["id"]
            for r in sorted(rows, key=lambda r: r["id"])
            if r["category"] == category
            and r["id"] not in used
            and all(r["correct"][s] == right for s, right in wanted.items())
        ][:count]
        chosen += [(i, label) for i in found]
        used.update(found)
    return chosen


def step_times(node_ms: dict, latency: float) -> dict:
    """C's recorded time per step. The run's trace has no verify entry, so verify gets
    the rest of the run's latency (latency minus the recorded nodes, never below 0):
    a time the run really spent (verify + graph overhead, 5-34 ms on the examples), the
    same on every export (the replay's own verify time changed each run: Step 10a)."""
    rest = max(0.0, latency - sum(node_ms.values()))
    return {**node_ms, "verify": node_ms.get("verify", round(rest, 1))}


def recorded(events: list[dict], row: dict, name: str) -> list[dict]:
    """A replayed event stream given the real run's pace: each C step its recorded
    time (step_times), the answer the run's latency (incl. the original time of calls
    the run itself replayed from the cache) and timings, usage as the run paid it (not
    cached). at_ms: when each event came in the real run (C: steps one after another;
    A/B: evidence and answer at the end). Nothing re-measured: the export is the same
    every time."""
    trace = json.loads(row.get("trace_json") or "{}")
    latency = float(row["latency_ms"]) + float(row.get("replayed_ms") or 0.0)
    node_ms = step_times(trace.get("node_ms", {}), latency)
    out, at = [], 0.0
    for event in events:
        event = dict(event)
        if event["type"] == "step":
            event["ms"] = node_ms.get(event["name"], event["ms"])
            at += event["ms"] or 0.0
        elif event["type"] == "evidence" and name != "c":
            at = latency
        elif event["type"] == "answer":
            event["latency_ms"] = round(latency)
            event["timings"] = timings(name, trace)
            event["usage"] = event["usage"] | {"cached": False, "cache_hits": 0}
            at = max(at, latency)
        out.append(event | {"at_ms": round(at)})
    return out


def outcomes(runs: dict[str, Path]) -> dict[str, pd.DataFrame]:
    """Each run scored against its own question file (metrics.scored: outcome + grade
    note per question), by question id."""
    from coveragecheck.evals import metrics as m

    questions_path = m.shared_questions_path(list(runs.values()))
    inputs = m.load_inputs(questions_path)
    return {
        s: m.scored(pd.read_parquet(p), *inputs[:4]).set_index("question_id")
        for s, p in runs.items()
    }


def system_numbers(tables: dict[str, pd.DataFrame]) -> dict:
    """The picker's headline per system, from metrics.summary."""
    from coveragecheck.evals import metrics as m

    out = {}
    for s, table in tables.items():
        x = m.summary(table.reset_index())
        out[s] = {
            "name": SYSTEMS[s],
            "accuracy": round(x["accuracy_best"], 3),
            "accuracy_ci": [round(x["accuracy_ci_low"], 3), round(x["accuracy_ci_high"], 3)],
            "latency_p50_ms": round(x["latency_p50_ms"]),
            "latency_p95_ms": round(x["latency_p95_ms"]),
            "tokens_mean": round(x["tokens_mean"]),
            "n": x["n"],
        }
    return out


def export(out_dir: Path, runs: dict[str, Path]) -> list[str]:
    """Write systems.json and the examples; returns the example ids."""
    from coveragecheck.evals import metrics as m
    from coveragecheck.evals.questions import load_questions
    from coveragecheck.web.engine import Engine

    tables = outcomes(runs)
    questions = {q.id: q for q in load_questions(m.shared_questions_path(list(runs.values())))}
    rows = [
        {
            "id": i,
            "category": tables["c"].category[i],
            "correct": {
                s: m.is_correct(t.outcome[i], bool(t.answerable[i])) for s, t in tables.items()
            },
        }
        for i in tables["c"].index
    ]
    chosen = pick(rows)
    runs_raw = {s: pd.read_parquet(p).set_index("question_id") for s, p in runs.items()}
    engine = Engine.load(replay_llm())
    (out_dir / "examples").mkdir(parents=True, exist_ok=True)
    index = []
    for qid, label in chosen:
        q = questions[qid]
        entry = {
            "id": qid,
            "label": label,
            "question": q.question,
            "category": q.category,
            "n_docs": q.n_docs,
            "outcomes": {s: t.outcome[qid] for s, t in tables.items()},
            # the question's own date (None: the run used its own day; the app says so)
            "policy_date": q.policy_effective_date.isoformat() if q.policy_effective_date else None,
        }
        detail = entry | {
            "reference": {"answer": q.gold_answer, "sources": list(q.gold_sources)},
            "runs": {},
        }
        for s, raw in runs_raw.items():
            row = raw.loc[qid].to_dict()
            day = date.fromisoformat(str(row["day"]))
            events = list(engine.events(s, q.question, day))
            final = events[-1]
            if final["type"] != "answer" or final["answer"] != row["answer"]:
                raise RuntimeError(f"{qid} {s}: the replay differs from the recorded run")
            detail["runs"][s] = {
                "run": runs[s].name,
                "outcome": tables[s].outcome[qid],
                "note": tables[s].note[qid],
                "events": recorded(events, row, s),
            }
        entry["day"] = str(runs_raw["c"].loc[qid, "day"])
        detail["day"] = entry["day"]
        write(out_dir / "examples" / f"{qid}.json", detail)
        index.append(entry)
    write(out_dir / "examples" / "index.json", index)
    write(
        out_dir / "systems.json",
        {
            "question_set": "held-out (249 questions, LLM-written and LLM-graded)",
            "runs": {s: p.name for s, p in runs.items()},
            "systems": system_numbers(tables),
        },
    )
    from coveragecheck.evals.report import collect

    questions_path = m.shared_questions_path(list(runs.values()))
    scored_runs = collect(list(runs.values()), m.load_inputs(questions_path))
    write(out_dir / "evals.json", evals_data(scored_runs))
    write(out_dir / "corpus.json", corpus_data())
    from coveragecheck.web import architecture

    evals = json.loads((out_dir / "evals.json").read_text(encoding="utf-8"))
    write(out_dir / "architecture.json", architecture.build(runs, evals))
    return [i for i, _ in chosen]


# --- the Evals and About pages (9c) ------------------------------------------------------------


def rounded(x, digits: int = 3):
    """A float for the page (NaN -> None: JSON has no NaN)."""
    return None if x is None or x != x else round(float(x), digits)


def group_rows(runs: list, column: str, order: list) -> list[dict]:
    """Accuracy (worst case) + its 95% CI per group value, one row per group with every
    system: report.group_intervals, the same numbers as the report's tables."""
    from coveragecheck.evals.report import group_intervals

    by_system = {
        r.system: {g[column]: g for g in group_intervals(r.table, column).to_dict("records")}
        for r in runs
    }
    rows = []
    for value in order:
        row = {"group": str(value)}
        for system, groups in by_system.items():
            g = groups.get(value)
            if g is not None:
                row["n"] = int(g["n"])
                row[system] = {
                    "accuracy": rounded(g["accuracy_worst"]),
                    "ci": [rounded(g["ci_low"]), rounded(g["ci_high"])],
                }
        rows.append(row)
    return rows


def docs_group(n_docs: int) -> str:
    """Documents an answerable question needs, with the 3s and the single 4 together
    (n=24 + 1: one 4-document question is no group of its own)."""
    return "3+" if n_docs >= 3 else str(n_docs)


def evals_data(runs: list) -> dict:
    """Everything the Evals page shows, from the report's own functions (so the page and
    evals/report_heldout/report.md cannot disagree)."""
    from coveragecheck.evals import metrics as m
    from coveragecheck.evals.report import comparisons, evidence_label

    systems = {}
    for r in runs:
        s = r.summary
        systems[r.system] = {
            "name": SYSTEMS[r.system],
            "accuracy": rounded(s["accuracy_worst"]),
            "accuracy_ci": [rounded(s["accuracy_ci_low"]), rounded(s["accuracy_ci_high"])],
            "cost": rounded(s["cost_worst"], 2),
            "cost_ci": [rounded(s["cost_ci_low"], 2), rounded(s["cost_ci_high"], 2)],
            "abstention": rounded(s["abstention_worst"]),
            "recall": {k: rounded(s[k]) for k in ("hit@1", "hit@5", "hit@10", "mrr")},
            "latency_p50_ms": round(s["latency_p50_ms"]),
            "latency_p95_ms": round(s["latency_p95_ms"]),
            "tokens_mean": round(s["tokens_mean"]),
            "citations": {
                "count": int(s["citations"]),
                "not_exact": rounded(s["hallucinated_citation_rate"], 4),
                "not_approximate": rounded(s["hallucinated_citation_rate_fuzzy"], 4),
                "not_shown": rounded(s["citation_not_shown_rate"], 4),
                "answers_with_bad": rounded(s["answers_with_bad_citation"], 4),
            },
            "n": int(s["n"]),
        }
    pairs = [
        {
            "new": p["new"],
            "base": p["base"],
            "primary": p["primary"],
            "n": p["n"],
            "fixed": p["fixed"],
            "broken": p["broken"],
            "diff": rounded(p["diff"]),
            "ci": [rounded(p["ci"][0]), rounded(p["ci"][1])],
            "p": p["mcnemar_p"],
            "holm_p": p["holm_p"],
        }
        for p in comparisons(runs)
    ]
    # unanswerable questions need 0 documents: group "0" is simply not charted (the
    # by-category view shows them)
    with_docs = [
        type(r)(r.info, r.table.assign(docs=r.table.n_docs.map(docs_group)), r.summary)
        for r in runs
    ]
    threshold = {}
    for r in runs:
        for x in m.threshold_curve(r.table).to_dict("records"):
            point = threshold.setdefault(round(x["t"], 2), {"t": round(x["t"], 2)})
            point[r.system] = {"answered": rounded(x["coverage"]), "cost": rounded(x["cost"], 2)}
    c = next(r for r in runs if r.system == "c")
    with_evidence = c.table.assign(evidence=c.table["trace_json"].map(evidence_label))
    evidence = [
        {"label": g["group"], "n": g["n"], "accuracy": g["c"]["accuracy"], "ci": g["c"]["ci"]}
        for g in group_rows(
            [type(c)(c.info, with_evidence.dropna(subset=["evidence"]), c.summary)],
            "evidence",
            ["sufficient", "second search"],
        )
        if "c" in g
    ]
    graders = sorted({g for r in runs for g in r.table.grader.dropna()})
    return {
        "question_set": {
            "name": "held-out",
            "n": systems["c"]["n"],
            "about": config.QUESTION_SETS["heldout.jsonl"][1],
            "graders": graders,
        },
        "systems": systems,
        "pairs": pairs,
        "by_docs": group_rows(with_docs, "docs", ["1", "2", "3+"]),
        "by_category": group_rows(runs, "category", ["single", "multi", "date", "unanswerable"]),
        "threshold": list(threshold.values()),
        "evidence": evidence,
        "cost_weights": [
            {"answerable": a, "outcome": o, "cost": w} for (a, o), w in config.COST_WEIGHTS.items()
        ],
    }


def corpus_data() -> list[dict]:
    """The About page's corpus table: data/manifest.csv (what each document is, its
    version and dates, where it comes from) with its number of indexed sections."""
    from coveragecheck.index.store import load_table

    manifest = pd.read_csv(config.DATA_DIR / "manifest.csv", dtype=str).fillna("")
    sections = load_table(config.INDEX_DIR / "sections.parquet")
    counts = sections.groupby("doc_id").size().to_dict()
    keep = [
        "doc_id",
        "title",
        "form_id",
        "version",
        "effective_from",
        "effective_to",
        "scope",
        "url",
    ]
    rows = []
    for row in manifest[keep].to_dict("records"):
        rows.append(
            {k: (v or None) for k, v in row.items()}
            | {"sections": int(counts.get(row["doc_id"], 0))}
        )
    return rows


def write(path: Path, data) -> None:
    """JSON as the app reads it (UTF-8, stable key order, a trailing newline)."""
    text = json.dumps(data, ensure_ascii=False, indent=1, default=str)
    path.write_text(text + "\n", encoding="utf-8", newline="\n")


def main() -> None:
    runs = {s: config.RUNS_DIR / name for s, name in config.WEB_HELDOUT_RUNS.items()}
    ids = export(config.WEB_DATA_DIR, runs)
    print(f"wrote systems.json and {len(ids)} examples: {', '.join(ids)}")


if __name__ == "__main__":
    main()