diff --git a/.claude/notes/orchestration.md b/.claude/notes/orchestration.md index 074e4be3..d6392035 100644 --- a/.claude/notes/orchestration.md +++ b/.claude/notes/orchestration.md @@ -933,17 +933,17 @@ Ungraded replicates — and ONLY those — drop out of a mean entirely: `or 0.0` a clean `execute` run down to a real-looking zero, while dropping an ERRORED one would pay it a bonus. -The rule lives once, in `result_metrics.measured_scores`, read by `VariantAggregate.average_score` -and run.md's Avg Reliability Score. run.md also hides that score whenever `nothing_was_measured` -holds, as the pass rate beside it does. Two known gaps remain. Closing either one changes a -serialized field that downstream consumers read, so each is a separate change: +The rule lives once: `result_metrics.measured_scores` picks the rows, and `measured_mean` takes +the headline mean, `None` when `nothing_was_measured` holds, as the pass rate beside it is. +run.md's Avg Reliability Score and suite.json's `average_weighted_score` read `measured_mean`; +`VariantAggregate.average_score` reads `measured_scores` only. One known gap remains. Closing it +changes a serialized field that downstream consumers read, so it is a separate change: -- `SuiteRollup.average_weighted_score` (suite.json) still averages scored rows only, so an - errored row leaves it. - `aggregate_results` counts `VariantAggregate.tasks_measured` after `_fold_replicates` has turned an errored replicate's missing score into 0.0, so an `execute` run with a crash - reports `pass_rate` 0.0 and `average_score` 0.0 in experiment.json where run.json reports - `None`. + reports `pass_rate` 0.0 and `average_score` 0.0 in experiment.json where run.json has no + `pass_rate` and run.md shows no score. Pinned by the strict xfail + `tests/test_ungraded_reporting.py::test_every_surface_has_no_mean_when_nothing_was_measured`. Only graded variants can win or set a spread; including ungraded ones at 0.0 would name an arbitrary "best" among scores that do not exist. When NOTHING was scored there is no diff --git a/docs/REPORT_SCHEMA.md b/docs/REPORT_SCHEMA.md index c1e11220..6b18138b 100644 --- a/docs/REPORT_SCHEMA.md +++ b/docs/REPORT_SCHEMA.md @@ -330,7 +330,7 @@ Written for dataset-backed suites; its `passed` flag drives the CI exit code. | `rows_total` / `rows_passed` / `rows_failed` / `rows_error` / `rows_not_graded` | `int` | Row counts. **Invariant:** the four category counts sum to `rows_total`. `rows_not_graded` defaults to `0`. | | `pass_rate` | `float \| null` | `rows_passed / rows_graded` — ungraded rows leave both sides, matching `RunSummary.pass_rate`. `null` when nothing was graded (0/0 is unknown, not 0%) **and** when no row produced a verdict, via the same shared `nothing_was_measured` helper the other two rates use. | | `rows_graded` | `int` | `rows_total - rows_not_graded`. The denominator above, serialized so a consumer never has to re-derive it. | -| `average_weighted_score` | `float \| null` | Mean row score. | +| `average_weighted_score` | `float \| null` | Mean `weighted_score` over every row except `NOT_GRADED` ones. A row with no score (`ERROR`, `BUILD_FAILED`, an unscored `TIMEOUT`) counts as `0.0`; a scored `TIMEOUT` keeps its score. `null` when the suite has no counted rows, or when it has `NOT_GRADED` rows and no row has a score (`nothing_was_measured`, the gate `pass_rate` uses). A suite of only errored rows scores `0.0`. run.md's Avg Reliability Score uses the same rule and gate. `VariantAggregate.average_score` uses the same rule but not the gate yet (a known gap in the orchestration notes). | | `criterion_stats` | `list[{criterion_type, rows_evaluated, average_score, error_count}]` | Per-criterion summary. | | `failed_samples` | `list[FailedRowSummary]` | Capped at 20 (`{row_id, task_id, final_status, weighted_score, failure_reasons, error_message, task_json_relpath, replicate_index}`). | | `criterion_aggregates` | `list[CriterionAggregate]` | The thresholdable metrics — see below. | diff --git a/src/coder_eval/models/results.py b/src/coder_eval/models/results.py index c8c1a893..d38b095a 100644 --- a/src/coder_eval/models/results.py +++ b/src/coder_eval/models/results.py @@ -968,7 +968,11 @@ class SuiteRollup(BaseModel): ), ) average_weighted_score: float | None = Field( - default=None, description="Mean weighted_score across rows that produced one." + default=None, + description=( + "Mean weighted_score over every row except NOT_GRADED ones; a row with no score counts as 0.0. " + "None when no row counts, or when nothing_was_measured holds, as for pass_rate." + ), ) criterion_stats: list[CriterionStats] = Field(default_factory=list) failed_samples: list[FailedRowSummary] = Field( diff --git a/src/coder_eval/reports/markdown.py b/src/coder_eval/reports/markdown.py index c2d6fbfc..e112801e 100644 --- a/src/coder_eval/reports/markdown.py +++ b/src/coder_eval/reports/markdown.py @@ -27,7 +27,7 @@ sum_costs, ) from ..path_utils import TASK_JSON_FILENAME, build_task_run_dir -from ..result_metrics import measured_scores +from ..result_metrics import measured_mean if TYPE_CHECKING: @@ -471,15 +471,18 @@ def _summary_section_lines(summary: RunSummary) -> list[str]: ] # Aggregate P0 metrics - scores = measured_scores((t["status"], t.get("weighted_score")) for t in summary.task_results) + avg_score = measured_mean( + ((t["status"], t.get("weighted_score")) for t in summary.task_results), + not_graded=summary.tasks_not_graded, + measured=summary.tasks_measured, + ) durations = [t["duration"] for t in summary.task_results if t["duration"] > 0] similarities = [ t["reference_similarity"] for t in summary.task_results if t.get("reference_similarity") is not None ] - # Gated like the pass rate: a 0.000 beside "Pass Rate: n/a" would read as "scored zero". - if scores and not nothing_was_measured(not_graded=summary.tasks_not_graded, measured=summary.tasks_measured): - lines.append(f"- **Avg Reliability Score**: {sum(scores) / len(scores):.3f}") + if avg_score is not None: + lines.append(f"- **Avg Reliability Score**: {avg_score:.3f}") if durations: # `duration` is END-TO-END (setup + agent + grading), so the label says so. # The agent's own share and the checker's share are averaged separately, @@ -956,14 +959,14 @@ def _compute_suite_rollup( rows_not_graded = sum(1 for r in rows if r.result.final_status.category == "ungraded") rows_graded = rows_total - rows_not_graded - scored = [r.result.weighted_score for r in rows if r.result.weighted_score is not None] # Verdict evidence, distinct from `rows_graded` (a bucket complement): a # TIMEOUT counts as graded while no criterion ever ran on it. - rows_measured = len(scored) - # Not yet `measured_scores`: an errored row still leaves this mean. A known gap, kept apart - # because closing it changes suite.json's `average_weighted_score`. - # Rationale: .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them - average_weighted_score = sum(scored) / len(scored) if scored else None + rows_measured = sum(1 for r in rows if r.result.weighted_score is not None) + average_weighted_score = measured_mean( + ((r.result.final_status, r.result.weighted_score) for r in rows), + not_graded=rows_not_graded, + measured=rows_measured, + ) # Per-criterion-type tallies (scores + errors) for the type-level summary. by_type: dict[str, list[float]] = defaultdict(list) diff --git a/src/coder_eval/result_metrics.py b/src/coder_eval/result_metrics.py index 93609be0..8b6494ac 100644 --- a/src/coder_eval/result_metrics.py +++ b/src/coder_eval/result_metrics.py @@ -17,7 +17,7 @@ from collections.abc import Iterable from typing import NamedTuple -from coder_eval.models import AssistantMessage, EvaluationResult, FinalStatus, TurnRecord +from coder_eval.models import AssistantMessage, EvaluationResult, FinalStatus, TurnRecord, nothing_was_measured from coder_eval.timing import main_thread_tool_spans, union_ms @@ -134,6 +134,21 @@ def measured_scores(rows: Iterable[tuple[str, float | None]]) -> list[float]: ] +def measured_mean(rows: Iterable[tuple[str, float | None]], *, not_graded: int, measured: int) -> float | None: + """The headline mean of ``measured_scores(rows)``, or ``None`` when there is none to report. + + ``None`` when no row counts toward the mean, and when ``nothing_was_measured`` + holds for the caller's counts, so an otherwise ungraded run with a crash shows + no score rather than ``0.000``, as its pass rate shows none. + + Rationale: .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them + """ + if nothing_was_measured(not_graded=not_graded, measured=measured): + return None + scores = measured_scores(rows) + return sum(scores) / len(scores) if scores else None + + def _sum_measured(values: Iterable[float | None]) -> float | None: """Sum what was measured, or ``None`` when nothing was. diff --git a/tests/test_suite_rollup.py b/tests/test_suite_rollup.py index 719b5e67..5a97cf2f 100644 --- a/tests/test_suite_rollup.py +++ b/tests/test_suite_rollup.py @@ -82,6 +82,9 @@ def _make_row( ) +_GRADED_ROWS: list[tuple[str, float | None]] = [("SUCCESS", 1.0), ("FAILURE", 0.0)] + + class TestComputeSuiteRollup: def test_all_passed(self, tmp_path: Path) -> None: rows = [ @@ -134,13 +137,34 @@ def test_mixed_outcomes(self, tmp_path: Path) -> None: assert rollup.rows_failed == 1 assert rollup.rows_error == 1 assert abs(rollup.pass_rate - 1 / 3) < 1e-9 - # average only over rows with weighted_score - assert rollup.average_weighted_score is not None - assert abs(rollup.average_weighted_score - 0.7) < 1e-9 + assert rollup.average_weighted_score == pytest.approx((1.0 + 0.4 + 0.0) / 3) # failed samples cover the failed and error rows ids = sorted(s.row_id for s in rollup.failed_samples if s.row_id is not None) assert ids == ["r2", "r3"] + @pytest.mark.parametrize( + ("statuses_and_scores", "expected"), + [ + pytest.param([*_GRADED_ROWS, ("ERROR", None)], 1 / 3, id="error-counts-as-zero"), + pytest.param([*_GRADED_ROWS, ("BUILD_FAILED", None)], 1 / 3, id="build-failed-counts-as-zero"), + pytest.param([*_GRADED_ROWS, ("TIMEOUT", None)], 1 / 3, id="unscored-timeout-counts-as-zero"), + pytest.param([*_GRADED_ROWS, ("TIMEOUT", 0.5)], 0.5, id="scored-timeout-keeps-its-score"), + pytest.param([*_GRADED_ROWS, ("NOT_GRADED", None)], 0.5, id="not-graded-leaves-the-mean"), + pytest.param([("ERROR", None), ("ERROR", None)], 0.0, id="all-error-suite-scores-zero"), + pytest.param([("NOT_GRADED", None), ("NOT_GRADED", None)], None, id="all-not-graded-suite-has-no-score"), + pytest.param([("NOT_GRADED", None), ("ERROR", None)], None, id="execute-suite-with-a-crash-has-no-score"), + ], + ) + def test_average_weighted_score_zeroes_unscored_rows_and_drops_ungraded( + self, tmp_path: Path, statuses_and_scores: list[tuple[str, float | None]], expected: float | None + ) -> None: + rows = [ + _make_row(suite_id="s", row_id=f"r{i}", final_status=FinalStatus(status), weighted_score=score, criteria=[]) + for i, (status, score) in enumerate(statuses_and_scores) + ] + rollup = _compute_suite_rollup("s", "v1", rows, tmp_path) + assert rollup.average_weighted_score == (pytest.approx(expected) if expected is not None else None) + def test_informational_criterion_is_not_a_failure_reason(self, tmp_path: Path) -> None: """A weight-0 criterion cannot fail a row, so it must not explain one. @@ -461,18 +485,26 @@ def test_renders_when_relpath_not_under_variant(self, tmp_path: Path) -> None: assert "[task.json]" in md assert "/abs/path/s/r1/00/task.json" in md + def test_shows_a_zero_avg_score_for_an_all_errored_suite(self, tmp_path: Path) -> None: + rows = [ + _make_row(suite_id="s", row_id=f"r{i}", final_status=FinalStatus.ERROR, weighted_score=None, criteria=[]) + for i in range(2) + ] + rollup = _compute_suite_rollup("s", "v1", rows, tmp_path) + assert "**Average weighted score**: 0.000" in _render_suite_markdown(rollup) + def test_omits_avg_score_when_none(self, tmp_path: Path) -> None: rows = [ _make_row( suite_id="s", row_id="r1", - final_status=FinalStatus.ERROR, + final_status=FinalStatus.NOT_GRADED, weighted_score=None, criteria=[], - error_message="boom", ), ] rollup = _compute_suite_rollup("s", "v1", rows, tmp_path) + assert rollup.average_weighted_score is None md = _render_suite_markdown(rollup) assert "Average weighted score" not in md diff --git a/tests/test_ungraded_reporting.py b/tests/test_ungraded_reporting.py index 315785c5..b737416f 100644 --- a/tests/test_ungraded_reporting.py +++ b/tests/test_ungraded_reporting.py @@ -113,11 +113,8 @@ def test_the_three_published_pass_rates_agree_on_one_set_of_counts() -> None: def test_run_md_and_the_variant_average_publish_one_mean_for_one_set_of_rows() -> None: - """run.md showed 1.000 and experiment.md 0.500 for the same rows when each - surface kept its own copy of the averaging rule. Both now read - `measured_scores`; this pins that they agree on every status that matters.""" - from coder_eval.reports import ReportGenerator - + """run.md, suite.json and experiment.json each kept a copy of the averaging rule and + published different means for the same rows. One rule now feeds all three.""" rows: list[tuple[FinalStatus, float | None]] = [ (FinalStatus.SUCCESS, 1.0), (FinalStatus.FAILURE, 0.0), @@ -125,26 +122,63 @@ def test_run_md_and_the_variant_average_publish_one_mean_for_one_set_of_rows() - (FinalStatus.TIMEOUT, None), (FinalStatus.NOT_GRADED, None), ] - variant_rows = [ - VariantResult(variant_id="v", task_id=f"t{i}", weighted_score=score, final_status=status, duration_seconds=1.0) + assert _published_means(rows) == (0.25, 0.25, 0.25) + + +@pytest.mark.xfail( + strict=True, + reason=( + "Known gap: VariantAggregate.average_score does not apply the nothing_was_measured gate yet. " + "See .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them" + ), +) +def test_every_surface_has_no_mean_when_nothing_was_measured() -> None: + rows: list[tuple[FinalStatus, float | None]] = [(FinalStatus.NOT_GRADED, None), (FinalStatus.ERROR, None)] + assert _published_means(rows) == (None, None, None) + + +def _published_means( + rows: list[tuple[FinalStatus, float | None]], +) -> tuple[float | None, float | None, float | None]: + """(run.md's Avg Reliability Score, suite.json's average_weighted_score, the variant mean) for one set of rows.""" + import re + + from coder_eval.models import EvaluationResult, TaskResult + from coder_eval.orchestration.batch import build_run_summary + from coder_eval.reports import ReportGenerator + from coder_eval.reports.markdown import _compute_suite_rollup + + task_rows = [ + TaskResult( + task_id=f"s/r{i}", + variant_id="v", + duration=1.0, + suite_id="s", + row_id=f"r{i}", + result=EvaluationResult( + task_id=f"s/r{i}", + task_description="t", + agent_type="claude-code", + started_at=datetime(2026, 1, 1), + final_status=status, + weighted_score=score, + iteration_count=1, + ), + ) for i, (status, score) in enumerate(rows) ] - summary = _summary( - tasks_run=5, - tasks_succeeded=1, - tasks_failed=2, - tasks_error=1, - tasks_not_graded=1, - tasks_measured=2, - task_results=[ - {"task_id": f"t{i}", "status": status, "weighted_score": score, "duration": 1.0} + summary = build_run_summary("r", task_rows, datetime(2026, 1, 1), datetime(2026, 1, 1)) + run_md = re.search(r"- \*\*Avg Reliability Score\*\*: ([0-9.]+)", ReportGenerator.generate_markdown(summary)) + suite = _compute_suite_rollup("s", "v", task_rows, Path("run")).average_weighted_score + variant = _mean_graded_score( + [ + VariantResult( + variant_id="v", task_id=f"t{i}", weighted_score=score, final_status=status, duration_seconds=1.0 + ) for i, (status, score) in enumerate(rows) - ], + ] ) - - variant_mean = _mean_graded_score(variant_rows) - assert variant_mean == 0.25 - assert f"- **Avg Reliability Score**: {variant_mean:.3f}" in ReportGenerator.generate_markdown(summary) + return (float(run_md.group(1)) if run_md else None), suite, variant def test_category_of_reads_a_serialized_status_and_counts_an_unknown_one_as_error() -> None: