Viewing files at commit 3cd2661fdbe9Commit detailsView latest

Browse files
tests/test_public_output.py 331 lines · 20.9 KB · python
1
from __future__ import annotations
2
3
import contextlib
4
import io
5
import json
6
from pathlib import Path
7
import sys
8
import tempfile
9
import unittest
10
11
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
12
13
import publish_gate
14
from oakbench.public_output import output_evidence_failures, workflow_evidence_failures
15
from oakbench.output_semantics import OUTPUT_ORACLE_VERSION, PATCH_ORACLE_VERSION
16
from oakbench.workflow_oracles import VERSION as WORKFLOW_ORACLE_VERSION
17
18
19
def exact_output():
20
    return {
21
        "information_recall": 1.0, "information_precision": 1.0,
22
        "information_recall_source": "exact_metadata_path_set",
23
        "information_precision_source": "exact_metadata_path_set",
24
        "output_oracle_version": OUTPUT_ORACLE_VERSION,
25
        "pipe_compatible_unified": True, "patch_application_required": True,
26
        "patch_apply_ok": True, "patch_tree_matches": True, "patch_apply_returncode": 0,
27
        "patch_oracle_version": PATCH_ORACLE_VERSION,
28
        "patch_apply_source": "git_apply_exact_tree",
29
        "patch_instrument_sha256": "a" * 64,
30
        "patch_instrument_version": "git version 2.50.1",
31
    }
32
33
34
class PublicOutputTest(unittest.TestCase):
35
    def test_absent_measurements_are_not_fabricated(self):
36
        self.assertEqual(output_evidence_failures({}), [])
37
        self.assertEqual(output_evidence_failures({"information_recall": None}), [])
38
39
    def test_exact_evidence_accepts_valid_patch_and_measured_low_recall(self):
40
        row = exact_output()
41
        self.assertEqual(output_evidence_failures(row), [])
42
        row["information_recall"] = 0.0
43
        self.assertEqual(output_evidence_failures(row), [])
44
45
    def test_legacy_substrings_and_structural_headers_are_not_proof(self):
46
        for change in (
47
            {"information_recall_source": "ground_truth_path_substring_match"},
48
            {"information_precision_source": "path_token_precision_against_changed_paths"},
49
            {"output_oracle_version": None},
50
            {"patch_apply_ok": None}, {"patch_tree_matches": False},
51
            {"patch_apply_returncode": 1}, {"patch_apply_returncode": False},
52
            {"patch_oracle_version": None}, {"patch_apply_source": "header_regex"},
53
            {"patch_skip_reason": "pristine_tree_over_cap"},
54
            {"patch_failure_reason": "patch_result_tree_mismatch"},
55
            {"information_recall": float("nan")}, {"information_precision": 1.1},
56
            {"information_recall": True}, {"patch_instrument_sha256": None},
57
            {"patch_instrument_version": ""},
58
            {"probe_output_truncated": True}, {"output_truncated": True},
59
        ):
60
            with self.subTest(change=change):
61
                self.assertTrue(output_evidence_failures({**exact_output(), **change}))
62
63
    def test_dirty_structure_is_diagnostic_not_patch_applicability(self):
64
        row = {key: value for key, value in exact_output().items() if not key.startswith("patch_")}
65
        row["operation"] = "diff.dirty.inforecall"
66
        self.assertEqual(output_evidence_failures(row), [])
67
        row["patch_application_required"] = True
68
        self.assertTrue(output_evidence_failures(row))
69
70
    def test_known_partial_exact_metrics_cannot_publish(self):
71
        for flag in ("output_truncated", "probe_output_truncated"):
72
            for metric in ("information_recall", "information_precision"):
73
                row = {metric: 1.0, metric + "_source": "exact_metadata_path_set",
74
                       "output_oracle_version": OUTPUT_ORACLE_VERSION, flag: True}
75
                self.assertTrue(output_evidence_failures(row))
76
                row[metric] = None
77
                self.assertEqual(output_evidence_failures(row), [])
78
79
    def test_malformed_flags_cannot_bypass_evidence_checks(self):
80
        for flag in ("pipe_compatible_unified", "patch_apply_ok", "patch_tree_matches"):
81
            self.assertEqual(output_evidence_failures({flag: None}), [])
82
            for value in (1, 0, "true", [], {}):
83
                with self.subTest(flag=flag, value=value):
84
                    self.assertTrue(output_evidence_failures({flag: value}))
85
86
    def test_real_bugfix_summary_failures_block_publication(self):
87
        import workflow_ab
88
        subject = workflow_ab.Subject("oak", "oak", "Oak", Path("/oak"))
89
        workflow = workflow_ab.WORKFLOWS["bugfix_test_loop"]
90
        metadata = {"bench_id": "gate", "profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
91
        for passed, reason in ((True, None), (False, "wrong_result"), (None, "missing_instrument")):
92
            summary = workflow_ab.sum_rows([], metadata, subject, workflow, 0, "workflow", "workflow.total", {
93
                "workflow_integrity_passed": passed, "workflow_integrity_failure_reason": reason if passed is False else None,
94
                "workflow_integrity_unmeasured_reason": reason if passed is None else None})
95
            with tempfile.TemporaryDirectory() as tmp:
96
                path = Path(tmp) / "rows.jsonl"
97
                path.write_text(json.dumps(summary)+"\n")
98
                with contextlib.redirect_stdout(io.StringIO()):
99
                    code = publish_gate.main([str(path)])
100
                self.assertEqual(code, 1)  # An unqualified singleton is never a public study.
101
102
    def test_real_bugfix_payload_oracle_failure_blocks_pair(self):
103
        import workflow_ab
104
        with tempfile.TemporaryDirectory() as tmp:
105
            root = Path(tmp)
106
            repo = root / "repo"
107
            workflow_ab.make_bugfix_fixture(repo)
108
            workflow = workflow_ab.WORKFLOWS["bugfix_test_loop"]
109
            subject = workflow_ab.Subject("oak", "oak", "Oak", Path("/oak"))
110
            metadata = {"bench_id": "producer", "profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
111
            for repaired in (False, True):
112
                if repaired:
113
                    pricing = repo / "app/pricing.py"
114
                    pricing.write_text(pricing.read_text().replace("return cents - percent", "return cents - ((cents * percent) // 100)"))
115
                fields = workflow_ab.workflow_integrity_fields(subject, workflow, repo, [])
116
                actual = workflow_ab.sum_rows([], metadata, subject, workflow, 0, "workflow", "workflow.total", fields)
117
                peer = {**actual, "subject": "git", "returncode": 0, "workflow_integrity_passed": True}
118
                path = root / "rows.jsonl"
119
                path.write_text("\n".join(map(json.dumps, [actual, peer])))
120
                with contextlib.redirect_stdout(io.StringIO()): code = publish_gate.main([str(path)])
121
                self.assertEqual(code, 1)  # Repairing worktree alone supplies neither HEAD proof nor study qualification.
122
123
    def test_real_load_tier_skip_cannot_remove_trusted_subject(self):
124
        import workflow_ab
125
        workflow = workflow_ab.WORKFLOWS["wide_config_refactor"]
126
        subject = workflow_ab.Subject("oak_local", "oak", "Oak", Path("/oak"))
127
        metadata = {"profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
128
        skipped = workflow_ab.load_tier_skip_rows([subject], [workflow], 1, metadata, "load unavailable", "busy")[0]
129
        passing = {**metadata, "subject": "git", "scenario": workflow.name,
130
                   "operation": "workflow.total", "returncode": 0, "workflow_integrity_passed": True}
131
        failures = workflow_evidence_failures([passing, skipped])
132
        self.assertTrue(any("oak_local" in failure for failure in failures))
133
        self.assertTrue(any("independent committed-tree" in failure for failure in failures))
134
        with tempfile.TemporaryDirectory() as tmp:
135
            path = Path(tmp) / "rows.jsonl"
136
            path.write_text("\n".join(map(json.dumps, [passing, skipped])))
137
            with contextlib.redirect_stdout(io.StringIO()):
138
                self.assertEqual(publish_gate.main([str(path)]), 1)
139
140
    def test_real_measured_agent_failure_remains_publishable(self):
141
        import agent_workflow as aw
142
        import workflow_ab
143
        from types import SimpleNamespace
144
        with tempfile.TemporaryDirectory() as tmp:
145
            root = Path(tmp)
146
            stdout, stderr, prompt = [root / name for name in ("stdout", "stderr", "prompt")]
147
            for path in (stdout, stderr, prompt): path.write_text("")
148
            rows = []
149
            for run, passed in enumerate((True, True, False)):
150
                oracle = SimpleNamespace(elapsed_ms=1, vcs_ms=1, test_ms=1, success=passed,
151
                    checks={"required_checks_passed": passed, "final_vcs_clean": True},
152
                    failure_reason=None if passed else "required_checks_passed", changed_files=[],
153
                    test_returncode=0 if passed else 1, test_output_bytes=0, dirty_files_at_end=0,
154
                    commit_delta=1, bytes_written=0, artifact_paths=[])
155
                oracle.evidence = {"oracle_version": WORKFLOW_ORACLE_VERSION,
156
                    "workflow_integrity_passed": passed, "workflow_integrity_failure_reason": None if passed else "required_checks_passed",
157
                    "workflow_integrity_source": "trusted_task_worktree;independent_git_reader",
158
                    "workflow_integrity_evidence_class": "independent_committed_payload" if passed else "worktree_payload",
159
                    "workflow_integrity_unmeasured_reason": None,
160
                    "git_head_instrument_sha256": "a" * 64, "workflow_subject_binary_sha256": "b" * 64}
161
                rows.append(aw.make_row("gate", "2026-09-11T00:00:00Z", "test",
162
                    aw.AgentConfig("synthetic", "codex_exec_json", "test", Path(sys.executable), "test", "test"),
163
                    workflow_ab.Subject("git", "git", "Git", Path("/git")),
164
                    workflow_ab.WORKFLOWS["bugfix_test_loop"], "agent-default", run, root, root,
165
                    0, 0, aw.AgentExecution(0, False, 1, stdout, stderr, prompt), oracle,
166
                    "task", {}, {}, {}, "minimal", "full-docs"))
167
            self.assertEqual(rows[-1]["outcome"], "fail")
168
            self.assertIs(rows[-1]["workflow_integrity_passed"], False)
169
            self.assertEqual(workflow_evidence_failures(rows), [])
170
            path = root / "rows.jsonl"
171
            path.write_text("\n".join(map(json.dumps, rows)))
172
            with contextlib.redirect_stdout(io.StringIO()):
173
                self.assertEqual(publish_gate.main([str(path)]), 1)  # n<30 and randomization unset remain unqualified.
174
            for change in ({"workflow_integrity_passed": None}, {"workflow_integrity_passed": 0},
175
                           {"outcome": "unknown"}, {"returncode": "77"}, {"skipped": True}):
176
                self.assertTrue(workflow_evidence_failures([{**rows[-1], **change}]), change)
177
178
    def test_trusted_pre_head_agent_failure_is_measured_not_persisted_success(self):
179
        import agent_workflow as aw
180
        import workflow_ab
181
        from oakbench.workflow_oracles import task_evidence
182
        from types import SimpleNamespace
183
        with tempfile.TemporaryDirectory() as tmp:
184
            root = Path(tmp)
185
            repo = root / "repo"
186
            workflow_ab.make_wide_config_fixture(repo)
187
            evidence = task_evidence("wide_config_refactor", repo, "git", "/git")
188
            self.assertIs(evidence["workflow_integrity_passed"], False)
189
            self.assertEqual(evidence["workflow_integrity_evidence_class"], "worktree_payload")
190
            stdout, stderr, prompt = [root / name for name in ("stdout", "stderr", "prompt")]
191
            for path in (stdout, stderr, prompt): path.write_text("")
192
            oracle = SimpleNamespace(elapsed_ms=1, vcs_ms=1, test_ms=1, success=False,
193
                checks={"required_checks_passed": False}, failure_reason=evidence["workflow_integrity_failure_reason"],
194
                changed_files=[], test_returncode=1, test_output_bytes=0, dirty_files_at_end=0,
195
                commit_delta=0, bytes_written=0, artifact_paths=[], evidence=evidence)
196
            rows = [aw.make_row("gate", "2026-09-11T00:00:00Z", "test",
197
                aw.AgentConfig("synthetic", "codex_exec_json", "test", Path(sys.executable), "test", "test"),
198
                workflow_ab.Subject(name, kind, name, Path("/" + kind)),
199
                workflow_ab.WORKFLOWS["wide_config_refactor"], "agent-default", 0, repo, root,
200
                0, 0, aw.AgentExecution(0, False, 1, stdout, stderr, prompt), oracle,
201
                "task", {}, {"oak_hash": "reviewed", "oak_status": "clean"}, {}, "minimal", "full-docs")
202
                for name, kind in (("git", "git"), ("oak", "oak"))]
203
            self.assertEqual(workflow_evidence_failures(rows), [])
204
            path = root / "rows.jsonl"
205
            path.write_text("\n".join(map(json.dumps, rows)))
206
            with contextlib.redirect_stdout(io.StringIO()):
207
                self.assertEqual(publish_gate.main([str(path)]), 1)  # n<30 and randomization unset remain unqualified.
208
            for change in ({"oracle_version": "retired"}, {"workflow_integrity_source": None},
209
                           {"workflow_integrity_passed": True}, {"success": True}, {"returncode": 0},
210
                           {"workflow_integrity_evidence_class": "independent_committed_tree"}):
211
                self.assertTrue(workflow_evidence_failures([rows[0], {**rows[1], **change}]), change)
212
213
    def test_cross_subject_workflow_evidence_cannot_hide_asymmetry(self):
214
        rows = [{"subject": subject, "scenario": "wide_config_refactor", "operation": "agent.workflow",
215
                 "workflow_integrity_source": source, "workflow_integrity_passed": True, "returncode": 0,
216
                 "workflow_integrity_evidence_class": evidence_class, "oracle_version": WORKFLOW_ORACLE_VERSION,
217
                 "workflow_subject_binary_sha256": "b" * 64, "git_head_instrument_sha256": "a" * 64}
218
                for subject, source, evidence_class in (("git", "trusted_exact_task_worktree;independent_committed_tree", "independent_committed_tree"),
219
                    ("oak", "trusted_exact_task_worktree;subject_produced_oak_head_export", "subject_produced_committed_tree"))]
220
        self.assertTrue(workflow_evidence_failures(rows))
221
        rows[1]["workflow_integrity_source"] = "another independently validated reader"
222
        rows[1]["workflow_integrity_evidence_class"] = "independent_committed_tree"
223
        self.assertEqual(workflow_evidence_failures(rows), [])
224
        rows[1]["workflow_integrity_passed"] = None
225
        self.assertTrue(workflow_evidence_failures(rows))
226
        rows[1].pop("workflow_integrity_source")
227
        self.assertTrue(workflow_evidence_failures(rows))
228
229
    def test_skipped_workflow_instrument_cannot_disappear_from_public_comparison(self):
230
        rows = [{"subject": subject, "scenario": "wide_config_refactor", "operation": "agent.workflow",
231
                 "workflow_integrity_source": "trusted_exact_task_worktree;independent_committed_tree",
232
                 "workflow_integrity_evidence_class": "independent_committed_tree", "oracle_version": WORKFLOW_ORACLE_VERSION,
233
                 "workflow_integrity_passed": True, "returncode": 0,
234
                 "agent": {"name": "agent", "model": "model", "provider": "provider", "environment": "minimal"}}
235
                for subject in ("git", "oak")]
236
        rows[0].update(returncode=77, skipped=True, skip_reason="git_head_instrument_unavailable",
237
                       workflow_integrity_passed=None)
238
        self.assertTrue(workflow_evidence_failures(rows))
239
        with tempfile.TemporaryDirectory() as temporary:
240
            path = Path(temporary) / "rows.jsonl"
241
            path.write_text("\n".join(json.dumps(row) for row in rows))
242
            output = io.StringIO()
243
            with contextlib.redirect_stdout(output):
244
                self.assertEqual(publish_gate.main([str(path)]), 1)
245
            self.assertIn("FAIL   workflow-evidence", output.getvalue())
246
        rows[1]["agent"] = {**rows[1]["agent"], "model": "different"}
247
        self.assertTrue(workflow_evidence_failures(rows))
248
249
    def test_bugfix_unequal_producer_labels_cannot_publish(self):
250
        rows = [{"subject": subject, "subject_kind": kind, "scenario": "bugfix_test_loop",
251
                 "operation": "workflow.total", "profile": "workflow", "returncode": 0,
252
                 "workflow_integrity_passed": True, "workflow_integrity_source": source,
253
                 "oracle_version": WORKFLOW_ORACLE_VERSION,
254
                 "source": {"oak_hash": "reviewed-revision", "oak_status": "clean"}}
255
                for subject, kind, source in (
256
                    ("git", "git", "worktree_payload_oracle;known_good_git_head_tree"),
257
                    ("oak", "oak", "worktree_payload_oracle;direct_repo_metadata_fingerprint"))]
258
        self.assertTrue(workflow_evidence_failures(rows))
259
        with tempfile.TemporaryDirectory() as temporary:
260
            path = Path(temporary) / "rows.jsonl"
261
            path.write_text("\n".join(json.dumps(row) for row in rows))
262
            output = io.StringIO()
263
            with contextlib.redirect_stdout(output):
264
                code = publish_gate.main([str(path)])
265
            self.assertEqual(code, 1, output.getvalue())
266
            self.assertIn("FAIL   workflow-evidence", output.getvalue())
267
268
    def test_trusted_workflows_require_measured_independent_same_version_evidence(self):
269
        for scenario in ("wide_config_refactor", "large_asset_manifest"):
270
            rows = [{"subject": subject, "scenario": scenario, "operation": "workflow.total",
271
                     "oracle_version": WORKFLOW_ORACLE_VERSION, "workflow_integrity_passed": True, "returncode": 0,
272
                     "workflow_integrity_evidence_class": "independent_committed_tree",
273
                     "workflow_integrity_source": source, "workflow_subject_binary_sha256": "b" * 64, "git_head_instrument_sha256": "a" * 64}
274
                    for subject, source in (("git", "trusted_exact_task_worktree;independent_committed_tree"),
275
                                            ("git_candidate", "trusted_exact_task_worktree;reviewed_external_reader"))]
276
            self.assertEqual(workflow_evidence_failures(rows), [])
277
            for change in ({"git_head_instrument_sha256": "b" * 64}, {"workflow_subject_binary_sha256": None}, {"oracle_version": "other"}, {"oracle_version": None},
278
                           {"workflow_integrity_evidence_class": None},
279
                           {"workflow_integrity_source": "trusted_exact_task_worktree;subject_produced_oak_head_export"},
280
                           {"workflow_integrity_evidence_class": "subject_produced_committed_tree"},
281
                           {"workflow_integrity_passed": None}, {"workflow_integrity_passed": False}):
282
                with self.subTest(scenario=scenario, change=change):
283
                    self.assertTrue(workflow_evidence_failures([rows[0], {**rows[1], **change}]))
284
            rows[1].update(subject="oak", workflow_integrity_source="trusted_exact_task_worktree;subject_produced_oak_head_export",
285
                           workflow_integrity_evidence_class="subject_produced_committed_tree")
286
            with tempfile.TemporaryDirectory() as temporary:
287
                path = Path(temporary) / "rows.jsonl"
288
                path.write_text("\n".join(json.dumps(row) for row in rows))
289
                output = io.StringIO()
290
                with contextlib.redirect_stdout(output):
291
                    self.assertEqual(publish_gate.main([str(path)]), 1)
292
                self.assertIn("FAIL   workflow-evidence", output.getvalue())
293
294
    def test_publication_entrypoint_enforces_evidence(self):
295
        rows = []
296
        for subject in ("git", "git_untracked_cache", "git_fsmonitor"):
297
            rows.append({
298
                "profile": "standard", "subject": subject, "scenario": "tiny_text",
299
                "operation": "diff.full.inforecall", "returncode": 0,
300
                "env_isolation_version": "1", "randomized_subject_order": True,
301
                "subject_order": ["git", "git_untracked_cache", "git_fsmonitor"],
302
                "benchmark_track": "core-equivalent", "bench_id": "gate-test", "run": 0,
303
                **exact_output(),
304
            })
305
        measured = [
306
            {key: value for key, value in row.items() if key not in exact_output()}
307
            for row in rows
308
        ]
309
        rows.extend({**row, "operation": "diff.dirty.inforecall",
310
                     **{key: value for key, value in exact_output().items() if not key.startswith("patch_")}}
311
                    for row in measured)
312
        rows.extend(
313
            {**row, "operation": "status.clean", "run": run}
314
            for row in measured for run in range(30)
315
        )
316
        with tempfile.TemporaryDirectory() as temporary:
317
            path = Path(temporary) / "rows.jsonl"
318
            path.write_text("\n".join(json.dumps(row) for row in rows))
319
            with contextlib.redirect_stdout(io.StringIO()):
320
                self.assertEqual(publish_gate.main([str(path)]), 0)
321
            rows[0]["patch_apply_ok"] = None
322
            rows[0]["patch_skip_reason"] = "git_unavailable"
323
            path.write_text("\n".join(json.dumps(row) for row in rows))
324
            output = io.StringIO()
325
            with contextlib.redirect_stdout(output):
326
                self.assertEqual(publish_gate.main([str(path)]), 1)
327
            self.assertIn("FAIL   output-evidence", output.getvalue())
328
329
330
if __name__ == "__main__":
331
    unittest.main()