File size: 33,438 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b323bf
 
23d418f
 
 
 
 
4b323bf
 
 
 
 
 
 
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
"""Step 4e: the eval report: markdown tables + SVG charts (light and dark).

    uv run python -m coveragecheck.evals.report [run.parquet ...] [--out DIR]

Default: the newest run of each system -> evals/report/ (committed; the README
embeds it). The dummy's report goes to a scratch folder, never evals/report/
(owner decision 4e: its raw-passage answers are never graded, so its numbers mean
nothing).

Owner decisions (4e): SVG charts (text in git, crisp in the README), made
byte-for-byte reproducible (fixed svg.hashsalt, no date), so an unchanged result
does not show up as a changed file; a light and a dark variant of every chart,
which the README picks with <picture> + prefers-color-scheme; every chart has a
table with the same numbers (no number lives only in a picture).

Chart design follows the dataviz method: categorical slots 1-3 of the validated
palette (validator run for both modes, all pairs: PASS; light aqua is below 3:1 on
the surface, so marks always carry direct labels and a table), color follows the
system (never its rank), dots + 95% interval lines instead of bars, 2px lines,
dots with a 2px surface ring, hairline recessive grid, text in text tokens only,
two panels instead of a second y-axis.
"""

import argparse
import io
import json
import math
from dataclasses import dataclass
from pathlib import Path

import pandas as pd

from coveragecheck import config
from coveragecheck.evals import metrics as m
from coveragecheck.evals.grade import latest_runs
from coveragecheck.index.store import load_table

# --- theme ---------------------------------------------------------------------------------

THEMES = {
    "light": {
        "surface": "#fcfcfb", "text": "#0b0b0b", "text2": "#52514e", "muted": "#898781",
        "grid": "#e1e0d9", "axis": "#c3c2b7",
        "series": ["#2a78d6", "#eb6834", "#1baf7a"],
    },
    "dark": {
        "surface": "#1a1a19", "text": "#f0efec", "text2": "#c3c2b7", "muted": "#898781",
        "grid": "#2c2c2a", "axis": "#383835",
        "series": ["#3987e5", "#d95926", "#199e70"],
    },
}  # fmt: skip
# Color follows the system, never its rank: A, B, C keep their slot in every chart.
# Other systems (the dummy, a renamed run) take a free slot (palette(): never C's).
SLOT = {"a": 0, "b": 1, "c": 2}
LABEL = {"a": "System A (naive RAG)", "b": "System B (hybrid RAG)", "c": "System C (agent)",
         "dummy": "Dummy (retrieval only)"}  # fmt: skip
FONT = ["Segoe UI", "Helvetica Neue", "Arial", "DejaVu Sans"]


def palette(systems: list[str], theme: dict) -> dict[str, str]:
    """system -> series color for one chart. A, B and C keep their own slot; any other
    system takes the first slot no system here uses (4e audit: they all fell back to
    C's color). More systems than validated slots raises: never two series one color."""
    free = [i for i in range(len(theme["series"])) if i not in {SLOT.get(s) for s in systems}]
    out = {}
    for system in systems:
        if system in SLOT:
            out[system] = theme["series"][SLOT[system]]
        elif free:
            out[system] = theme["series"][free.pop(0)]
        else:
            raise ValueError(f"more systems than the {len(theme['series'])} validated colors")
    return out


def label(system: str) -> str:
    return LABEL.get(system, system)


def rc(theme: dict) -> dict:
    """matplotlib settings for one theme: recessive hairline grid and axes, text
    tokens for all text, deterministic SVG (fixed hash salt; glyphs as paths so the
    chart looks the same on any machine)."""
    return {
        "font.family": "sans-serif",
        "font.sans-serif": FONT,
        "font.size": 9.5,
        "xtick.labelsize": 9,
        "ytick.labelsize": 9,
        "text.color": theme["text"],
        "axes.labelcolor": theme["text2"],
        "axes.edgecolor": theme["axis"],
        "axes.facecolor": theme["surface"],
        "axes.linewidth": 0.8,
        "axes.grid": True,
        "axes.axisbelow": True,
        "grid.color": theme["grid"],
        "grid.linewidth": 0.8,
        "grid.linestyle": "-",
        "xtick.color": theme["muted"],
        "ytick.color": theme["muted"],
        "xtick.labelcolor": theme["text2"],
        "ytick.labelcolor": theme["text2"],
        "figure.facecolor": theme["surface"],
        "savefig.facecolor": theme["surface"],
        "svg.hashsalt": "coveragecheck",
        "svg.fonttype": "path",
    }


def new_figure(width: float, height: float, theme: dict):
    """A figure (Figure, not pyplot: no global state). Call inside render(), which
    applies the theme while the figure is built AND saved (fonts are looked up at
    save time: a theme applied only at creation fell back to DejaVu Sans)."""
    from matplotlib.figure import Figure

    return Figure(figsize=(width, height), layout="constrained")


def style_axes(ax, theme: dict) -> None:
    """Only the baseline spine stays; ticks are short and muted."""
    for side in ("top", "right", "left"):
        ax.spines[side].set_visible(False)
    ax.spines["bottom"].set_color(theme["axis"])
    ax.tick_params(length=0, pad=6, labelcolor=theme["text2"])


def titles(fig, title: str, subtitle: str, theme: dict, legend_ax=None) -> None:
    """Left-aligned title, subtitle and (with 2+ series) a one-row legend, placed in
    INCHES from the top (fractions of the height crowded them on short figures); the
    plots are laid out below that block, so the legend never covers data (it did,
    inside the axes, in the 3-system preview)."""
    height = fig.get_figheight()
    top = lambda inches: 1 - inches / height  # noqa: E731
    fig.text(0.012, top(0.14), title, ha="left", va="top", fontsize=12.5,
             fontweight="semibold", color=theme["text"])  # fmt: skip
    fig.text(0.012, top(0.44), subtitle, ha="left", va="top", fontsize=9.5, color=theme["text2"])
    block = 0.78
    if legend_ax is not None:
        handles, names = legend_ax.get_legend_handles_labels()
        if len(handles) > 1:
            legend = fig.legend(handles, names, loc="upper left", ncol=len(handles),
                                bbox_to_anchor=(0.004, top(0.66)), frameon=False,
                                fontsize=9, handlelength=1.6, columnspacing=1.6)  # fmt: skip
            for text in legend.get_texts():
                text.set_color(theme["text2"])
            block = 1.0
    fig.get_layout_engine().set(rect=(0.01, 0, 0.98, top(block)), w_pad=0.12, wspace=0.06)


def dot(ax, x, y, fill: str, theme: dict, size: float = 64) -> None:
    """A >=8px dot with a 2px ring in the surface color (legible where it overlaps)."""
    ax.scatter([x], [y], s=size, color=fill, edgecolors=theme["surface"], linewidths=2,
               zorder=4, clip_on=False)  # fmt: skip


def render(chart, runs: list, theme: dict, fmt: str = "svg") -> bytes:
    """Build and save one chart with the theme applied throughout. SVG is
    reproducible: same data -> same bytes (no date metadata, fixed hash salt) on the
    same machine; glyphs are paths, so another machine's fonts change the bytes (build
    the committed report on one machine)."""
    import matplotlib as mpl

    buffer = io.BytesIO()
    with mpl.rc_context(rc(theme)):
        fig = chart(runs, theme)
        metadata = {"Date": None} if fmt == "svg" else None
        fig.savefig(buffer, format=fmt, metadata=metadata, dpi=150)
    return buffer.getvalue()


# --- the data the report shows --------------------------------------------------------------


@dataclass
class RunData:
    """Everything the report needs from one run, computed once."""

    info: dict  # describe(): run, system, commit, started_at, complete
    table: pd.DataFrame  # scored()
    summary: dict  # summary()

    @property
    def system(self) -> str:
        return self.info.get("system") or Path(self.info["run"]).stem


def group_intervals(table: pd.DataFrame, column: str) -> pd.DataFrame:
    """Per value of a column: n, accuracy (worst case) and its 95% CI (envelope of
    best and worst). The per-group n is small, so the interval matters."""
    rows = []
    for value, group in m.live(table).groupby(column, sort=True):
        best, worst = m.scores(group, "pass")[0], m.scores(group, "fail")[0]
        low, high = m.envelope(m.bootstrap_ci(best), m.bootstrap_ci(worst))
        rows.append(
            {
                column: value,
                "n": len(group),
                "accuracy_best": best.mean(),
                "accuracy_worst": worst.mean(),
                "ci_low": low,
                "ci_high": high,
            }
        )
    return pd.DataFrame(
        rows, columns=[column, "n", "accuracy_best", "accuracy_worst", "ci_low", "ci_high"]
    )


def comparisons(runs: list[RunData]) -> list[dict]:
    """Every pair of systems, the declared primary pairs first, each with the paired
    result on questions graded in both and its Holm-adjusted McNemar p (adjusted over
    all pairs that could be compared)."""
    by_system = {r.system: r for r in runs}
    pairs = [(n, b) for n, b in config.PRIMARY_COMPARISONS if n in by_system and b in by_system]
    names = [r.system for r in runs]
    for i, a in enumerate(names):
        for b in names[i + 1 :]:
            if (b, a) not in pairs and (a, b) not in pairs:
                pairs.append((b, a))
    out = []
    for new, base in pairs:
        ta, tb = m.align(by_system[base].table, by_system[new].table)
        row = {"new": new, "base": base, "primary": (new, base) in config.PRIMARY_COMPARISONS}
        if not ta.empty:
            row |= m.paired(m.scores(ta, "fail")[0], m.scores(tb, "fail")[0])
            row["cost_diff"], row["cost_ci"] = m.paired_diff_ci(
                m.scores(ta, "fail")[1], m.scores(tb, "fail")[1]
            )
        out.append(row)
    tested = [r for r in out if "mcnemar_p" in r]
    for r, p in zip(tested, m.holm([r["mcnemar_p"] for r in tested]), strict=True):
        r["holm_p"] = p
    return out


# --- charts ---------------------------------------------------------------------------------


def headline_chart(runs: list[RunData], theme: dict):
    """Accuracy and cost per system: a dot (worst case) and its 95% interval, in two
    panels (two measures -> two scales, never a second y-axis)."""
    fig = new_figure(8.2, 1.9 + 0.55 * len(runs), theme)
    colors = palette([r.system for r in runs], theme)
    axes = fig.subplots(1, 2, sharey=True)
    panels = [("accuracy", "Accuracy (strict)", 1.0), ("cost", "Cost per question", None)]
    ys = list(range(len(runs)))[::-1]
    for ax, (key, name, top) in zip(axes, panels, strict=True):
        style_axes(ax, theme)
        ax.grid(axis="y", visible=False)
        high = max(r.summary[f"{key}_ci_high"] for r in runs)
        limit = top or max(1.0, high * 1.25)
        for run, y in zip(runs, ys, strict=True):
            s, c = run.summary, colors[run.system]
            low, up = s[f"{key}_ci_low"], s[f"{key}_ci_high"]
            ax.plot([low, up], [y, y], color=c, linewidth=2, solid_capstyle="round", zorder=3)
            dot(ax, s[f"{key}_worst"], y, c, theme)
            partial = "" if s["complete"] else "  PARTIAL"
            text = f"{s[f'{key}_worst']:.2f}  [{low:.2f}-{up:.2f}]{partial}"
            # one anchor for every row (4e audit: labels floated and flipped sides)
            ax.text(0, y + 0.3, text, transform=ax.get_yaxis_transform(), fontsize=8.5,
                    color=theme["text2"], ha="left", va="center")  # fmt: skip
        ax.set_xlim(-0.02 * limit, limit * 1.02)
        ax.set_ylim(-0.6, len(runs) - 0.4)
        ax.set_title(name, loc="left", fontsize=9.5, color=theme["text"], pad=8)
    axes[0].set_yticks(ys, [label(r.system) for r in runs])
    axes[1].set_xlabel("lower is better (E&O loss proxy)", fontsize=8.5, color=theme["muted"])
    axes[0].set_xlabel("higher is better", fontsize=8.5, color=theme["muted"])
    titles(
        fig,
        "Accuracy and cost by system",
        "Dot: worst case (ungraded = fail). Line: 95% bootstrap interval.",
        theme,
    )
    return fig


def coverage_chart(runs: list[RunData], theme: dict):
    """Cost against coverage as the confidence threshold rises (one line per system).
    Coverage, not the threshold itself, on the x-axis: each system's confidence scale
    differs, coverage means the same for all."""
    fig = new_figure(6.4, 3.9, theme)
    ax = fig.subplots()
    style_axes(ax, theme)
    colors = palette([r.system for r in runs], theme)
    for run in runs:
        curve = m.threshold_curve(run.table)
        c = colors[run.system]
        ax.plot(
            curve.coverage,
            curve.cost,
            color=c,
            linewidth=1.75,
            solid_joinstyle="round",
            solid_capstyle="round",
            label=label(run.system),
            zorder=3,
        )
        full = curve.iloc[0]  # t = 0: the system as it ran
        dot(ax, full.coverage, full.cost, c, theme)
        if len(runs) == 1:  # several systems: end labels collide; the legend explains
            ax.annotate(
                f"as run: {full.cost:.2f}",
                (full.coverage, full.cost),
                xytext=(-8, 8),
                textcoords="offset points",
                ha="right",
                fontsize=8.5,
                color=theme["text2"],
            )
    if len(runs) > 1:
        ax.scatter([], [], s=64, color=theme["muted"], edgecolors=theme["surface"],
                   linewidths=2, label="as run")  # fmt: skip
    ax.set_xlim(-0.02, 1.04)
    ax.set_ylim(bottom=0)
    ax.set_xlabel("Coverage: share of questions answered (rises as the threshold falls)")
    ax.set_ylabel("Mean cost per question")
    ax.xaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
    titles(
        fig,
        "Cost if the system abstained below a confidence threshold",
        "Worst case (ungraded = fail). Point estimate on the eval questions, not a tuned "
        "threshold.",
        theme,
        legend_ax=ax,
    )
    return fig


def ndocs_chart(runs: list[RunData], theme: dict):
    """Accuracy by the number of documents the gold answer needs (0 = unanswerable):
    per system a dot (worst case) and its 95% interval, side by side per group."""
    fig = new_figure(6.4, 3.9, theme)
    ax = fig.subplots()
    style_axes(ax, theme)
    colors = palette([r.system for r in runs], theme)
    groups = {r.system: group_intervals(r.table, "n_docs").set_index("n_docs") for r in runs}
    values = sorted({v for g in groups.values() for v in g.index})
    width = 0.22
    for i, run in enumerate(runs):
        g, c = groups[run.system], colors[run.system]
        offset = (i - (len(runs) - 1) / 2) * width
        for x, value in enumerate(values):
            if value not in g.index:
                continue
            row = g.loc[value]
            ax.plot(
                [x + offset] * 2,
                [row.ci_low, row.ci_high],
                color=c,
                linewidth=2,
                solid_capstyle="round",
                zorder=3,
            )
            dot(ax, x + offset, row.accuracy_worst, c, theme)
        ax.plot([], [], color=c, linewidth=2, marker="o", markersize=6, label=label(run.system))
    ax.set_xticks(range(len(values)), [group_name(v, groups) for v in values])
    ax.set_ylim(-0.05, 1.05)
    ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])  # no phantom 1.2 tick above the range
    ax.set_xlim(-0.6, len(values) - 0.4)
    ax.grid(axis="x", visible=False)
    ax.set_ylabel("Accuracy (strict)")
    titles(
        fig,
        "Accuracy by documents needed",
        "Dot: worst case (ungraded = fail). Line: 95% bootstrap interval; groups are small.",
        theme,
        legend_ax=ax,
    )
    return fig


def group_name(value: int, groups: dict[str, pd.DataFrame]) -> str:
    """Tick label for an n_docs group: its name and its n. Each system's n is shown
    when they differ (stale rows), else one n (4e audit: it showed the first's)."""
    name = "unanswerable" if value == 0 else f"{value} doc" + ("s" if value > 1 else "")
    counts = [int(g.loc[value].n) if value in g.index else 0 for g in groups.values()]
    n = str(counts[0]) if len(set(counts)) == 1 else "/".join(map(str, counts))
    return f"{name}\nn = {n}"


CHARTS = {"headline": headline_chart, "coverage": coverage_chart, "ndocs": ndocs_chart}


# --- markdown -------------------------------------------------------------------------------


def pct(value: float) -> str:
    return "n/a" if value is None or math.isnan(value) else f"{value:.2f}"


def ci(low: float, high: float, signed: bool = False) -> str:
    form = "{:+.2f}" if signed else "{:.2f}"
    return "n/a" if math.isnan(low) else f"{form.format(low)} to {form.format(high)}"


def table(header: list[str], rows: list[list[str]]) -> list[str]:
    """A GitHub markdown table."""
    lines = ["| " + " | ".join(header) + " |", "|" + "|".join("---" for _ in header) + "|"]
    return lines + ["| " + " | ".join(r) + " |" for r in rows]


def headline_alt(runs: list[RunData]) -> str:
    """Alt text with the numbers the chart shows (screen readers get the data, not
    just the chart's name)."""
    parts = [
        f"{label(r.system)}: accuracy {r.summary['accuracy_worst']:.2f}, cost per question "
        f"{r.summary['cost_worst']:.2f}"
        for r in runs
    ]
    return "Accuracy and cost by system (worst case). " + "; ".join(parts)


def picture(name: str, alt: str) -> str:
    """The README/GitHub way to show the light or the dark variant."""
    return (
        f'<picture><source media="(prefers-color-scheme: dark)" srcset="{name}-dark.svg">'
        f'<img alt="{alt}" src="{name}-light.svg"></picture>'
    )


def grader_banner(runs: list[RunData]) -> list[str]:
    """A warning when any judged answer was graded by an LLM instead of the owner (5c:
    owner's decision, for time). Those grades are not validated against hand labels,
    so accuracy and cost rest on the LLM's judgement: the reader must know. Empty when
    every grade is a hand grade (or nothing is graded)."""
    graders = [
        g for r in runs if "grader" in r.table for g in r.table["grader"] if isinstance(g, str)
    ]
    llm = [g for g in graders if g.startswith("llm:")]
    if not llm:
        return []
    names = ", ".join(sorted(set(llm)))
    return [
        f"> **Graded by an LLM:** {len(llm)} of {len(graders)} judged answers were graded "
        f"by {names} in the owner's place, not validated against hand grades. Accuracy "
        "and cost below rest on that judgement.",
        "",
    ]


def citation_markdown(runs: list[RunData]) -> list[str]:
    """The Step 8 citation check: one row per run, rates per citation."""
    rows = [
        [
            label(r.system),
            str(r.summary["citations"]),
            f"{r.summary['hallucinated_citation_rate']:.1%}",
            f"{r.summary['hallucinated_citation_rate_fuzzy']:.1%}",
            f"{r.summary['citation_not_shown_rate']:.1%}",
            f"{r.summary['answers_with_bad_citation']:.1%}",
        ]
        for r in runs
        if not math.isnan(r.summary["hallucinated_citation_rate"])
    ]
    if not rows:
        return ["Hallucinated citation rate: not checked (no citations, or no corpus).", ""]
    return [
        "## Citations",
        "",
        "Every quote checked against the section it cites (verify/citations.py). *Not "
        "exact* (the hallucinated citation rate): not found word for word after normalizing "
        "case, spaces, quotes and dashes, or a number missing. *Not even approximate*: also "
        "fails the fuzzy fallback (each fragment >= 90 partial ratio, its numbers and "
        "negation words in the matching text); the fallback accepts a changed word, so it "
        "is the lenient bound. *Not in shown passages*: the quote matches neither tier in "
        "what the system showed the model (e.g. recalled wording). Rates are per citation, "
        "abstentions' citations included; the last column counts answers with at least "
        "one citation.",
        "",
        *table(
            [
                "System",
                "Citations",
                "Not exact",
                "Not even approximate",
                "Not in shown passages",
                "Answers with a non-exact citation",
            ],
            rows,
        ),
        "",
    ]


def markdown(runs: list[RunData], pairs: list[dict]) -> str:
    """The whole report.md."""
    out = ["# CoverageCheck eval report", ""]
    partial = [r.system for r in runs if not r.summary["complete"]]
    if partial:
        out += [
            f"> **PARTIAL:** ungraded answers in {', '.join(partial)}. Ranges show best "
            "(ungraded = pass) to worst (ungraded = fail); intervals cover both.",
            "",
        ]
    out += set_banner(runs)
    out += grader_banner(runs)
    out += ["## Runs", ""] + table(
        ["System", "Run file", "Commit", "Started", "Run complete", "Graded", "Model", "Prompt"],
        [
            [
                label(r.system),
                f"`{r.info['run']}`",
                f"`{(r.info.get('git_commit') or '?')[:12]}`",
                str(r.info.get("started_at")),
                str(r.info.get("complete")),
                f"{r.summary['n'] - r.summary['pending']}/{r.summary['n']}",
                r.info.get("llm_model") or "none",
                f"`{r.info['prompt_hash']}`" if r.info.get("prompt_hash") else "none",
            ]
            for r in runs
        ],
    )
    prompts = {r.info.get("prompt_hash") for r in runs if r.info.get("prompt_hash")}
    if len(prompts) > 1:  # 5b audit: B and C claim "the same answer prompt as A"
        out += ["", "> **Note:** these runs used different answer prompts (see Prompt)."]
    out += ["", "## Headline", "", picture("headline", headline_alt(runs)), ""]
    rows = []
    for r in runs:
        s = r.summary
        rows.append(
            [
                label(r.system),
                m.fmt_range(s["accuracy_best"], s["accuracy_worst"]),
                ci(s["accuracy_ci_low"], s["accuracy_ci_high"]),
                m.fmt_range(s["cost_best"], s["cost_worst"]),
                ci(s["cost_ci_low"], s["cost_ci_high"]),
                m.fmt_range(s["abstention_best"], s["abstention_worst"]),
                " / ".join(pct(s[k]) for k in ("hit@1", "hit@5", "hit@10")),
                f"{s['latency_p50_ms']:.0f} / {s['latency_p95_ms']:.0f}",
                f"{s['tokens_mean']:.0f}",
                f"{s['reasks_mean']:.2f}",
                pct(s["cached_share"]),
                str(s["errors"]),
            ]
        )
    out += table(
        [
            "System",
            "Accuracy",
            "95% CI",
            "Cost / question",
            "95% CI",
            "Correct abstention",
            "Recall @1 / @5 / @10",
            "Latency ms p50 / p95",
            "Tokens",
            "Reasks / q",
            "Cached",
            "Errors",
        ],
        rows,
    )
    out += [
        "",
        "Latency includes the original model time of answers replayed from the LLM cache "
        "(*Cached* = share of questions served from it), so a rerun reports the first run's "
        "latency. A reask re-sends the prompt (about twice the input tokens).",
        "",
    ]
    out += citation_markdown(runs)
    if pairs:
        out += [
            "## Paired comparisons",
            "",
            "Same questions, graded in both systems. *Fixed* = the baseline fails and the new "
            "system passes; *broken* = the reverse. Primary comparisons were declared before "
            "any result; McNemar p is shown raw and Holm-adjusted over all testable pairs "
            "(pairs with a question graded in both).",
            "",
        ]
        prow = []
        for p in pairs:
            name = f"{label(p['new'])} vs {label(p['base'])}" + (
                " (primary)" if p["primary"] else ""
            )
            if "n" not in p:
                prow.append([name, "0", "", "", "", "", "", "", "no question graded in both"])
                continue
            prow.append(
                [
                    name,
                    str(p["n"]),
                    str(p["fixed"]),
                    str(p["broken"]),
                    f"{p['diff']:+.2f} ({ci(*p['ci'], signed=True)})",
                    f"{p['cost_diff']:+.2f} ({ci(*p['cost_ci'], signed=True)})",
                    f"{p['mcnemar_p']:.3f}",
                    f"{p['holm_p']:.3f}",
                    "",
                ]
            )
        out += table(
            [
                "Comparison",
                "n",
                "Fixed",
                "Broken",
                "Accuracy diff (95% CI)",
                "Cost diff (95% CI)",
                "McNemar p",
                "Holm p",
                "Note",
            ],
            prow,
        ) + [""]
    out += [
        "## Accuracy by documents needed",
        "",
        picture("ndocs", "Accuracy by documents needed per system; values in the table below"),
        "",
    ]
    out += group_markdown(runs, "n_docs") + ["", "## Accuracy by category", ""]
    out += group_markdown(runs, "category")
    out += [
        "",
        "## Confidence threshold",
        "",
        picture(
            "coverage",
            "Mean cost against coverage as the confidence threshold rises; "
            "values in the table below",
        ),
        "",
        "If a system abstained on every answer below confidence t (worst case, ungraded = fail). "
        "The lowest-cost t here is picked on the same questions it is measured on, so it is "
        "optimistic: not a recommended setting.",
        "",
    ]
    out += threshold_markdown(runs)
    out += [""] + evidence_markdown(runs)
    out += [
        "",
        "## How to read the cost",
        "",
        "Per question: correct = 0; abstaining on an answerable question = 1; a wrong answer = 5 "
        "(low stakes) or 20 (could leave a client uncovered); answering an unanswerable question "
        "= 20; an error counts as a wrong answer. Weights live in `config.COST_WEIGHTS`. A few "
        f"20-point questions dominate the mean, and {unanswerable_share(runs)} questions are "
        "unanswerable by design.",
        "",
    ]
    return "\n".join(out)


def unanswerable_share(runs: list[RunData]) -> str:
    """ "<k> of the <n>": counted from the run's own question set (the text once said
    "10 of the 63", the draft set's numbers, also under the held-out report: Step 10d)."""
    answerable = runs[0].table["answerable"].astype(bool)
    return f"{int((~answerable).sum())} of the {len(answerable)}"


def group_markdown(runs: list[RunData], column: str) -> list[str]:
    """One row per group value, one accuracy column per system (with its CI)."""
    tables = {r.system: group_intervals(r.table, column).set_index(column) for r in runs}
    values = sorted({v for t in tables.values() for v in t.index}, key=str)
    rows = []
    for v in values:
        row = [str(v)]
        for r in runs:
            t = tables[r.system]
            if v in t.index:
                g = t.loc[v]
                value = m.fmt_range(g.accuracy_best, g.accuracy_worst)
                row.append(f"{value} ({ci(g.ci_low, g.ci_high)}), n={int(g.n)}")
            else:
                row.append("")
        rows.append(row)
    return table([column] + [label(r.system) for r in runs], rows)


def threshold_markdown(runs: list[RunData]) -> list[str]:
    """Every 0.1 of the threshold curve: coverage and cost per system."""
    curves = {r.system: m.threshold_curve(r.table).set_index("t") for r in runs}
    rows = []
    for t in [round(0.1 * i, 1) for i in range(11)]:
        row = [f"{t:.1f}"]
        for r in runs:
            c = curves[r.system].loc[t]
            row.append(f"{c.coverage:.0%} answered, cost {c.cost:.2f}")
        rows.append(row)
    return table(["t"] + [label(r.system) for r in runs], rows)


# --- build ---------------------------------------------------------------------------------


def collect(paths: list[Path], inputs) -> list[RunData]:
    """Score each run once (in the order given). Two runs of one system are refused:
    the report keys everything by system (4e audit: it compared a run with itself)."""
    out = []
    for path in paths:
        table_ = m.scored(load_table(path), *inputs)
        out.append(RunData(m.describe(path), table_, m.summary(table_)))
    systems = [r.system for r in out]
    if len(set(systems)) != len(systems):
        raise ValueError(f"one run per system, got {systems}: pass the run files to compare")
    hashes = {r.info.get("questions_sha256") for r in out} - {None}
    if len(hashes) > 1:
        raise ValueError(
            "the runs used different question files: compare runs of one question set "
            f"({sorted(str(r.info.get('questions_file')) for r in out)})"
        )
    return out


def set_banner(runs: list[RunData]) -> list[str]:
    """What the question set IS (config.QUESTION_SETS, by the runs' question file):
    the draft gold is a development set that shaped System C, the held-out set is the
    final test (owner, 7d). An unknown or unrecorded file gets a neutral line."""
    files = {r.info.get("questions_file") for r in runs} - {None}
    if len(files) == 1 and (known := config.QUESTION_SETS.get(next(iter(files)))):
        text = known[1]
    else:
        text = "The question set is not a registered one (config.QUESTION_SETS)."
    return [
        f"> {text} These are measurements of retrieval and answering on public "
        "FSRA/e-Laws documents, not coverage advice.",
        "",
    ]


def evidence_label(trace_json: str | None) -> str | None:
    """System C's own evidence check for one question, from its trace: the judge
    found every requirement stated ("sufficient"), or a second search ran ("second
    search"), or it did not ("insufficient, no new candidates"). None for a run
    without a judge (A, B) or an unreadable trace."""
    try:
        trace = json.loads(trace_json) if isinstance(trace_json, str) else None
    except ValueError:
        return None
    if not trace or "judge" not in trace:
        return None
    if trace["judge"].get("sufficient"):
        return "sufficient"
    return "second search" if "judge_new" in trace else "insufficient, no new candidates"


def evidence_markdown(runs: list[RunData]) -> list[str]:
    """Accuracy by System C's evidence check ("Sufficient Context", ICLR 2025: a
    sufficiency signal says when an answer is likely wrong). Measured, not tuned: the
    check's verdict is not used to abstain. Empty when no run has a judge trace."""
    out = []
    for r in runs:
        if "trace_json" not in r.table:
            continue
        table_ = r.table.assign(evidence=r.table["trace_json"].map(evidence_label))
        if table_["evidence"].isna().all():
            continue
        rows = group_intervals(table_.dropna(subset=["evidence"]), "evidence")
        out += (
            [f"**{label(r.system)}**", ""]
            + table(
                ["Evidence check", "n", "Accuracy", "95% CI"],
                [
                    [
                        str(x["evidence"]),
                        str(x["n"]),
                        f"{x['accuracy_worst']:.2f}",
                        ci(x["ci_low"], x["ci_high"]),
                    ]
                    for x in rows.to_dict("records")
                ],
            )
            + [""]
        )
    if not out:
        return []
    return [
        "## Evidence check (System C)",
        "",
        "Accuracy grouped by C's own verdict on its evidence before answering: every "
        "requirement stated by a passage (sufficient), or a second search ran. Measured, "
        "not used to abstain.",
        "",
    ] + out


def build(paths: list[Path], out_dir: Path, inputs) -> list[Path]:
    """Write report.md and every chart in both themes; returns the files written.
    Files are only rewritten when their bytes change, so an unchanged report leaves
    git clean."""
    runs = collect(paths, inputs)
    files = {"report.md": markdown(runs, comparisons(runs)).encode("utf-8")}
    for name, chart in CHARTS.items():
        for theme_name, theme in THEMES.items():
            files[f"{name}-{theme_name}.svg"] = render(chart, runs, theme)
    out_dir.mkdir(parents=True, exist_ok=True)
    written = []
    for name, data in files.items():
        path = out_dir / name
        if not path.exists() or path.read_bytes() != data:
            path.write_bytes(data)
        written.append(path)
    return written


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("runs", nargs="*", type=Path, help="run files (default: newest per system)")
    parser.add_argument("--out", type=Path, default=config.REPORT_DIR)
    args = parser.parse_args()
    paths = args.runs or latest_runs(config.RUNS_DIR)
    if not paths:
        raise SystemExit(f"no runs in {config.RUNS_DIR}")
    written = build(paths, args.out, m.load_inputs(m.shared_questions_path(paths)))
    print(f"wrote {len(written)} files to {args.out}")


if __name__ == "__main__":
    main()