File size: 4,343 Bytes
4b323bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Step 10d: the README's results block, generated from web/public/data/evals.json (the
numbers the Evals page shows, themselves computed from the held-out runs), so the README,
the app and evals/report_heldout cannot disagree and no number is typed by hand.

    uv run python -m coveragecheck.deploy.readme          # rewrite the block in README.md
    uv run python -m coveragecheck.deploy.readme --check  # exit 1 if the block is stale

Only the text between the START and END markers is generated; the rest of the README is
written by hand.
"""

import json
import sys

from coveragecheck import config

START = "<!-- results:start (generated by coveragecheck.deploy.readme; do not edit) -->"
END = "<!-- results:end -->"
NAMES = {"a": "A: naive RAG", "b": "B: hybrid RAG", "c": "C: agent (LangGraph)"}


def pct(x: float) -> str:
    return f"{round(100 * x)}%"


def results_block(evals: dict) -> str:
    """The results table (one row per system), accuracy by documents needed, and the
    paired comparisons in words. Accuracy is the worst case (ungraded = wrong)."""
    systems, docs = evals["systems"], {g["group"]: g for g in evals["by_docs"]}
    groups = [g for g in ("1", "2", "3+") if g in docs]
    head = ["System", "Accuracy (95% CI)", "Cost / question", "Median time", "Not-exact quotes"]
    head += [f"{g} doc{'s' if g != '1' else ''} (n={docs[g]['n']})" for g in groups]
    lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
    for key, name in NAMES.items():
        s = systems[key]
        low, high = s["accuracy_ci"]
        row = [
            name,
            f"**{pct(s['accuracy'])}** ({pct(low)} to {pct(high)})",
            f"{s['cost']:.2f}",
            f"{s['latency_p50_ms'] / 1000:.1f} s",
            f"{100 * s['citations']['not_exact']:.1f}%",
        ]
        row += [pct(docs[g][key]["accuracy"]) for g in groups]
        lines.append("| " + " | ".join(row) + " |")
    n = evals["question_set"]["n"]
    lines += [
        "",
        f"{n} held-out questions, the same for every system. Cost per question: 0 when "
        'right, 1 for an unnecessary "I can\'t determine", 5 or 20 for a wrong answer '
        "(lower is better; see [the cost view](#the-cost-weighted-view)). Not-exact quotes: "
        "cited text not found word for word in the cited section.",
        "",
    ]
    for p in evals["pairs"]:
        if not p["primary"]:
            continue
        low, high = p["ci"]
        lines.append(
            f"- **{p['new'].upper()} vs {p['base'].upper()}** on the same {p['n']} questions: "
            # one decimal: the stored diffs have 3 (0.285), so whole points would round
            # half-even and disagree with the report's 2-decimal figure (+28 vs +0.29)
            f"{p['fixed']} fixed, {p['broken']} broken; accuracy {100 * p['diff']:+.1f} points "
            f"(95% CI {100 * low:+.1f} to {100 * high:+.1f}), McNemar p < 0.001."
            if p["holm_p"] < 0.001
            else f"- **{p['new'].upper()} vs {p['base'].upper()}**: {p['fixed']} fixed, "
            f"{p['broken']} broken; Holm p = {p['holm_p']:.3f}."
        )
    return "\n".join(lines)


def fill(readme: str, block: str) -> str:
    """The README with the text between the markers replaced by block (each marker must
    appear exactly once, START before END)."""
    if (
        readme.count(START) != 1
        or readme.count(END) != 1
        or readme.index(START) > readme.index(END)
    ):
        raise ValueError("README.md needs exactly one START marker followed by one END marker")
    before, rest = readme.split(START)
    _, after = rest.split(END)
    return f"{before}{START}\n{block}\n{END}{after}"


def main(argv: list[str] | None = None) -> None:
    argv = sys.argv[1:] if argv is None else argv
    evals = json.loads((config.WEB_DATA_DIR / "evals.json").read_text(encoding="utf-8"))
    path = config.ROOT / "README.md"
    readme = path.read_text(encoding="utf-8")
    fresh = fill(readme, results_block(evals))
    if "--check" in argv:
        sys.exit(
            0 if fresh == readme else "README results are stale: run coveragecheck.deploy.readme"
        )
    path.write_bytes(fresh.encode("utf-8"))
    print("README.md results block rewritten" if fresh != readme else "README.md already fresh")


if __name__ == "__main__":
    main()