diff --git a/.claude/notes/orchestration.md b/.claude/notes/orchestration.md index 074e4be3..edfb3412 100644 --- a/.claude/notes/orchestration.md +++ b/.claude/notes/orchestration.md @@ -933,17 +933,29 @@ 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. +`VariantAggregate.average_score` and run.md's Avg Reliability Score both read `measured_mean`. + +The verdict evidence lives on the fold. `_fold_replicates` sets `VariantResult.measured` when +any replicate carries a verdict, because its score turns an errored replicate into 0.0 and +so cannot answer "was this measured". A variant where `nothing_was_measured` holds also loses +its per-task scores, so the fold's 0.0 for a crash cannot win a task, set a spread or feed +the replicate statistics. An `execute` run with a crash therefore has no `pass_rate` or +`average_score` in experiment.json and wins no task, as run.json has no `pass_rate` and run.md +shows no Avg Reliability Score. A graded run is unchanged: its errored rows still score 0.0 +and can still lose. + +Known gaps. Closing either changes a serialized value that downstream consumers read, so +each 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`. +- A task whose replicates are a crash plus ungraded runs folds to ERROR (`_pick_worst_status` + ranks ungraded last). A variant made only of such tasks has no ungraded task, so + `nothing_was_measured` cannot hold and experiment.json shows 0.0 where run.json shows no + rate. Pinned by the strict xfail + `tests/test_ungraded_reporting.py::test_a_variant_of_only_crashed_and_ungraded_replicates_has_no_rate_or_score`. 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 @@ -952,10 +964,10 @@ happened to list first, so swapping the inputs flipped the reported winner while `is_tie=False` asserted it was a real result. It now sorts by `variant_id` for determinism and marks a tie among all arms, which is what "no arm outscored another" means. -`tasks_measured` counts rows with a score, because a TIMEOUT lands in the `failed` bucket -without any criterion having run — so the buckets alone cannot answer "was this measured -at all". `average_score` is `None` rather than `0.000` when nothing was graded, since a -zero beside "Pass Rate: n/a" is indistinguishable from "scored zero". +`tasks_measured` counts evidence, not buckets, because a TIMEOUT lands in the `failed` +bucket without any criterion having run, so the buckets alone cannot answer "was this +measured at all". run.json counts replicate rows with a score; experiment.json counts tasks +with a measured replicate. Only the gate they feed is shared. The status-priority map is annotated with the SAME `Literal` that `FinalStatus.category` returns and indexed directly rather than via `.get(..., -1)`. Adding the fourth `ungraded` diff --git a/docs/REPORT_SCHEMA.md b/docs/REPORT_SCHEMA.md index c1e11220..d5b9664e 100644 --- a/docs/REPORT_SCHEMA.md +++ b/docs/REPORT_SCHEMA.md @@ -46,7 +46,7 @@ run-level summary; full per-replicate detail lives in each `task.json`. | `total_duration_seconds` | `float` | Wall-clock. | | `tasks_run` | `int` | Total replicates executed. | | `tasks_succeeded` / `tasks_failed` / `tasks_error` | `int` | Category counts. **Invariant:** these three plus `tasks_not_graded` sum to `tasks_run`. | -| `tasks_measured` | `int` | Rows carrying a criteria verdict (`weighted_score is not None`). NOT a bucket and not part of the task-count invariant: it is the evidence that gates `pass_rate` / `error_share`, because the four category buckets cannot tell a graded `FAILURE` from a `TIMEOUT` no criterion ever saw. Defaults to `0`, inert on pre-`execute` `run.json` (where `tasks_not_graded` is `0`). | +| `tasks_measured` | `int` | Replicate rows carrying a criteria verdict (`weighted_score is not None`); `variant.json` counts tasks instead. NOT a bucket and not part of the task-count invariant: it is the evidence that gates `pass_rate` / `error_share`, because the four category buckets cannot tell a graded `FAILURE` from a `TIMEOUT` no criterion ever saw. Defaults to `0`, inert on pre-`execute` `run.json` (where `tasks_not_graded` is `0`). | | `tasks_not_graded` | `int` | Tasks run by `coder-eval execute` — executed, deliberately unscored. Excluded from **both** sides of `pass_rate`. Defaults to `0`, so pre-`execute` `run.json` still parses. | | `tasks_token_budget_exceeded` / `tasks_cost_budget_exceeded` | `int` | Sub-counters of `tasks_failed` (not part of the invariant). | | `skipped_tasks` | `list[{path, reason}]` | Load failures / `skip: true` opt-outs. | @@ -291,10 +291,14 @@ the same weighted armed gate as a native fail), A single aggregate (not wrapped): `variant_id`, `tasks_run`, `tasks_succeeded`, `tasks_failed`, `tasks_error`, `tasks_not_graded` (same sum-to-`tasks_run` invariant), -`average_score` (`float | None` — the mean over **measured** rows: an errored row counts -as `0.0`, an ungraded one leaves both sides; `null` when nothing was measured), -`average_duration`, `total_tokens`, `replicate_count`, `tasks_token_budget_exceeded`, -`tasks_cost_budget_exceeded`. +`tasks_graded` (`tasks_run - tasks_not_graded`), `tasks_measured` (tasks with at least one +replicate that carries a criteria verdict, from `VariantResult.measured`; an errored +replicate's `0.0` is not a verdict), `pass_rate` (`tasks_succeeded / tasks_graded`; `null` +when `tasks_graded` is `0` or `nothing_was_measured` holds), `average_score` +(`float | None` — the mean over **measured** rows: an errored row counts as `0.0`, an +ungraded one leaves both sides; `null` when no row counts or `nothing_was_measured` holds, +the same gate as `pass_rate`), `average_duration`, `total_tokens`, `replicate_count`, +`tasks_token_budget_exceeded`, `tasks_cost_budget_exceeded`. ## `experiment.json` — `ExperimentResult` @@ -303,17 +307,21 @@ The cross-variant summary: - `experiment_id`, `description`, `variant_ids`. - `task_summaries: list[TaskExperimentSummary]` — each `{task_id, variant_results, best_variant, is_tie, score_spread, replicate_count}`, - where each `VariantResult` carries `{variant_id, task_id, weighted_score, + where each `VariantResult` carries `{variant_id, task_id, weighted_score, measured, final_status, duration_seconds, total_tokens, iteration_count, total_assistant_turns, reference_similarity, replicate_index, replicate_count}`. - `weighted_score` is `float | None`: `null` only when every replicate was - **ungraded**. An **errored** replicate counts as `0.0` — same rule as - `VariantAggregate.average_score` above. That is deliberate: dropping errored + `weighted_score` is `float | None`: `null` when every replicate was **ungraded**, + and for every task of a variant where `nothing_was_measured` holds (an `execute` + run with a crash). Otherwise an **errored** replicate counts as `0.0`, the same rule + as `VariantAggregate.average_score` above. That is deliberate: dropping errored rows would let a nightly where one image build failed report a *higher* - headline score than a clean one. + headline score than a clean one. `measured` is `true` when at least one replicate + carries a criteria verdict. Only a non-`null` `weighted_score` can be + `best_variant` or count toward `score_spread`; a task with none is a tie. - `variant_aggregates: dict[str, VariantAggregate]` — keyed by variant id. - `total_duration_seconds`. -- `per_replicate_scores: dict[variant_id -> dict[task_id -> list[float]]]`. +- `per_replicate_scores: dict[variant_id -> dict[task_id -> list[float]]]` — empty lists for a + variant where `nothing_was_measured` holds. > **Statistics are render-time only.** Bootstrap/Wilson confidence intervals and the > Welch/paired mean-difference tests appear in `experiment.md` / HTML but are **not** diff --git a/src/coder_eval/models/experiment.py b/src/coder_eval/models/experiment.py index ece7d444..5526a858 100644 --- a/src/coder_eval/models/experiment.py +++ b/src/coder_eval/models/experiment.py @@ -193,6 +193,13 @@ class VariantResult(BaseModel): # noqa: CE009 -- persisted result model; round- # None when nothing was graded. A plain float would launder that into 0.000. # Rationale: .claude/notes/orchestration.md § Rates need verdict evidence, not bucket counts weighted_score: float | None = None + measured: bool = Field( + default_factory=lambda data: data.get("weighted_score") is not None, + description=( + "At least one replicate carries a criteria verdict. An errored replicate's 0.0 is not one. " + "Defaults to `weighted_score is not None`." + ), + ) final_status: FinalStatus duration_seconds: float total_tokens: int | None = None @@ -232,9 +239,13 @@ class VariantAggregate(BaseModel): # noqa: CE009 -- persisted result model; rou ge=0, description="Tasks executed without grading (`coder-eval execute`). Excluded from pass_rate entirely.", ) - # None when nothing in this variant was graded: a 0.0 is indistinguishable from - # "measured and scored zero". - average_score: float | None + average_score: float | None = Field( + description=( + "Mean over measured rows: an errored row counts as 0.0, an ungraded one leaves. None when no " + "row counts, or when nothing_was_measured holds (aggregate_results applies it through " + "result_metrics.measured_mean)." + ), + ) average_duration: float total_tokens: int | None = None replicate_count: int = Field( @@ -258,7 +269,10 @@ class VariantAggregate(BaseModel): # noqa: CE009 -- persisted result model; rou tasks_measured: int = Field( default=0, ge=0, - description="Rows carrying a criteria verdict (weighted_score is not None). Gates pass_rate.", + description=( + "Tasks with at least one replicate carrying a criteria verdict (VariantResult.measured). " + "Gates pass_rate here, and average_score in aggregate_results." + ), ) @model_validator(mode="after") diff --git a/src/coder_eval/models/results.py b/src/coder_eval/models/results.py index c8c1a893..952501ef 100644 --- a/src/coder_eval/models/results.py +++ b/src/coder_eval/models/results.py @@ -1175,14 +1175,14 @@ class RunSummary(BaseModel): ), ) - # Verdict evidence, NOT a bucket and NOT part of the invariant. Symmetric with - # VariantAggregate.tasks_measured so the three published rates read one input. + # Verdict evidence, NOT a bucket and NOT part of the invariant. The same gate input as + # VariantAggregate.tasks_measured, in a different unit: replicate rows here, tasks there. # Rationale: .claude/notes/orchestration.md § Rates need verdict evidence, not bucket counts tasks_measured: int = Field( default=0, ge=0, description=( - "Rows carrying a criteria verdict (weighted_score is not None). " + "Replicate rows carrying a criteria verdict (weighted_score is not None). " "Gates pass_rate / error_share: nothing measured means no rate, not a 0% one." ), ) diff --git a/src/coder_eval/orchestration/experiment.py b/src/coder_eval/orchestration/experiment.py index f93b84d2..e8892210 100644 --- a/src/coder_eval/orchestration/experiment.py +++ b/src/coder_eval/orchestration/experiment.py @@ -37,9 +37,10 @@ VariantAggregate, VariantResult, apply_prompt_mutations, + nothing_was_measured, ) from ..path_utils import resolve_dir_template -from ..result_metrics import measured_scores +from ..result_metrics import measured_mean, measured_scores from .config import BatchRunConfig from .config_merge import ConfigSource, Layer, merge_layers, resolve_root from .task_loader import ( @@ -804,10 +805,32 @@ def _measured_scores(rows: Sequence[VariantResult] | Sequence[TaskResult]) -> li return measured_scores((r.final_status, r.weighted_score) for r in results) -def _mean_graded_score(vr_list: list[VariantResult]) -> float | None: - """Mean score over the measured rows; ``None`` when none were measured.""" - scores = _measured_scores(vr_list) - return sum(scores) / len(scores) if scores else None +def _verdict_evidence(vr_list: Sequence[VariantResult]) -> tuple[int, int]: + """``(not_graded, measured)`` task counts, the two inputs of ``nothing_was_measured``.""" + return ( + sum(1 for v in vr_list if v.final_status.category == "ungraded"), + sum(1 for v in vr_list if v.measured), + ) + + +def _mean_graded_score(vr_list: Sequence[VariantResult]) -> float | None: + """The variant's headline mean: measured rows only, ``None`` when the variant has no verdict.""" + not_graded, measured = _verdict_evidence(vr_list) + return measured_mean( + ((v.final_status, v.weighted_score) for v in vr_list), not_graded=not_graded, measured=measured + ) + + +def _has_no_verdict(vr_list: Sequence[VariantResult]) -> bool: + not_graded, measured = _verdict_evidence(vr_list) + return nothing_was_measured(not_graded=not_graded, measured=measured) + + +def _variants_without_a_verdict(folded: list[VariantResult]) -> set[str]: + by_variant: dict[str, list[VariantResult]] = {} + for vr in folded: + by_variant.setdefault(vr.variant_id, []).append(vr) + return {vid for vid, vr_list in by_variant.items() if _has_no_verdict(vr_list)} def _mean_reference_similarity(reps: list[TaskResult]) -> float | None: @@ -840,6 +863,7 @@ def _fold_replicates(task_id: str, variant_id: str, reps: list[TaskResult]) -> V variant_id=variant_id, task_id=task_id, weighted_score=sum(scores) / len(scores) if scores else None, + measured=any(r.result.weighted_score is not None for r in reps), final_status=_pick_worst_status([r.result.final_status for r in reps]), duration_seconds=sum(durations), total_tokens=sum(token_vals) if token_vals else None, @@ -851,6 +875,63 @@ def _fold_replicates(task_id: str, variant_id: str, reps: list[TaskResult]) -> V ) +def _summarize_task(task_id: str, variants: list[VariantResult]) -> TaskExperimentSummary: + """Pick one task's winner and spread from its folded per-variant results.""" + # Only GRADED variants can win or set a spread, and when nothing was + # scored the fallback must not invent a winner. + # Rationale: .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them + scored = [(v, v.weighted_score) for v in variants if v.weighted_score is not None] + if scored: + best = max(scored, key=lambda pair: (pair[1], pair[0].variant_id))[0] + top_count = sum(1 for _, s in scored if s == best.weighted_score) + else: + best = min(variants, key=lambda v: v.variant_id) + top_count = len(variants) + scores = [s for _, s in scored] + rep_counts = {v.replicate_count for v in variants} + return TaskExperimentSummary( + task_id=task_id, + variant_results=variants, + best_variant=best.variant_id, + is_tie=top_count > 1, + score_spread=(max(scores) - min(scores)) if scores else 0.0, + replicate_count=min(rep_counts) if rep_counts else 1, + ) + + +def _aggregate_variant(vid: str, vr_list: list[VariantResult]) -> VariantAggregate: + """Roll one variant's folded per-task results into its VariantAggregate.""" + if not vr_list: + return VariantAggregate( + variant_id=vid, + tasks_run=0, + tasks_succeeded=0, + tasks_failed=0, + tasks_error=0, + average_score=None, + average_duration=0.0, + ) + token_values = [v.total_tokens for v in vr_list if v.total_tokens is not None] + tasks_not_graded, tasks_measured = _verdict_evidence(vr_list) + return VariantAggregate( + variant_id=vid, + tasks_run=len(vr_list), + tasks_succeeded=sum(1 for v in vr_list if v.final_status.category == "succeeded"), + tasks_failed=sum(1 for v in vr_list if v.final_status.category == "failed"), + tasks_error=sum(1 for v in vr_list if v.final_status.category == "error"), + tasks_not_graded=tasks_not_graded, + tasks_token_budget_exceeded=sum(1 for v in vr_list if v.final_status == FinalStatus.TOKEN_BUDGET_EXCEEDED), + tasks_cost_budget_exceeded=sum(1 for v in vr_list if v.final_status == FinalStatus.COST_BUDGET_EXCEEDED), + # Verdict evidence: a TIMEOUT lands in `failed` with no criterion + # having run, so the buckets alone cannot answer this. + tasks_measured=tasks_measured, + average_score=_mean_graded_score(vr_list), + average_duration=sum(v.duration_seconds / v.replicate_count for v in vr_list) / len(vr_list), + total_tokens=sum(token_values) if token_values else None, + replicate_count=vr_list[0].replicate_count, + ) + + def aggregate_results( experiment_id: str, description: str, @@ -880,77 +961,28 @@ def aggregate_results( for tr in task_results: task_variant_reps.setdefault((tr.task_id, tr.variant_id), []).append(tr) + folded = [_fold_replicates(task_id, variant_id, reps) for (task_id, variant_id), reps in task_variant_reps.items()] + # A variant with no verdict has no per-task score either: the fold's 0.0 for its + # crashed rows must not win a task, set a spread or feed the replicate statistics. + # Rationale: .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them + no_verdict = _variants_without_a_verdict(folded) + folded = [vr.model_copy(update={"weighted_score": None}) if vr.variant_id in no_verdict else vr for vr in folded] + # Collect per-replicate scores keyed variant_id → task_id → [scores] for stats rendering. per_replicate_scores: dict[str, dict[str, list[float]]] = {} for (task_id, variant_id), reps in task_variant_reps.items(): - per_replicate_scores.setdefault(variant_id, {})[task_id] = _measured_scores(reps) + scores = [] if variant_id in no_verdict else _measured_scores(reps) + per_replicate_scores.setdefault(variant_id, {})[task_id] = scores task_variants: dict[str, list[VariantResult]] = {} - for (task_id, variant_id), reps in task_variant_reps.items(): - task_variants.setdefault(task_id, []).append(_fold_replicates(task_id, variant_id, reps)) - - # Build task summaries - task_summaries: list[TaskExperimentSummary] = [] - for task_id, variants in task_variants.items(): - # Only GRADED variants can win or set a spread, and when nothing was - # scored the fallback must not invent a winner. - # Rationale: .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them - scored = [(v, v.weighted_score) for v in variants if v.weighted_score is not None] - if scored: - best = max(scored, key=lambda pair: (pair[1], pair[0].variant_id))[0] - top_count = sum(1 for _, s in scored if s == best.weighted_score) - else: - best = min(variants, key=lambda v: v.variant_id) - top_count = len(variants) - scores = [s for _, s in scored] - rep_counts = {v.replicate_count for v in variants} - task_summaries.append( - TaskExperimentSummary( - task_id=task_id, - variant_results=variants, - best_variant=best.variant_id, - is_tie=top_count > 1, - score_spread=(max(scores) - min(scores)) if scores else 0.0, - replicate_count=min(rep_counts) if rep_counts else 1, - ) - ) - - # Build variant aggregates - variant_aggregates: dict[str, VariantAggregate] = {} - for vid in variant_ids: - vr_list = [vr for ts in task_summaries for vr in ts.variant_results if vr.variant_id == vid] - if not vr_list: - variant_aggregates[vid] = VariantAggregate( - variant_id=vid, - tasks_run=0, - tasks_succeeded=0, - tasks_failed=0, - tasks_error=0, - average_score=None, - average_duration=0.0, - ) - continue + for vr in folded: + task_variants.setdefault(vr.task_id, []).append(vr) + task_summaries = [_summarize_task(task_id, variants) for task_id, variants in task_variants.items()] - token_values = [v.total_tokens for v in vr_list if v.total_tokens is not None] - total_tokens = sum(token_values) if token_values else None - variant_aggregates[vid] = VariantAggregate( - variant_id=vid, - tasks_run=len(vr_list), - tasks_succeeded=sum(1 for v in vr_list if v.final_status.category == "succeeded"), - tasks_failed=sum(1 for v in vr_list if v.final_status.category == "failed"), - tasks_error=sum(1 for v in vr_list if v.final_status.category == "error"), - tasks_not_graded=sum(1 for v in vr_list if v.final_status.category == "ungraded"), - tasks_token_budget_exceeded=sum(1 for v in vr_list if v.final_status == FinalStatus.TOKEN_BUDGET_EXCEEDED), - tasks_cost_budget_exceeded=sum(1 for v in vr_list if v.final_status == FinalStatus.COST_BUDGET_EXCEEDED), - # Verdict evidence: a TIMEOUT lands in `failed` with no criterion - # having run, so the buckets alone cannot answer this. - tasks_measured=sum(1 for v in vr_list if v.weighted_score is not None), - # GRADED rows only, and None when there are none. - average_score=_mean_graded_score(vr_list), - average_duration=sum(v.duration_seconds / v.replicate_count for v in vr_list) / len(vr_list), - total_tokens=total_tokens, - replicate_count=vr_list[0].replicate_count if vr_list else 1, - ) + variant_aggregates = { + vid: _aggregate_variant(vid, [vr for ts in task_summaries for vr in ts.variant_results if vr.variant_id == vid]) + for vid in variant_ids + } return ExperimentResult( experiment_id=experiment_id, diff --git a/src/coder_eval/reports/markdown.py b/src/coder_eval/reports/markdown.py index c2d6fbfc..685b16ba 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, 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_ungraded_reporting.py b/tests/test_ungraded_reporting.py index 315785c5..bdf269df 100644 --- a/tests/test_ungraded_reporting.py +++ b/tests/test_ungraded_reporting.py @@ -20,8 +20,16 @@ import pytest -from coder_eval.models import FinalStatus, RunSummary, VariantAggregate, VariantResult -from coder_eval.orchestration.experiment import _mean_graded_score, _pick_worst_status +from coder_eval.models import ( + EvaluationResult, + FinalStatus, + RunSummary, + TaskResult, + VariantAggregate, + VariantResult, +) +from coder_eval.orchestration.batch import build_run_summary +from coder_eval.orchestration.experiment import _mean_graded_score, _pick_worst_status, aggregate_results def _summary(**kwargs: object) -> RunSummary: @@ -112,6 +120,148 @@ def test_the_three_published_pass_rates_agree_on_one_set_of_counts() -> None: assert aggregate.pass_rate is None +def _task_row( + task_id: str, status: FinalStatus, score: float | None = None, replicate_index: int = 0, variant_id: str = "v" +) -> TaskResult: + result = EvaluationResult( + task_id=task_id, + task_description="t", + variant_id=variant_id, + agent_type="claude-code", + started_at=datetime(2026, 1, 1), + final_status=status, + weighted_score=score, + duration_seconds=1.0, + iteration_count=1, + ) + return TaskResult( + task_id=task_id, variant_id=variant_id, result=result, duration=1.0, replicate_index=replicate_index + ) + + +_NG, _ERR, _OK = FinalStatus.NOT_GRADED, FinalStatus.ERROR, FinalStatus.SUCCESS + + +@pytest.mark.parametrize( + ("rows", "measured", "pass_rate", "average_score"), + [ + pytest.param( + [*(_task_row(f"t{i}", _NG) for i in range(9)), _task_row("t9", _ERR)], + 0, + None, + None, + id="execute-run-with-a-crash-has-no-rate-or-score", + ), + pytest.param( + [_task_row("t0", _ERR), _task_row("t0", _NG, replicate_index=1), _task_row("t1", _NG)], + 0, + None, + None, + id="a-crashed-replicate-is-not-a-verdict", + ), + pytest.param( + [_task_row("t0", _ERR), _task_row("t0", _OK, 1.0, replicate_index=1), _task_row("t1", _NG)], + 1, + 0.0, + 0.5, + id="one-scored-replicate-measures-the-task", + ), + pytest.param( + [_task_row("t0", _ERR), _task_row("t1", _ERR)], + 0, + 0.0, + 0.0, + id="all-error-graded-run-still-scores-zero", + ), + ], +) +def test_variant_aggregate_counts_a_task_measured_only_when_a_replicate_has_a_verdict( + rows: list[TaskResult], measured: int, pass_rate: float | None, average_score: float | None +) -> None: + aggregate = aggregate_results("e", "", ["v"], rows, 1.0).variant_aggregates["v"] + + assert aggregate.tasks_measured == measured + assert aggregate.pass_rate == pass_rate + assert aggregate.average_score == average_score + + +def test_run_json_and_experiment_json_agree_on_an_execute_run_with_a_crash() -> None: + from coder_eval.reports import ReportGenerator + + rows = [*(_task_row(f"t{i}", _NG) for i in range(9)), _task_row("t9", _ERR)] + + summary = build_run_summary("r", rows, datetime(2026, 1, 1), datetime(2026, 1, 1)) + aggregate = aggregate_results("e", "", ["v"], rows, 1.0).variant_aggregates["v"] + + assert (aggregate.tasks_measured, aggregate.pass_rate) == (summary.tasks_measured, summary.pass_rate) == (0, None) + assert aggregate.average_score is None + assert "Avg Reliability Score" not in ReportGenerator.generate_markdown(summary) + + +def test_one_variants_verdict_does_not_measure_another() -> None: + rows = [ + _task_row("t0", _OK, 1.0, variant_id="a"), + _task_row("t0", _ERR, variant_id="b"), + _task_row("t1", _NG, variant_id="b"), + ] + aggregates = aggregate_results("e", "", ["a", "b"], rows, 1.0).variant_aggregates + + assert (aggregates["a"].tasks_measured, aggregates["a"].pass_rate, aggregates["a"].average_score) == (1, 1.0, 1.0) + assert (aggregates["b"].tasks_measured, aggregates["b"].pass_rate, aggregates["b"].average_score) == (0, None, None) + + +def test_a_variant_with_no_verdict_wins_no_task_and_scores_no_cell() -> None: + from coder_eval.reports import ExperimentReportGenerator + + rows = [ + _task_row("t0", _ERR, variant_id="A"), + _task_row("t1", _NG, variant_id="A"), + _task_row("t0", _NG, variant_id="B"), + _task_row("t1", _NG, variant_id="B"), + ] + result = aggregate_results("e", "", ["A", "B"], rows, 1.0) + t0 = next(ts for ts in result.task_summaries if ts.task_id == "t0") + + assert t0.is_tie + assert [vr.weighted_score for vr in t0.variant_results] == [None, None] + assert result.per_replicate_scores["A"]["t0"] == [] + assert "- **A**: 0/2 tasks (0%)" in ExperimentReportGenerator.generate_experiment_report(result) + + +def test_a_graded_variant_that_errors_still_scores_zero_and_can_lose() -> None: + rows = [ + _task_row("t0", _ERR, variant_id="A"), + _task_row("t0", _OK, 0.5, variant_id="B"), + _task_row("t1", _ERR, variant_id="A"), + _task_row("t1", FinalStatus.FAILURE, 0.0, variant_id="B"), + ] + result = aggregate_results("e", "", ["A", "B"], rows, 1.0) + t0, t1 = result.task_summaries + + assert (t0.best_variant, t0.is_tie, t0.score_spread) == ("B", False, 0.5) + assert t1.is_tie + assert result.variant_aggregates["A"].average_score == 0.0 + assert result.per_replicate_scores["A"]["t0"] == [0.0] + + +@pytest.mark.xfail( + strict=True, + reason=( + "Known gap: a task whose replicates are a crash plus ungraded runs folds to ERROR, so the variant " + "has no ungraded task and nothing_was_measured cannot hold. " + "See .claude/notes/orchestration.md § Aggregation drops ungraded rows rather than zeroing them" + ), +) +def test_a_variant_of_only_crashed_and_ungraded_replicates_has_no_rate_or_score() -> None: + rows = [_task_row("t0", _ERR), _task_row("t0", _NG, replicate_index=1)] + + summary = build_run_summary("r", rows, datetime(2026, 1, 1), datetime(2026, 1, 1)) + aggregate = aggregate_results("e", "", ["v"], rows, 1.0).variant_aggregates["v"] + + assert summary.pass_rate is None + assert (aggregate.pass_rate, aggregate.average_score) == (None, 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