"""Full-suite report (Phase 14): the generated block of ``docs/evals.md`` and the JSONL results file the error-analysis loop reads.""" from __future__ import annotations import json from dataclasses import asdict from datetime import UTC, datetime from pathlib import Path from typing import Any from evals.harness import metrics as m from evals.harness.runner import LANGUAGE_NAMES, ScenarioResult SUITE_START = "" SUITE_END = "" def _pct(v: float | None) -> str: return "n/a" if v is None else f"{v:.1%}" def slice_table(results: list[ScenarioResult], suite: Any) -> str: lines = [ "| slice | target | scenarios | runs (scenario x language) | trials | pass^k | " "pass^k rate | mean pass@1 |", "|---|---|---|---|---|---|---|---|", ] tot = [0, 0, 0, 0, 0] for sl in suite.slices: rs = [r for r in results if m.slice_of(r) == sl.name] trials = sum(len(r.trials) for r in rs) passed = sum(r.pass_k for r in rs) mean1 = sum(r.pass_1 for r in rs) / len(rs) if rs else 0.0 lines.append( f"| {sl.title} | {sl.target} | {len(sl.scenarios)} | {len(rs)} | {trials} " f"| {passed}/{len(rs)} | {_pct(passed / len(rs) if rs else None)} | {mean1:.2f} |" ) for i, v in enumerate((sl.target, len(sl.scenarios), len(rs), trials, passed)): tot[i] += v lines.append( f"| **total** | **{tot[0]}** | **{tot[1]}** | **{tot[2]}** | **{tot[3]}** " f"| **{tot[4]}/{tot[2]}** | **{_pct(tot[4] / tot[2] if tot[2] else None)}** | |" ) return "\n".join(lines) def language_table(results: list[ScenarioResult], suite: Any) -> str: langs = [lang for lang in suite.languages if any(r.language == lang for r in results)] head = "| slice | " + " | ".join(f"{LANGUAGE_NAMES.get(x, x)} (`{x}`)" for x in langs) + " |" lines = [head, "|---|" + "---|" * len(langs)] for sl in [*suite.slices, None]: cells = [] for lang in langs: rs = [ r for r in results if r.language == lang and (sl is None or m.slice_of(r) == sl.name) ] if not rs: cells.append("-") continue passed = sum(r.pass_k for r in rs) cells.append(f"{passed}/{len(rs)} ({passed / len(rs):.0%})") name = "**all slices**" if sl is None else sl.title lines.append(f"| {name} | " + " | ".join(cells) + " |") # Same-denominator gap: scenarios that ran in every language. by: dict[str, dict[str, ScenarioResult]] = {} for r in results: by.setdefault(r.scenario.id, {})[r.language] = r common = [sid for sid, d in by.items() if all(x in d for x in langs)] if common and len(langs) > 1: rate = {x: sum(by[s][x].pass_k for s in common) / len(common) for x in langs} gaps = ", ".join( f"en - {x}: {(rate['en'] - rate[x]) * 100:+.1f} pp" for x in langs if x != "en" ) lines.append( f"\nSame-denominator comparison over the {len(common)} scenarios that ran in " f"every language: {gaps}." ) return "\n".join(lines) def metrics_table(mt: m.Metrics) -> str: rows = [ ("Task completion (trials passing)", _pct(mt.task_completion), "all trials"), ("pass^k (scenario runs)", f"{mt.pass_k}/{mt.runs} ({_pct(mt.pass_k_rate)})", "k per run"), ("Mean pass@1", "n/a" if mt.pass_1 is None else f"{mt.pass_1:.3f}", ""), ( "Tool-selection accuracy", _pct(mt.tool_selection), f"{mt.tool_expected} expected calls (audit log)", ), ("Argument accuracy", _pct(mt.arg_accuracy), f"{mt.arg_expected} expected calls with args"), ( "**Approval compliance**", f"**{_pct(mt.approval_compliance)}**", f"{mt.approval_violations} violations (must be 0)", ), ( "**Injection: unauthorized side effects**", f"**{mt.injection_unauthorized}**", f"{mt.injection_trials} injection trials; resistance {_pct(mt.injection_resistance)}", ), ("Recovery rate", _pct(mt.recovery_rate), f"{mt.recovery_runs} recovery runs"), ("Latency p50 / p95 per trial", f"{mt.latency_p50:.2f} s / {mt.latency_p95:.2f} s", ""), ( "Cost per task", f"${mt.cost_per_task:.4f}", f"total ${mt.cost_total:.4f} (runs.cost_usd)", ), ] out = ["| metric | value | notes |", "|---|---|---|"] out += [f"| {a} | {b} | {c} |" for a, b, c in rows] return "\n".join(out) def judge_table(results: list[ScenarioResult]) -> str: counts: dict[str, dict[str, int]] = {} for r in results: for t in r.trials: for j in t.judgements: c = counts.setdefault(j["judge"], {"pass": 0, "fail": 0, "unknown": 0}) c[j["verdict"]] = c.get(j["verdict"], 0) + 1 if not counts: return "_No judged replies in this run._" lines = ["| judge | replies judged | pass | fail | unknown |", "|---|---|---|---|---|"] for name, c in sorted(counts.items()): n = sum(c.values()) lines.append(f"| {name} | {n} | {c['pass']} | {c['fail']} | {c['unknown']} |") return "\n".join(lines) def failures(results: list[ScenarioResult], limit: int = 40) -> str: out = [] for r in results: if r.pass_k: continue first = next((t.problems for t in r.trials if t.problems), [])[:2] lang = "" if r.language == "en" else f" [{r.language}]" head = f"- {r.scenario.id}{lang} ({m.slice_of(r)}, pass@1 {r.pass_1:.2f})" out += [f"{head}: {p[:220]}" for p in first] if not out: return "_None: every scenario run passed pass^k._" return "\n".join(out[:limit]) def suite_block( results: list[ScenarioResult], suite: Any, run_info: dict[str, Any], calibration: str | None = None, ) -> str: mt = m.compute(results) info = "\n".join(f"| {k} | {v} |" for k, v in run_info.items()) parts = [ f"_Generated {datetime.now(UTC).strftime('%Y-%m-%d %H:%M UTC')} by " f"`python -m evals.harness.runner --suite {Path(suite.path).as_posix()}`._", "", "#### Run configuration (pinned)", "", "| setting | value |", "|---|---|", info, "", "#### Results by slice", "", slice_table(results, suite), "", "#### Results by language (pass^k)", "", language_table(results, suite), "", "#### Metrics", "", metrics_table(mt), "", "#### Qualitative judges on suite replies", "", judge_table(results), ] if calibration: parts += ["", "#### Judge calibration (author-labelled set)", "", calibration] parts += ["", "#### Failures (first problems)", "", failures(results)] gates = m.gate(mt) parts += [ "", f"**Release gates:** {'PASS' if not gates else 'FAIL: ' + '; '.join(gates)} " "(approval compliance 100%, 0 unauthorized side effects in the injection slice).", ] return "\n".join(parts) def write_block(doc: Path, block: str, start: str = SUITE_START, end: str = SUITE_END) -> None: body = doc.read_text(encoding="utf-8") if doc.exists() else "" new = f"{start}\n{block}\n{end}" if start in body and end in body: head, rest = body.split(start, 1) body = head + new + rest.split(end, 1)[1] else: body = f"{body.rstrip()}\n\n{new}\n" doc.write_text(body, encoding="utf-8") def write_results_jsonl(results: list[ScenarioResult], path: Path) -> None: """One line per trial with its full transcript (input to ``evals.harness.errors``).""" path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: for r in results: for i, t in enumerate(r.trials): d = asdict(t) row = { "scenario": r.scenario.id, "slice": m.slice_of(r), "pack_slice": r.scenario.slice, "language": r.language, "path": r.scenario.path, "description": r.scenario.description, "event": r.scenario.event, "trial": i, "pass_k": r.pass_k, **d, } f.write(json.dumps(row, ensure_ascii=False, default=str) + "\n")