diff --git a/dokimi/changelog.d/20261128_120000_napetrov_arch-r8-45-report-sections.md b/dokimi/changelog.d/20261128_120000_napetrov_arch-r8-45-report-sections.md new file mode 100644 index 000000000..983cc13bd --- /dev/null +++ b/dokimi/changelog.d/20261128_120000_napetrov_arch-r8-45-report-sections.md @@ -0,0 +1,3 @@ +### Changed + +- **Internal: the eval and task-run Markdown reports are built one section at a time.** `generate_report` in `report/eval_report.py` and `render_task_runs_report` in `report/task_runs_report.py` call a helper per section instead of one long body. The reports and the Q&A sidecar are byte-identical, so this has no user-visible effect. diff --git a/dokimi/dokimi/report/eval_report.py b/dokimi/dokimi/report/eval_report.py index 2ca587e79..6f7cf9b7e 100755 --- a/dokimi/dokimi/report/eval_report.py +++ b/dokimi/dokimi/report/eval_report.py @@ -19,6 +19,7 @@ import os import re from collections import Counter, defaultdict +from dataclasses import dataclass from datetime import datetime, timezone from typing import Any @@ -192,6 +193,11 @@ def detect_static_prefix(evals): return None +def _is_static(prefix: str | None, e: Record) -> bool: + """Whether ``e`` is a golden static question: its key starts with the detected static prefix.""" + return bool(prefix and e.key.startswith(prefix)) + + DIAG_MAP = { "docs_helped": "✅ Docs helped", "knowledge_sufficient": "🔵 Model knowledge sufficient", @@ -276,7 +282,25 @@ def _sibling_answers_path(eval_path: str) -> str: return re.sub(r"(^|[\\/])eval(?=[\\/][^\\/]*$)", r"\1answers", eval_path, count=1) -def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = None): +@dataclass(frozen=True) +class _Report: + """What the sections of one eval report read, computed once by :func:`_report_context`.""" + + data: dict + evals: list[Record] + meta: Any + library: str + static_prefix: str | None + static_qs: list[Record] + dynamic_qs: list[Record] + all_stats: dict + static_stats: dict + dyn_stats: dict + diff_groups: dict + valid_all: list[Record] + + +def _report_context(eval_path: str) -> _Report: data = _load_eval(eval_path) evals = records(data["evaluations"], source=eval_path, kind="evaluations") @@ -284,8 +308,8 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non library = os.path.basename(eval_path).replace(".json", "") static_prefix = detect_static_prefix(evals) - static_qs = [e for e in evals if static_prefix and e.key.startswith(static_prefix)] - dynamic_qs = [e for e in evals if not (static_prefix and e.key.startswith(static_prefix))] + static_qs = [e for e in evals if _is_static(static_prefix, e)] + dynamic_qs = [e for e in evals if not _is_static(static_prefix, e)] all_stats = stats(evals) static_stats = stats(static_qs) @@ -299,26 +323,47 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non e for e in evals if has_scores(e) and e.delta is not None and not math.isnan(e.delta) ] + return _Report( + data=data, evals=evals, meta=meta, library=library, static_prefix=static_prefix, + static_qs=static_qs, dynamic_qs=dynamic_qs, all_stats=all_stats, + static_stats=static_stats, dyn_stats=dyn_stats, diff_groups=diff_groups, + valid_all=valid_all, + ) - lines = [] - # Header + context - lines += [ - f"# {library} Documentation Quality Report", +def _source_label(r: _Report, e: Record) -> str: + return "🔵 static" if _is_static(r.static_prefix, e) else "🟡 gen" + + +def _metric(sig: dict, key: str): + """Render a metric, distinguishing "absent" from a real number. + + ``sig.get(key, "N/A")`` only defaults on a *missing key*; these keys + are always present and may hold None, which would print "None". + """ + value = sig.get(key) + return "N/A" if value is None else value + + +def _header_section(r: _Report) -> list[str]: + meta = r.meta + return [ + f"# {r.library} Documentation Quality Report", f"_Generated: {datetime.now(tz=_TZ).strftime('%Y-%m-%d %H:%M %Z') if _TZ else datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}_", "", - *stop_note(data), + *stop_note(r.data), "## Run Configuration", "| | |", "|---|---|", f'| Answer model | {meta.get("answer_model", "—")} ({meta.get("answer_provider", "—")}) |', - f'| Judge model | {data.get("judge_model", "—")} ({data.get("judge_provider", "—")}) |', - f'| Total questions | {all_stats["count"]} ({dyn_stats["count"]} dynamic + {static_stats["count"]} golden static) |', + f'| Judge model | {r.data.get("judge_model", "—")} ({r.data.get("judge_provider", "—")}) |', + f'| Total questions | {r.all_stats["count"]} ({r.dyn_stats["count"]} dynamic + {r.static_stats["count"]} golden static) |', "", ] - # Legend - lines += [ + +def _legend_section() -> list[str]: + return [ "## How to Read This Report", "", "Each answer is scored **0–100** by the judge model across 5 dimensions: " @@ -343,21 +388,23 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non "", ] - # Summary - lines += [ + +def _summary_section(r: _Report) -> list[str]: + return [ "## Summary", "| Set | Count | Context arm | Baseline | Delta |", "|---|---:|---:|---:|---:|", - f'| **All** | {_count_cell(all_stats)} | {" | ".join(_summary_cells(all_stats))} |', - f'| Generated (dynamic) | {_count_cell(dyn_stats)} | {" | ".join(_summary_cells(dyn_stats))} |', - f'| Golden (static) | {_count_cell(static_stats)} | {" | ".join(_summary_cells(static_stats))} |', + f'| **All** | {_count_cell(r.all_stats)} | {" | ".join(_summary_cells(r.all_stats))} |', + f'| Generated (dynamic) | {_count_cell(r.dyn_stats)} | {" | ".join(_summary_cells(r.dyn_stats))} |', + f'| Golden (static) | {_count_cell(r.static_stats)} | {" | ".join(_summary_cells(r.static_stats))} |', "", + *_unpaired_note(r.all_stats), ] - lines += _unpaired_note(all_stats) - # Statistical significance - sig, refusal = _significance_or_refusal(evals) - lines += refusal + +def _significance_section(r: _Report) -> list[str]: + sig, refusal = _significance_or_refusal(r.evals) + lines = list(refusal) if sig: sig_label = ("✅ **Statistically significant** (p < 0.05)" if sig.get("significant") else "❌ **Not statistically significant** (p ≥ 0.05)" if sig.get("significant") is False @@ -367,15 +414,6 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non # abs(cohens_d), which raises on the None that a zero-variance sample # now reports, and could drift from stats.effect_label. effect_label = sig.get("effect", "unknown") - - def _val(key): - """Render a metric, distinguishing "absent" from a real number. - - ``sig.get(key, "N/A")`` only defaults on a *missing key*; these keys - are always present and may hold None, which would print "None". - """ - value = sig.get(key) - return "N/A" if value is None else value lines += [ "## Statistical Significance", f"_Is the delta ({sig['delta_mean']:+}) meaningful for n={sig['n']} questions?_", @@ -384,55 +422,61 @@ def _val(key): "", "| Metric | Value |", "|---|---|", - f"| Sign-flip p (two-sided) | {_val('p')} |", + f"| Sign-flip p (two-sided) | {_metric(sig, 'p')} |", f"| Changed pairs (non-zero delta) | {sig['n_changed']} of {sig['n']} |", - f"| Cohen's d (effect size) | {_val('cohens_d')} ({effect_label}) |", + f"| Cohen's d (effect size) | {_metric(sig, 'cohens_d')} ({effect_label}) |", f"| 95% CI on the delta | [{'-inf' if sig['ci_lo'] is None else sig['ci_lo']}, " - f"{'+inf' if sig['ci_hi'] is None else sig['ci_hi']}] ({_val('ci_method')}) |", + f"{'+inf' if sig['ci_hi'] is None else sig['ci_hi']}] ({_metric(sig, 'ci_method')}) |", f"| Delta mean ± std | {sig['delta_mean']:+} ± {sig['delta_std']} |", "", ] + return lines - # Dynamic vs Static breakdown - lines += [ + +def _breakdown_section(r: _Report) -> list[str]: + lines = [ "## Breakdown: Dynamic vs Static", "| Set | Count | Context | Baseline | Delta | Improved | Degraded | Neutral |", "|---|---:|---:|---:|---:|---:|---:|---:|", ] for label, s in [ - ("Dynamic (generated)", dyn_stats), - ("Golden (static)", static_stats), - ("**Total**", all_stats), + ("Dynamic (generated)", r.dyn_stats), + ("Golden (static)", r.static_stats), + ("**Total**", r.all_stats), ]: lines.append( f'| {label} | {_count_cell(s)} | {" | ".join(_summary_cells(s))} ' f'| {s["improvements"]} | {s["degradations"]} | {s["neutral"]} |' ) lines.append("") + return lines + - # Difficulty breakdown - lines += [ +def _difficulty_section(r: _Report) -> list[str]: + lines = [ "## Breakdown by Difficulty", "| Difficulty | Count | Context | Baseline | Delta | Improved | Degraded |", "|---|---:|---:|---:|---:|---:|---:|", ] for d in DIFFICULTY_ORDER: - if d in diff_groups: - s = stats(diff_groups[d]) + if d in r.diff_groups: + s = stats(r.diff_groups[d]) lines.append( f'| {d} | {_count_cell(s)} | {" | ".join(_summary_cells(s))} ' f'| {s["improvements"]} | {s["degradations"]} |' ) lines.append("") + return lines + - # Diagnosis +def _diagnosis_section(r: _Report) -> list[str]: diag = Counter( e.diagnosis["label"] - for e in evals + for e in r.evals if e.diagnosis is not None and "label" in e.diagnosis ) total_diag = sum(diag.values()) - lines += [ + lines = [ "## Diagnosis", "| Diagnosis | Count | Rate |", "|---|---:|---:|", @@ -441,36 +485,22 @@ def _val(key): name = DIAG_MAP.get(label, label) rate = round(count / total_diag * 100) if total_diag else 0 lines.append(f"| {name} | {count} | {rate}% |") - missing = all_stats["count"] - total_diag + missing = r.all_stats["count"] - total_diag if missing > 0: - lines.append(f"| ⚪ Insufficient data | {missing} | {round(missing/all_stats['count']*100)}% |") + lines.append(f"| ⚪ Insufficient data | {missing} | {round(missing/r.all_stats['count']*100)}% |") lines.append("") + return lines - # Top 15 helped - lines += [ - "## Top 15 — Context Helped Most", - "| QID | Source | Delta | Context | Baseline | Difficulty | Question |", - "|---|---|---:|---:|---:|---|---|", - ] - for e in sorted(valid_all, key=lambda x: x.delta or 0, reverse=True)[:15]: - src = "🔵 static" if static_prefix and e.key.startswith(static_prefix) else "🟡 gen" - q = fmt_question(e.question_text) - delta = round(e.delta, 1) if isinstance(e.delta, float) else e.delta - lines.append( - f'| {e.question_id} | {src} | **{fmt_delta(delta)}** ' - f'| {e.score(CONTEXT)} | {e.score(BASELINE)} ' - f'| {_difficulty(e, "—")} | {q} |' - ) - lines.append("") - # Bottom 15 degradations - lines += [ - "## Bottom 15 — Biggest Degradations", +def _delta_rank_section(r: _Report, title: str, rows: list[Record]) -> list[str]: + """A ranked table of questions by delta, the rows already in the order to show.""" + lines = [ + title, "| QID | Source | Delta | Context | Baseline | Difficulty | Question |", "|---|---|---:|---:|---:|---|---|", ] - for e in sorted(valid_all, key=lambda x: x.delta or 0)[:15]: - src = "🔵 static" if static_prefix and e.key.startswith(static_prefix) else "🟡 gen" + for e in rows: + src = _source_label(r, e) q = fmt_question(e.question_text) delta = round(e.delta, 1) if isinstance(e.delta, float) else e.delta lines.append( @@ -479,10 +509,26 @@ def _val(key): f'| {_difficulty(e, "—")} | {q} |' ) lines.append("") + return lines + + +def _helped_section(r: _Report) -> list[str]: + return _delta_rank_section( + r, "## Top 15 — Context Helped Most", + sorted(r.valid_all, key=lambda x: x.delta or 0, reverse=True)[:15], + ) + + +def _degradations_section(r: _Report) -> list[str]: + return _delta_rank_section( + r, "## Bottom 15 — Biggest Degradations", + sorted(r.valid_all, key=lambda x: x.delta or 0)[:15], + ) + - # Worst baseline by absolute score - baseline_sorted = [e for e in evals if e.score(BASELINE) is not None] - lines += [ +def _baseline_weak_section(r: _Report) -> list[str]: + baseline_sorted = [e for e in r.evals if e.score(BASELINE) is not None] + lines = [ "## Baseline Weak Spots", "_Lowest absolute scores for the base model without retrieval context._", "", @@ -490,35 +536,22 @@ def _val(key): "|---|---|---:|---:|---|---|", ] for e in sorted(baseline_sorted, key=lambda x: x.score(BASELINE) or 0)[:15]: - src = "🔵 static" if static_prefix and e.key.startswith(static_prefix) else "🟡 gen" + src = _source_label(r, e) lines.append( f'| {e.question_id} | {src} | **{e.score(BASELINE)}** | {_score_cell(e, CONTEXT)} ' f'| {_difficulty(e, "—")} | {fmt_question(e.question_text)} |' ) lines.append("") + return lines - # Full Q&A — Static - lines += [ - "## Full Q&A Table — Golden Static Questions", - "| QID | Difficulty | Context | Baseline | Delta | Question |", - "|---|---|---:|---:|---:|---|", - ] - for e in sorted(static_qs, key=lambda x: (_difficulty(x, ""), x.key)): - delta = e.delta - rounded = round(delta, 1) if isinstance(delta, float) else delta - lines.append( - f'| {e.question_id} | {_difficulty(e, "—")} | {_score_cell(e, CONTEXT)} | {_score_cell(e, BASELINE)} ' - f'| {fmt_delta(rounded)} | {fmt_question(e.question_text)} |' - ) - lines.append("") - # Full Q&A — Dynamic - lines += [ - "## Full Q&A Table — Dynamic Generated Questions", +def _qa_table_section(title: str, qs: list[Record]) -> list[str]: + lines = [ + title, "| QID | Difficulty | Context | Baseline | Delta | Question |", "|---|---|---:|---:|---:|---|", ] - for e in sorted(dynamic_qs, key=lambda x: (_difficulty(x, ""), x.key)): + for e in sorted(qs, key=lambda x: (_difficulty(x, ""), x.key)): delta = e.delta rounded = round(delta, 1) if isinstance(delta, float) else delta lines.append( @@ -526,65 +559,101 @@ def _val(key): f'| {fmt_delta(rounded)} | {fmt_question(e.question_text)} |' ) lines.append("") + return lines - # Recommendations - lines += [ - "## Key Observations & Recommendations", - "", - _overall_line(all_stats), - _agreement_line(dyn_stats, static_stats), - f'- **Win rate:** {round(all_stats["improvements"]/all_stats["valid"]*100) if all_stats["valid"] else 0}% questions improved with context ' - f'({all_stats["improvements"]}/{all_stats["valid"]}).', - f'- **Degradations:** {all_stats["degradations"]} questions ' - f'({round(all_stats["degradations"]/all_stats["valid"]*100) if all_stats["valid"] else 0}%).', - "", - ] - report = "\n".join(lines) +def _qa_static_section(r: _Report) -> list[str]: + return _qa_table_section("## Full Q&A Table — Golden Static Questions", r.static_qs) - dir_path = os.path.dirname(out_path) - if dir_path: - os.makedirs(dir_path, exist_ok=True) - write_bytes_in_place_or_atomic(out_path, text_file_bytes(report)) - # Sidecar JSON: questions + answers + scores - if qa_json_out is None: - qa_json_out = os.path.splitext(out_path)[0] + ".qa.json" +def _qa_dynamic_section(r: _Report) -> list[str]: + return _qa_table_section("## Full Q&A Table — Dynamic Generated Questions", r.dynamic_qs) - answers_by_id = _answers_by_id(_sibling_answers_path(eval_path)) - def _answer_text(a: Record | None, condition: str): - answer = a.answer(condition) if a is not None else None - return answer.text if answer is not None else None +def _recommendations_section(r: _Report) -> list[str]: + return [ + "## Key Observations & Recommendations", + "", + _overall_line(r.all_stats), + _agreement_line(r.dyn_stats, r.static_stats), + f'- **Win rate:** {round(r.all_stats["improvements"]/r.all_stats["valid"]*100) if r.all_stats["valid"] else 0}% questions improved with context ' + f'({r.all_stats["improvements"]}/{r.all_stats["valid"]}).', + f'- **Degradations:** {r.all_stats["degradations"]} questions ' + f'({round(r.all_stats["degradations"]/r.all_stats["valid"]*100) if r.all_stats["valid"] else 0}%).', + "", + ] + +def _report_lines(r: _Report) -> list[str]: + lines = [] + lines += _header_section(r) + lines += _legend_section() + lines += _summary_section(r) + lines += _significance_section(r) + lines += _breakdown_section(r) + lines += _difficulty_section(r) + lines += _diagnosis_section(r) + lines += _helped_section(r) + lines += _degradations_section(r) + lines += _baseline_weak_section(r) + lines += _qa_static_section(r) + lines += _qa_dynamic_section(r) + lines += _recommendations_section(r) + return lines + + +def _answer_text(a: Record | None, condition: str): + answer = a.answer(condition) if a is not None else None + return answer.text if answer is not None else None + + +def _qa_records(r: _Report, answers_by_id: dict[str, Record]) -> list[dict]: + """The Q&A sidecar's one row per question: its text, scores and both arms' answers.""" qa_records = [] - for e in evals: + for e in r.evals: a = answers_by_id.get(e.key) qa_records.append({ "question_id": e.question_id, "question_text": _sidecar_question_text(e), "difficulty": e.difficulty, - "source": "static" if static_prefix and e.key.startswith(static_prefix) else "dynamic", + "source": "static" if _is_static(r.static_prefix, e) else "dynamic", "with_docs_score": e.score(CONTEXT), "without_docs_score": e.score(BASELINE), "delta": e.delta, "with_docs_answer": _answer_text(a, CONTEXT), "without_docs_answer": _answer_text(a, BASELINE), }) + return qa_records + + +def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = None): + r = _report_context(eval_path) + report = "\n".join(_report_lines(r)) + dir_path = os.path.dirname(out_path) + if dir_path: + os.makedirs(dir_path, exist_ok=True) + write_bytes_in_place_or_atomic(out_path, text_file_bytes(report)) + + # Sidecar JSON: questions + answers + scores + if qa_json_out is None: + qa_json_out = os.path.splitext(out_path)[0] + ".qa.json" + + answers_by_id = _answers_by_id(_sibling_answers_path(eval_path)) + qa_records = _qa_records(r, answers_by_id) _write_qa_json(qa_json_out, { "eval_path": eval_path, "report_path": out_path, "generated_at": datetime.now(timezone.utc).isoformat(), - "run_metadata": with_stop(meta, data), + "run_metadata": with_stop(r.meta, r.data), "count": len(qa_records), "records": qa_records, }) print(f"✅ Report written to: {out_path}") print(f"✅ Q&A JSON written to: {qa_json_out}") - print(f" Questions: {all_stats['count']} ({dyn_stats['count']} dynamic + {static_stats['count']} static)") - print(_delta_summary(all_stats)) + print(f" Questions: {r.all_stats['count']} ({r.dyn_stats['count']} dynamic + {r.static_stats['count']} static)") + print(_delta_summary(r.all_stats)) return out_path diff --git a/dokimi/dokimi/report/task_runs_report.py b/dokimi/dokimi/report/task_runs_report.py index cd32813ec..838d42f25 100644 --- a/dokimi/dokimi/report/task_runs_report.py +++ b/dokimi/dokimi/report/task_runs_report.py @@ -23,6 +23,7 @@ import json from collections import defaultdict +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -168,9 +169,20 @@ def _discovery_lines(data: dict[str, Any]) -> list[str]: return lines + note -def render_task_runs_report(data: dict[str, Any]) -> str: - """Render a ``task_runs.v1`` artifact as Markdown.""" - lines: list[str] = [] +@dataclass(frozen=True) +class _RunContext: + """What the sections of one task-run report read, taken from the artifact once.""" + + data: dict[str, Any] + per_harness: dict[str, Any] + harnesses: list[str] + diff_of: dict[str, Any] + status_of_task: dict[str, str] + rows: list[dict[str, Any]] + baseline: str | None + + +def _run_context(data: dict[str, Any]) -> _RunContext: ph = data.get("summary", {}).get("per_harness", {}) harnesses = list(ph.keys()) diff_of = { @@ -187,26 +199,33 @@ def render_task_runs_report(data: dict[str, Any]) -> str: if r["harness"] not in seen: seen.append(r["harness"]) harnesses = seen + return _RunContext(data=data, per_harness=ph, harnesses=harnesses, diff_of=diff_of, + status_of_task=status_of_task, rows=rows, baseline=baseline) - lines.append("# Executable task-run report") - lines.append("") - lines.append(f"- Model: `{data.get('model', '?')}`") - lines.append(f"- Repeats: {data.get('repeats', 1)}") - lines.append(f"- Harnesses: {', '.join(f'`{h}`' for h in harnesses)}") - lines.append(f"- Baseline: `{baseline}`" if baseline else "- Baseline: —") - lines.append(f"- Generated: `{data.get('generated_at', '?')}`") - lines.append("") - # ── headline ── - lines.append("## Headline") - lines.append("") +def _header_lines(c: _RunContext) -> list[str]: + return [ + "# Executable task-run report", + "", + f"- Model: `{c.data.get('model', '?')}`", + f"- Repeats: {c.data.get('repeats', 1)}", + f"- Harnesses: {', '.join(f'`{h}`' for h in c.harnesses)}", + f"- Baseline: `{c.baseline}`" if c.baseline else "- Baseline: —", + f"- Generated: `{c.data.get('generated_at', '?')}`", + "", + ] + + +def _headline_section(c: _RunContext) -> list[str]: + ph = c.per_harness + lines = ["## Headline", ""] lines.append(f"| Harness | Pass rate | Errored | {PASS_RATE_CI_CONFIDENCE:.0%} CI (Wilson) | " "Cost (USD) | $/pass | Wall (min) | " "Completion tok | Cache read tok | Cost-known | Skill invoked (rows reporting) |") lines.append("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") - for h in harnesses: + for h in c.harnesses: s = ph.get(h, {}) - c = s.get("cost", {}) + c_s = s.get("cost", {}) rate = s.get("pass_rate") scored = s.get("scored", s.get("n", 0)) rate_s = fmt.percent(rate, 2) + (f" ({s.get('passed', 0)}/{scored})" if is_number(rate) else "") @@ -216,24 +235,29 @@ def render_task_runs_report(data: dict[str, Any]) -> str: sir = s.get("skill_invocation_rate") sir_s = fmt.percent(sir) + (f" ({s.get('skill_invocation_n', 0)})" if is_number(sir) else "") lines.append( - f"| `{h}` | {rate_s} | {s.get('errored', 0)} | {ci_s} | {fmt.usd(c.get('total_cost_usd'))} | " - f"{fmt.usd(c.get('cost_per_pass_usd'))} | " - f"{s.get('elapsed_sec', 0)/60:.1f} | {_or_dash(c.get('completion_tokens'))} | " - f"{_or_dash(c.get('cache_read_tokens'))} | " - f"{c.get('cost_known_n', '—')}/{s.get('n', 0)} | {sir_s} |" + f"| `{h}` | {rate_s} | {s.get('errored', 0)} | {ci_s} | {fmt.usd(c_s.get('total_cost_usd'))} | " + f"{fmt.usd(c_s.get('cost_per_pass_usd'))} | " + f"{s.get('elapsed_sec', 0)/60:.1f} | {_or_dash(c_s.get('completion_tokens'))} | " + f"{_or_dash(c_s.get('cache_read_tokens'))} | " + f"{c_s.get('cost_known_n', '—')}/{s.get('n', 0)} | {sir_s} |" ) lines.append("") - if any(ph.get(h, {}).get("errored") for h in harnesses): + if any(ph.get(h, {}).get("errored") for h in c.harnesses): lines.append("_Pass rate is over scored cells. An errored cell is one whose " "harness raised (docker build, exec, config) or the solver CLI made " "no attempt (rejected credentials): it produced no verdict, so it is " "missing data, not a 0. An agent or verifier timeout is a failure, " "not an error._") lines.append("") + return lines + - # ── per-cell aggregation, keyed by full harness id ── - # cost is None until a row actually reports cost_usd, so harnesses without - # LLM telemetry (oracle, dry runs) render "—" rather than a fake $0.0000. +def _aggregate_cells(rows: list[dict[str, Any]]) -> tuple[list[str], dict[tuple[str, str], dict[str, Any]]]: + """Per (task, full harness id) cell: pass counts, cost and each repeat's detail. + + cost is None until a row actually reports cost_usd, so harnesses without + LLM telemetry (oracle, dry runs) render "—" rather than a fake $0.0000. + """ tasks = sorted({r["task"] for r in rows}) cell: dict[tuple[str, str], dict[str, Any]] = defaultdict( lambda: {"passed": 0, "n": 0, "errored": 0, "cost": None, "detail": []} @@ -255,91 +279,98 @@ def render_task_runs_report(data: dict[str, Any]) -> str: "rc": r.get("returncode"), "cost": cost, "turns": turns, "claim": claim, }) + return tasks, cell - # ── difficulty rollup (one column pair per harness) ── - lines.append("## Difficulty rollup") - lines.append("") - lines.append("| Difficulty | Tasks | " + " | ".join(f"`{h}` pass" for h in harnesses) + " |") - lines.append("|-----------|------:|" + "|".join("------:" for _ in harnesses) + "|") + +def _difficulty_section(c: _RunContext, tasks: list[str], cell: dict) -> list[str]: + """The difficulty rollup, one column pair per harness.""" + lines = ["## Difficulty rollup", ""] + lines.append("| Difficulty | Tasks | " + " | ".join(f"`{h}` pass" for h in c.harnesses) + " |") + lines.append("|-----------|------:|" + "|".join("------:" for _ in c.harnesses) + "|") by_diff: dict[str, dict[str, list[int]]] = defaultdict( - lambda: {h: [0, 0, 0] for h in harnesses} + lambda: {h: [0, 0, 0] for h in c.harnesses} ) for t in tasks: - dlv = diff_of.get(t, "?") - for h in harnesses: + dlv = c.diff_of.get(t, "?") + for h in c.harnesses: by_diff[dlv][h][0] += cell[(t, h)]["passed"] by_diff[dlv][h][1] += cell[(t, h)]["n"] by_diff[dlv][h][2] += cell[(t, h)]["errored"] for dlv in sorted(by_diff): - n_tasks = sum(1 for t in tasks if diff_of.get(t) == dlv) + n_tasks = sum(1 for t in tasks if c.diff_of.get(t) == dlv) cols = [] - for h in harnesses: + for h in c.harnesses: p, n, e = by_diff[dlv][h] cols.append((f"{p}/{n}" if n else "—") + (f" (+{e} err)" if e else "")) lines.append(f"| {dlv} | {n_tasks} | " + " | ".join(cols) + " |") lines.append("") + return lines - # ── comparison (straight from artifact) ── - cmp = data.get("summary", {}).get("comparisons", {}) - if cmp: - lines.append("## Comparison vs baseline") - lines.append("") - lines.append("| Harness | Pass-rate Δ | Normalized gain (Hake) | Normalized change | " - "Passed Δ | Op-count Δ | Cost Δ (USD) |") - lines.append("| --- | ---: | ---: | ---: | ---: | ---: | ---: |") - for h, cr in cmp.items(): - prd = cr.get("pass_rate_delta") - withheld = cr.get("passed_delta", 0) is None - prd_s = fmt.points(prd, missing="— (arms lost different cells)" if withheld else fmt.DASH) - # With a delta in hand, a null gain/change is the formula's own - # undefined case; without one, it is withheld with the delta. An - # artifact older than these keys has no reason to give. - has_delta = is_number(prd) - ng_s = _norm_cell(cr.get("normalized_gain"), "withheld" if withheld else - "baseline at 100%" if has_delta and "normalized_gain" in cr - else None) - nc_s = _norm_cell(cr.get("normalized_change"), "withheld" if withheld else - "both at 0% or 100%" if has_delta and "normalized_change" in cr - else None) - pd = cr.get("passed_delta", 0) - pd_s = "—" if pd is None else f"{pd:+}" - lines.append(f"| `{h}` | {prd_s} | {ng_s} | {nc_s} | {pd_s} | " - f"{cr.get('operation_count_delta', 0):+} | {fmt.signed(cr.get('cost_delta_usd'), 4)} |") - lines.append("") - lines.extend(_mcnemar_lines(cmp, baseline)) - lines.extend(_discovery_lines(data)) - # ── per-task pass + cost (one column pair per harness) ── - lines.append("## Per-task pass + cost") +def _comparison_section(c: _RunContext) -> list[str]: + """The comparison against the baseline (straight from the artifact), with its McNemar table.""" + cmp = c.data.get("summary", {}).get("comparisons", {}) + if not cmp: + return [] + lines = ["## Comparison vs baseline", ""] + lines.append("| Harness | Pass-rate Δ | Normalized gain (Hake) | Normalized change | " + "Passed Δ | Op-count Δ | Cost Δ (USD) |") + lines.append("| --- | ---: | ---: | ---: | ---: | ---: | ---: |") + for h, cr in cmp.items(): + prd = cr.get("pass_rate_delta") + withheld = cr.get("passed_delta", 0) is None + prd_s = fmt.points(prd, missing="— (arms lost different cells)" if withheld else fmt.DASH) + # A null gain or change is the formula's own undefined case when a delta + # exists, and is withheld with the delta otherwise (older artifacts: no reason). + has_delta = is_number(prd) + ng_s = _norm_cell(cr.get("normalized_gain"), "withheld" if withheld else + "baseline at 100%" if has_delta and "normalized_gain" in cr + else None) + nc_s = _norm_cell(cr.get("normalized_change"), "withheld" if withheld else + "both at 0% or 100%" if has_delta and "normalized_change" in cr + else None) + pd = cr.get("passed_delta", 0) + pd_s = "—" if pd is None else f"{pd:+}" + lines.append(f"| `{h}` | {prd_s} | {ng_s} | {nc_s} | {pd_s} | " + f"{cr.get('operation_count_delta', 0):+} | {fmt.signed(cr.get('cost_delta_usd'), 4)} |") lines.append("") + lines.extend(_mcnemar_lines(cmp, c.baseline)) + return lines + + +def _task_table_section(c: _RunContext, tasks: list[str], cell: dict) -> list[str]: + """The per-task pass and cost, one column pair per harness.""" + lines = ["## Per-task pass + cost", ""] lines.append("| Task | Diff | Status | " + " | ".join( - f"`{h}` pass | `{h}` $" for h in harnesses + f"`{h}` pass | `{h}` $" for h in c.harnesses ) + " |") - lines.append("| --- | :---: | :---: |" + "|".join(" :---: | ---: " for _ in harnesses) + "|") + lines.append("| --- | :---: | :---: |" + "|".join(" :---: | ---: " for _ in c.harnesses) + "|") for t in tasks: cols = [] - for h in harnesses: - c = cell[(t, h)] - err_s = f" (+{c['errored']} err)" if c["errored"] else "" - pass_s = f"{c['passed']}/{c['n']}" if c["n"] else "—" - cols.append(f"{pass_s}{err_s} | {fmt.usd(c['cost'])}") - lines.append(f"| {t} | {diff_of.get(t, '?')} | {status_of_task.get(t, UNKNOWN)} | " + " | ".join(cols) + " |") + for h in c.harnesses: + cc = cell[(t, h)] + err_s = f" (+{cc['errored']} err)" if cc["errored"] else "" + pass_s = f"{cc['passed']}/{cc['n']}" if cc["n"] else "—" + cols.append(f"{pass_s}{err_s} | {fmt.usd(cc['cost'])}") + lines.append(f"| {t} | {c.diff_of.get(t, '?')} | {c.status_of_task.get(t, UNKNOWN)} | " + " | ".join(cols) + " |") lines.append("") + return lines - # ── per-cell answer detail ── - lines.append("## Per-cell answer detail") - lines.append("") + +def _cell_detail_section(c: _RunContext, tasks: list[str], cell: dict) -> list[str]: + """The per-cell answer detail: verifier verdict beside the model's own self-report.""" + lines = ["## Per-cell answer detail", ""] lines.append("Each repeat: verifier reward, pass/fail, turns, cost, and the model's " "own one-line self-report. ⚠️ marks cells where the model claimed " "success (\"done\") yet the verifier scored 0 — usually correct code " "that missed the performance bar the verifier enforces.") lines.append("") for t in tasks: - lines.append(f"### {t} ({diff_of.get(t, '?')})") + lines.append(f"### {t} ({c.diff_of.get(t, '?')})") lines.append("") lines.append("| Harness | Rep | Reward | Pass | Turns | Cost | Model self-report |") lines.append("| --- | :---: | :---: | :---: | :---: | ---: | --- |") - for h in harnesses: + for h in c.harnesses: for det in sorted(cell[(t, h)]["detail"], key=lambda x: x["repeat"]): rw = det["reward"] rw_s = f"{rw:g}" if as_float(rw) is not None else "null" @@ -356,5 +387,18 @@ def render_task_runs_report(data: dict[str, Any]) -> str: lines.append(f"| `{h}` | {det['repeat']} | {rw_s} | {pass_s} | {turns_s} | " f"{fmt.usd(det['cost'])} | {_md_cell(claim)} |") lines.append("") + return lines + +def render_task_runs_report(data: dict[str, Any]) -> str: + """Render a ``task_runs.v1`` artifact as Markdown.""" + c = _run_context(data) + lines = _header_lines(c) + lines += _headline_section(c) + tasks, cell = _aggregate_cells(c.rows) + lines += _difficulty_section(c, tasks, cell) + lines += _comparison_section(c) + lines += _discovery_lines(data) + lines += _task_table_section(c, tasks, cell) + lines += _cell_detail_section(c, tasks, cell) return "\n".join(lines) diff --git a/dokimi/scripts/duplicates_baseline.json b/dokimi/scripts/duplicates_baseline.json index dab4dde94..119a58198 100644 --- a/dokimi/scripts/duplicates_baseline.json +++ b/dokimi/scripts/duplicates_baseline.json @@ -2,11 +2,9 @@ "groups": { "3c397e7b5b50": {"count": 3, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/repos/cli_traces.py", "dokimi/repos/events.py"]}, "4751a8be1f57": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/eval/agent_runner.py"]}, - "925b1461ae22": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/report/eval_report.py"]}, "96a248688260": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/commands/baseline.py", "dokimi/eval/judge.py"]}, "9912f72bb7c0": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/repos/reach.py", "dokimi/repos/skill_reach.py"]}, "a2801d27c7b0": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/eval/ragas_eval.py"]}, - "aa55a06bf99c": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/report/eval_report.py"]}, "b120773b627e": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/commands/repo_run.py"]}, "d3dc645dd2cc": {"count": 3, "rationale": "pre-existing when the gate was introduced", "where": ["scripts/check_changelog_fragment.py", "scripts/check_comment_blocks.py", "scripts/check_docs_review_triggers.py"]}, "e00d5aa50148": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/repos/reach.py", "dokimi/repos/skill_reach.py"]}, diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 4b7affcc4..dbe60cf88 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -54,12 +54,10 @@ "dokimi/questions/validator.py::QuestionValidator._deduplicate": {"complexity": 13}, "dokimi/records.py::record": {"complexity": 14, "rationale": "pre-existing when the gate was introduced"}, "dokimi/report/arms_report.py::render_arms_report": {"complexity": 20}, - "dokimi/report/eval_report.py::generate_report": {"complexity": 18}, "dokimi/report/generator.py::ReportGenerator._format_markdown": {"complexity": 16}, "dokimi/report/model_compare.py::check_run_consistency": {"complexity": 13}, "dokimi/report/model_compare.py::extract_scores": {"complexity": 16}, "dokimi/report/subject_report.py::render_subject_scorecard": {"complexity": 12}, - "dokimi/report/task_runs_report.py::render_task_runs_report": {"complexity": 20}, "dokimi/repos/environment/__init__.py::inspect_repo": {"complexity": 22, "rationale": "pre-existing when the gate was introduced"}, "dokimi/repos/environment/checks.py::_python": {"complexity": 11, "rationale": "pre-existing when the gate was introduced"}, "dokimi/repos/environment/risks.py::_runs_repository_code": {"complexity": 12, "rationale": "pre-existing when the gate was introduced"}, diff --git a/dokimi/tests/test_report_fmt.py b/dokimi/tests/test_report_fmt.py index 8627809b5..e48647e2b 100644 --- a/dokimi/tests/test_report_fmt.py +++ b/dokimi/tests/test_report_fmt.py @@ -25,6 +25,7 @@ from dokimi.eval.arm_summary import TOOL_COUNTS from dokimi.report import fmt from dokimi.report.arms_report import render_arms_report +from dokimi.report.eval_report import generate_report as generate_eval_report from dokimi.report.exploration_report import render_exploration_metrics, render_explore_report from dokimi.report.generator import ReportGenerator from dokimi.report.model_compare import generate_section_report @@ -359,3 +360,50 @@ def test_plain_prints_any_stored_value_but_none(): def test_verdict_keeps_unknown_apart_from_no(): assert [fmt.verdict(v) for v in (None, True, False)] == ["—", "yes", "no"] + + +def test_the_eval_report_has_every_section_in_order_with_its_rows(tmp_path): + """``generate_report`` on one golden static and one generated question: each section and its rows.""" + rows = [ + {"question_id": "lib-Q001", "question_text": "Static?", "difficulty": "easy", "delta": 20.0, + "with_docs": {"aggregate": 80.0}, "without_docs": {"aggregate": 60.0}, "diagnosis": {"label": "docs_helped"}}, + {"question_id": "gen-1", "question_text": "Generated?", "difficulty": "hard", "delta": -10.0, + "with_docs": {"aggregate": 40.0}, "without_docs": {"aggregate": 50.0}, "diagnosis": {"label": "low_relevance"}}, + ] + path = tmp_path / "eval" / "lib.json" + path.parent.mkdir() + path.write_text(json.dumps({"judge_model": "j", "evaluations": rows}), encoding="utf-8") + md, qa = tmp_path / "lib.md", tmp_path / "lib.qa.json" + generate_eval_report(str(path), str(md), str(qa)) + text = md.read_text(encoding="utf-8") + + assert text.startswith("# lib Documentation Quality Report\n") + sections: dict[str, list[str]] = {} + for line in text.split("\n"): + if line.startswith("## "): + sections[line[3:]] = [] + elif sections: + sections[list(sections)[-1]].append(line) + assert list(sections) == [ + "Run Configuration", "How to Read This Report", "Summary", "Statistical Significance", + "Breakdown: Dynamic vs Static", "Breakdown by Difficulty", "Diagnosis", + "Top 15 — Context Helped Most", "Bottom 15 — Biggest Degradations", "Baseline Weak Spots", + "Full Q&A Table — Golden Static Questions", "Full Q&A Table — Dynamic Generated Questions", + "Key Observations & Recommendations", + ] + static_row = "| lib-Q001 | 🔵 static | **+20.0** | 80.0 | 60.0 | easy | Static? |" + gen_row = "| gen-1 | 🟡 gen | **-10.0** | 40.0 | 50.0 | hard | Generated? |" + assert "| Total questions | 2 (1 dynamic + 1 golden static) |" in sections["Run Configuration"] + assert "| 🟡 Low relevance | 1 | 50% |" in sections["Diagnosis"] + assert sections["Top 15 — Context Helped Most"][2:4] == [static_row, gen_row] + assert sections["Bottom 15 — Biggest Degradations"][2:4] == [gen_row, static_row] + assert sections["Baseline Weak Spots"][4:6] == [ + "| gen-1 | 🟡 gen | **50.0** | 40.0 | hard | Generated? |", + "| lib-Q001 | 🔵 static | **60.0** | 80.0 | easy | Static? |", + ] + assert sections["Full Q&A Table — Golden Static Questions"][2:] == [ + "| lib-Q001 | easy | 80.0 | 60.0 | +20.0 | Static? |", ""] + assert sections["Full Q&A Table — Dynamic Generated Questions"][2:] == [ + "| gen-1 | hard | 40.0 | 50.0 | -10.0 | Generated? |", ""] + records = json.loads(qa.read_text(encoding="utf-8"))["records"] + assert [(rec["question_id"], rec["source"]) for rec in records] == [("lib-Q001", "static"), ("gen-1", "dynamic")]