Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

tests/test_summary_accuracy.py in oak/benchmarks

tests/test_summary_accuracy.py 222 lines · 11.6 KB · python
1
"""Accuracy fixes from the 2026-11-09 benchmark audit.
2
3
Each test pins one way a summary or row used to report a misleading number:
4
cross-op averages over different op mixes, medians that hid failures,
5
workflow runs that vanished when setup failed, and history answers that
6
were never checked.
7
"""
8
9
from __future__ import annotations
10
11
import sys
12
import tempfile
13
import unittest
14
from pathlib import Path
15
16
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
17
18
import bench  # noqa: E402
19
import workflow_ab  # noqa: E402
20
from oakbench.subjects import Subject  # noqa: E402
21
22
GIT = Subject(name="git", kind="git", label="git", bin=Path("/usr/bin/git"))
23
OAK = Subject(name="oak_installed", kind="oak", label="oak", bin=Path("oak"))
24
OAK_MAIN = Subject(name="oak_main", kind="oak", label="oak main", bin=Path("oak"))
25
26
27
def core_row(subject: str, op: str, ms: float, returncode: int = 0, scenario: str = "tiny_text", **extra):
28
    return {"subject": subject, "scenario": scenario, "operation": op, "elapsed_ms": ms,
29
            "returncode": returncode, "estimated_tokens_total": ms * 10, **extra}
30
31
32
class SubjectAveragesCompareSameOpMixTest(unittest.TestCase):
33
    def test_oak_only_probe_rows_do_not_enter_the_average(self) -> None:
34
        rows = [
35
            core_row("git", "status.dirty", 10.0),
36
            core_row("oak_installed", "status.dirty", 10.0),
37
            # Oak-only agent-native JSON probe: no Git counterpart.
38
            core_row("oak_installed", "oak.status.json", 90.0),
39
            core_row("oak_installed", "oak.agent.state.json", 90.0),
40
        ]
41
        averages = bench.average_by_subject(rows, "elapsed_ms")
42
        self.assertEqual(averages, {"git": 10.0, "oak_installed": 10.0})
43
44
    def test_cell_failed_for_one_subject_leaves_the_common_mix(self) -> None:
45
        rows = [
46
            core_row("git", "status.dirty", 10.0),
47
            core_row("git", "diff.dirty", 30.0),
48
            core_row("oak_installed", "status.dirty", 12.0),
49
            core_row("oak_installed", "diff.dirty", 5.0, returncode=1),
50
        ]
51
        averages = bench.average_by_subject(rows, "elapsed_ms")
52
        self.assertEqual(averages, {"git": 10.0, "oak_installed": 12.0})
53
54
55
class OperationMediansShowFailuresTest(unittest.TestCase):
56
    def test_counts_exclude_skips_and_count_failures(self) -> None:
57
        rows = [
58
            core_row("oak_installed", "status.dirty", 10.0),
59
            core_row("oak_installed", "status.dirty", 11.0, returncode=1),
60
            core_row("oak_installed", "status.dirty", 12.0, returncode=1),
61
            core_row("oak_installed", "status.dirty", 0.0, returncode=77, skipped=True),
62
        ]
63
        counts = bench.cell_outcome_counts(rows)
64
        self.assertEqual(counts[("oak_installed", "tiny_text/status.dirty")], (1, 2))
65
66
    def test_summary_prints_counts_and_all_failed_cells(self) -> None:
67
        rows = [
68
            core_row("git", "status.dirty", 10.0),
69
            core_row("oak_installed", "status.dirty", 9.0),
70
            core_row("oak_installed", "status.dirty", 9.0, returncode=1),
71
            core_row("git", "diff.dirty", 20.0),
72
            core_row("oak_installed", "diff.dirty", 5.0, returncode=1),
73
            core_row("oak_installed", "diff.dirty", 5.0, returncode=1),
74
        ]
75
        summary = bench.summary_text(rows, [GIT, OAK])
76
        status_line = next(line for line in summary.splitlines()
77
                           if line.startswith("| `tiny_text/status.dirty` | `oak_installed` |"))
78
        self.assertIn("| 1/1 | 9.0 |", status_line)
79
        diff_line = next(line for line in summary.splitlines()
80
                         if line.startswith("| `tiny_text/diff.dirty` | `oak_installed` |"))
81
        self.assertIn("| 0/2 |", diff_line)
82
83
    def test_oak_main_is_preferred_as_the_oak_baseline(self) -> None:
84
        rows = [
85
            core_row("git", "status.dirty", 10.0),
86
            core_row("oak_installed", "status.dirty", 20.0),
87
            core_row("oak_main", "status.dirty", 10.0),
88
        ]
89
        summary = bench.summary_text(rows, [GIT, OAK, OAK_MAIN])
90
        installed_line = next(line for line in summary.splitlines()
91
                              if line.startswith("| `tiny_text/status.dirty` | `oak_installed` |"))
92
        # vs Oak time is relative to oak_main (10 ms): 20 ms is 100% worse.
93
        self.assertIn("-100.0%", installed_line)
94
95
96
class WorkflowRunAccountingTest(unittest.TestCase):
97
    def test_setup_failure_counts_as_a_failed_run(self) -> None:
98
        rows = [
99
            {"subject": "oak_installed", "workflow": "w", "run": 0, "operation": "setup.total", "returncode": 0},
100
            {"subject": "oak_installed", "workflow": "w", "run": 0, "operation": "workflow.total", "returncode": 0},
101
            # Run 1: setup failed, so no workflow.total row exists.
102
            {"subject": "oak_installed", "workflow": "w", "run": 1, "operation": "setup.total", "returncode": 1},
103
            # Run 2: completed, integrity unmeasured.
104
            {"subject": "oak_installed", "workflow": "w", "run": 2, "operation": "setup.total", "returncode": 0},
105
            {"subject": "oak_installed", "workflow": "w", "run": 2, "operation": "workflow.total", "returncode": 77},
106
        ]
107
        stats = workflow_ab.workflow_total_stats(rows)[("oak_installed", "w")]
108
        self.assertEqual(stats["runs"], 3)
109
        self.assertEqual(stats["successes"], 1)
110
        self.assertEqual(stats["failures"], 1)
111
        self.assertEqual(stats["unmeasured"], 1)
112
        self.assertAlmostEqual(stats["failure_rate"], 1 / 3)
113
114
    def test_skipped_runs_are_not_attempts(self) -> None:
115
        rows = [{"subject": "oak_installed", "workflow": "w", "run": 0, "operation": "workflow.skipped",
116
                 "returncode": 77}]
117
        stats = workflow_ab.workflow_total_stats(rows)[("oak_installed", "w")]
118
        self.assertEqual((stats["runs"], stats["skipped"], stats["failure_rate"]), (0, 1, 0.0))
119
120
    def test_workflow_summary_uses_medians(self) -> None:
121
        workflow = workflow_ab.WORKFLOWS["bugfix_test_loop"]
122
        rows = [
123
            {"subject": "git", "workflow": workflow.name, "run": i, "operation": "workflow.total",
124
             "returncode": 0, "elapsed_ms": ms, "estimated_tokens_total": 1, "raw_output_bytes": 1,
125
             "tool_call_count": 1}
126
            for i, ms in enumerate([10.0, 11.0, 1000.0])
127
        ]
128
        summary = workflow_ab.summary_text(rows, [GIT], [workflow])
129
        line = next(line for line in summary.splitlines() if line.startswith(f"| `{workflow.name}` | `git` |"))
130
        self.assertIn("| 11.0 |", line)
131
132
133
class HistoryArchaeologyV2AnswersTest(unittest.TestCase):
134
    def run_step(self, step: workflow_ab.Step, admitted: int = 100_000) -> dict:
135
        workflow = workflow_ab.WORKFLOWS["history_archaeology_v2"]
136
        with tempfile.TemporaryDirectory() as tmp:
137
            return workflow_ab.run_step(OAK, workflow, step, Path(tmp), 0, "workflow", {}, admitted)
138
139
    def test_v1_is_kept_and_v2_is_registered(self) -> None:
140
        self.assertIn("history_archaeology", workflow_ab.WORKFLOWS)
141
        self.assertIn("history_archaeology_v2", workflow_ab.WORKFLOWS)
142
143
    def test_v2_uses_native_oak_history_commands(self) -> None:
144
        steps = {step.operation: step for step in workflow_ab.history_archaeology_v2_steps(OAK, "agent-default")}
145
        self.assertEqual(steps["history.file_history"].command[1:], ["log", "--oneline", "-n", "5", "app/pricing.py"])
146
        self.assertEqual(steps["history.pickaxe"].command[1:], ["log", "-S", "surcharge", "--oneline"])
147
        for step in steps.values():
148
            self.assertEqual(step.expected_returncodes, (0,))
149
            self.assertIsNotNone(step.answer_check)
150
151
    def test_correct_answer_passes(self) -> None:
152
        step = workflow_ab.Step("history.pickaxe", "vcs", ["printf", "abc123 one\n"],
153
                                answer_check=workflow_ab._line_count_is(1), answer_description="1 commit")
154
        row = self.run_step(step)
155
        self.assertEqual((row["returncode"], row["answer_correct"]), (0, True))
156
157
    def test_wrong_answer_fails_the_step(self) -> None:
158
        # The v1 failure mode: an unfiltered log exits 0 but answers wrongly.
159
        step = workflow_ab.Step("history.pickaxe", "vcs", ["printf", "a one\nb two\nc three\n"],
160
                                answer_check=workflow_ab._line_count_is(1), answer_description="1 commit")
161
        row = self.run_step(step)
162
        self.assertEqual(row["returncode"], 1)
163
        self.assertIs(row["answer_correct"], False)
164
        self.assertIn("wrong_answer", row["failure_reason"])
165
166
    def test_truncated_output_is_unmeasured_not_wrong(self) -> None:
167
        step = workflow_ab.Step("history.recent", "vcs", ["printf", "x" * 500],
168
                                answer_check=workflow_ab._line_count_is(1), answer_description="1 commit")
169
        row = self.run_step(step, admitted=10)
170
        self.assertIsNone(row["answer_correct"])
171
        self.assertEqual(row["returncode"], 0)
172
173
174
class CampaignTimeExcludesOracleTest(unittest.TestCase):
175
    """The independent reader's verification time must never count as Oak's cost."""
176
177
    def test_agent_time_and_oracle_time_are_separate_metrics(self) -> None:
178
        from oakbench import campaign_report
179
        row = {"wall_clock_metrics": {"setup_ms": 150.0, "agent_active_ms": 9000.0, "test_ms": 74000.0,
180
                                      "total_ms": 83150.0}}
181
        self.assertNotIn("task_total_ms", campaign_report.METRICS)
182
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["setup_and_agent_ms"]), 9150.0)
183
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["oracle_ms"]), 74000.0)
184
185
    def test_missing_component_is_unmeasured_not_zero(self) -> None:
186
        from oakbench import campaign_report
187
        row = {"wall_clock_metrics": {"setup_ms": None, "agent_active_ms": 9000.0}}
188
        self.assertIsNone(campaign_report._metric(row, campaign_report.METRICS["setup_and_agent_ms"]))
189
190
191
class CampaignTokensCountCachedContextTest(unittest.TestCase):
192
    """reported_tokens omits Claude's cached context; context_tokens must not."""
193
194
    def row(self, adapter, **tokens):
195
        base = {"input_tokens_reported": 8, "output_tokens_reported": 481, "reasoning_tokens_reported": None,
196
                "cache_read_tokens_reported": 59196, "cache_write_tokens_reported": 20242,
197
                "total_tokens_reported": 489}
198
        return {"agent": {"adapter": adapter}, "token_metrics": {**base, **tokens}}
199
200
    def test_claude_context_adds_separately_reported_cache(self) -> None:
201
        from oakbench import campaign_report
202
        row = self.row("claude_print_stream_json")
203
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["reported_tokens"]), 489.0)
204
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["output_tokens"]), 481.0)
205
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["context_tokens"]), 8 + 59196 + 20242)
206
207
    def test_codex_cache_reads_are_inside_input_and_not_double_counted(self) -> None:
208
        from oakbench import campaign_report
209
        row = self.row("codex_exec_json", input_tokens_reported=70000, cache_read_tokens_reported=60000,
210
                       cache_write_tokens_reported=0)
211
        self.assertEqual(campaign_report._metric(row, campaign_report.METRICS["context_tokens"]), 70000.0)
212
213
    def test_unknown_adapter_or_missing_cache_field_is_unmeasured(self) -> None:
214
        from oakbench import campaign_report
215
        path = campaign_report.METRICS["context_tokens"]
216
        self.assertIsNone(campaign_report._metric(self.row("mystery_cli"), path))
217
        self.assertIsNone(campaign_report._metric(self.row("claude_print_stream_json",
218
                                                           cache_read_tokens_reported=None), path))
219
220
221
if __name__ == "__main__":
222
    unittest.main()