Viewing files at commit 2e081b95a118Commit detailsView latest

Browse files
tests/test_public_output.py 316 lines · 19.6 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_malformed_flags_cannot_bypass_evidence_checks(self):
71
        for flag in ("pipe_compatible_unified", "patch_apply_ok", "patch_tree_matches"):
72
            self.assertEqual(output_evidence_failures({flag: None}), [])
73
            for value in (1, 0, "true", [], {}):
74
                with self.subTest(flag=flag, value=value):
75
                    self.assertTrue(output_evidence_failures({flag: value}))
76
77
    def test_real_bugfix_summary_failures_block_publication(self):
78
        import workflow_ab
79
        subject = workflow_ab.Subject("oak", "oak", "Oak", Path("/oak"))
80
        workflow = workflow_ab.WORKFLOWS["bugfix_test_loop"]
81
        metadata = {"bench_id": "gate", "profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
82
        for passed, reason in ((True, None), (False, "wrong_result"), (None, "missing_instrument")):
83
            summary = workflow_ab.sum_rows([], metadata, subject, workflow, 0, "workflow", "workflow.total", {
84
                "workflow_integrity_passed": passed, "workflow_integrity_failure_reason": reason if passed is False else None,
85
                "workflow_integrity_unmeasured_reason": reason if passed is None else None})
86
            with tempfile.TemporaryDirectory() as tmp:
87
                path = Path(tmp) / "rows.jsonl"
88
                path.write_text(json.dumps(summary)+"\n")
89
                with contextlib.redirect_stdout(io.StringIO()):
90
                    code = publish_gate.main([str(path)])
91
                self.assertEqual(code, 0 if passed else 1)
92
93
    def test_real_bugfix_payload_oracle_failure_blocks_pair(self):
94
        import workflow_ab
95
        with tempfile.TemporaryDirectory() as tmp:
96
            root = Path(tmp)
97
            repo = root / "repo"
98
            workflow_ab.make_bugfix_fixture(repo)
99
            workflow = workflow_ab.WORKFLOWS["bugfix_test_loop"]
100
            subject = workflow_ab.Subject("oak", "oak", "Oak", Path("/oak"))
101
            metadata = {"bench_id": "producer", "profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
102
            for repaired in (False, True):
103
                if repaired:
104
                    pricing = repo / "app/pricing.py"
105
                    pricing.write_text(pricing.read_text().replace("return cents - percent", "return cents - ((cents * percent) // 100)"))
106
                fields = workflow_ab.workflow_integrity_fields(subject, workflow, repo, [])
107
                actual = workflow_ab.sum_rows([], metadata, subject, workflow, 0, "workflow", "workflow.total", fields)
108
                peer = {**actual, "subject": "git", "returncode": 0, "workflow_integrity_passed": True}
109
                path = root / "rows.jsonl"
110
                path.write_text("\n".join(map(json.dumps, [actual, peer])))
111
                with contextlib.redirect_stdout(io.StringIO()): code = publish_gate.main([str(path)])
112
                self.assertEqual(code, 0 if repaired else 1)
113
114
    def test_real_load_tier_skip_cannot_remove_trusted_subject(self):
115
        import workflow_ab
116
        workflow = workflow_ab.WORKFLOWS["wide_config_refactor"]
117
        subject = workflow_ab.Subject("oak_local", "oak", "Oak", Path("/oak"))
118
        metadata = {"profile": "workflow", "source": {"oak_hash": "reviewed", "oak_status": "clean"}}
119
        skipped = workflow_ab.load_tier_skip_rows([subject], [workflow], 1, metadata, "load unavailable", "busy")[0]
120
        passing = {**metadata, "subject": "git", "scenario": workflow.name,
121
                   "operation": "workflow.total", "returncode": 0, "workflow_integrity_passed": True}
122
        failures = workflow_evidence_failures([passing, skipped])
123
        self.assertTrue(any("oak_local" in failure for failure in failures))
124
        self.assertTrue(any("independent committed-tree" in failure for failure in failures))
125
        with tempfile.TemporaryDirectory() as tmp:
126
            path = Path(tmp) / "rows.jsonl"
127
            path.write_text("\n".join(map(json.dumps, [passing, skipped])))
128
            with contextlib.redirect_stdout(io.StringIO()):
129
                self.assertEqual(publish_gate.main([str(path)]), 1)
130
131
    def test_real_measured_agent_failure_remains_publishable(self):
132
        import agent_workflow as aw
133
        import workflow_ab
134
        from types import SimpleNamespace
135
        with tempfile.TemporaryDirectory() as tmp:
136
            root = Path(tmp)
137
            stdout, stderr, prompt = [root / name for name in ("stdout", "stderr", "prompt")]
138
            for path in (stdout, stderr, prompt): path.write_text("")
139
            rows = []
140
            for run, passed in enumerate((True, True, False)):
141
                oracle = SimpleNamespace(elapsed_ms=1, vcs_ms=1, test_ms=1, success=passed,
142
                    checks={"required_checks_passed": passed, "final_vcs_clean": True},
143
                    failure_reason=None if passed else "required_checks_passed", changed_files=[],
144
                    test_returncode=0 if passed else 1, test_output_bytes=0, dirty_files_at_end=0,
145
                    commit_delta=1, bytes_written=0, artifact_paths=[])
146
                rows.append(aw.make_row("gate", "2026-09-11T00:00:00Z", "test",
147
                    aw.AgentConfig("synthetic", "codex_exec_json", "test", Path(sys.executable), "test", "test"),
148
                    workflow_ab.Subject("git", "git", "Git", Path("/git")),
149
                    workflow_ab.WORKFLOWS["bugfix_test_loop"], "agent-default", run, root, root,
150
                    0, 0, aw.AgentExecution(0, False, 1, stdout, stderr, prompt), oracle,
151
                    "task", {}, {}, {}, "minimal", "full-docs"))
152
            self.assertEqual(rows[-1]["outcome"], "fail")
153
            self.assertIs(rows[-1]["workflow_integrity_passed"], False)
154
            self.assertEqual(workflow_evidence_failures(rows), [])
155
            path = root / "rows.jsonl"
156
            path.write_text("\n".join(map(json.dumps, rows)))
157
            with contextlib.redirect_stdout(io.StringIO()):
158
                self.assertEqual(publish_gate.main([str(path)]), 0)
159
            for change in ({"workflow_integrity_passed": None}, {"workflow_integrity_passed": 0},
160
                           {"outcome": "unknown"}, {"returncode": "77"}, {"skipped": True}):
161
                self.assertTrue(workflow_evidence_failures([{**rows[-1], **change}]), change)
162
163
    def test_trusted_pre_head_agent_failure_is_measured_not_persisted_success(self):
164
        import agent_workflow as aw
165
        import workflow_ab
166
        from oakbench.workflow_oracles import task_evidence
167
        from types import SimpleNamespace
168
        with tempfile.TemporaryDirectory() as tmp:
169
            root = Path(tmp)
170
            repo = root / "repo"
171
            workflow_ab.make_wide_config_fixture(repo)
172
            evidence = task_evidence("wide_config_refactor", repo, "git", "/git")
173
            self.assertIs(evidence["workflow_integrity_passed"], False)
174
            self.assertEqual(evidence["workflow_integrity_evidence_class"], "worktree_payload")
175
            stdout, stderr, prompt = [root / name for name in ("stdout", "stderr", "prompt")]
176
            for path in (stdout, stderr, prompt): path.write_text("")
177
            oracle = SimpleNamespace(elapsed_ms=1, vcs_ms=1, test_ms=1, success=False,
178
                checks={"required_checks_passed": False}, failure_reason=evidence["workflow_integrity_failure_reason"],
179
                changed_files=[], test_returncode=1, test_output_bytes=0, dirty_files_at_end=0,
180
                commit_delta=0, bytes_written=0, artifact_paths=[], evidence=evidence)
181
            rows = [aw.make_row("gate", "2026-09-11T00:00:00Z", "test",
182
                aw.AgentConfig("synthetic", "codex_exec_json", "test", Path(sys.executable), "test", "test"),
183
                workflow_ab.Subject(name, kind, name, Path("/" + kind)),
184
                workflow_ab.WORKFLOWS["wide_config_refactor"], "agent-default", 0, repo, root,
185
                0, 0, aw.AgentExecution(0, False, 1, stdout, stderr, prompt), oracle,
186
                "task", {}, {"oak_hash": "reviewed", "oak_status": "clean"}, {}, "minimal", "full-docs")
187
                for name, kind in (("git", "git"), ("oak", "oak"))]
188
            self.assertEqual(workflow_evidence_failures(rows), [])
189
            path = root / "rows.jsonl"
190
            path.write_text("\n".join(map(json.dumps, rows)))
191
            with contextlib.redirect_stdout(io.StringIO()):
192
                self.assertEqual(publish_gate.main([str(path)]), 0)
193
            for change in ({"oracle_version": "retired"}, {"workflow_integrity_source": None},
194
                           {"workflow_integrity_passed": True}, {"success": True}, {"returncode": 0},
195
                           {"workflow_integrity_evidence_class": "independent_committed_tree"}):
196
                self.assertTrue(workflow_evidence_failures([rows[0], {**rows[1], **change}]), change)
197
198
    def test_cross_subject_workflow_evidence_cannot_hide_asymmetry(self):
199
        rows = [{"subject": subject, "scenario": "wide_config_refactor", "operation": "agent.workflow",
200
                 "workflow_integrity_source": source, "workflow_integrity_passed": True, "returncode": 0,
201
                 "workflow_integrity_evidence_class": evidence_class, "oracle_version": WORKFLOW_ORACLE_VERSION,
202
                 "workflow_subject_binary_sha256": "b" * 64, "git_head_instrument_sha256": "a" * 64}
203
                for subject, source, evidence_class in (("git", "trusted_exact_task_worktree;independent_committed_tree", "independent_committed_tree"),
204
                    ("oak", "trusted_exact_task_worktree;subject_produced_oak_head_export", "subject_produced_committed_tree"))]
205
        self.assertTrue(workflow_evidence_failures(rows))
206
        rows[1]["workflow_integrity_source"] = "another independently validated reader"
207
        rows[1]["workflow_integrity_evidence_class"] = "independent_committed_tree"
208
        self.assertEqual(workflow_evidence_failures(rows), [])
209
        rows[1]["workflow_integrity_passed"] = None
210
        self.assertTrue(workflow_evidence_failures(rows))
211
        rows[1].pop("workflow_integrity_source")
212
        self.assertTrue(workflow_evidence_failures(rows))
213
214
    def test_skipped_workflow_instrument_cannot_disappear_from_public_comparison(self):
215
        rows = [{"subject": subject, "scenario": "wide_config_refactor", "operation": "agent.workflow",
216
                 "workflow_integrity_source": "trusted_exact_task_worktree;independent_committed_tree",
217
                 "workflow_integrity_evidence_class": "independent_committed_tree", "oracle_version": WORKFLOW_ORACLE_VERSION,
218
                 "workflow_integrity_passed": True, "returncode": 0,
219
                 "agent": {"name": "agent", "model": "model", "provider": "provider", "environment": "minimal"}}
220
                for subject in ("git", "oak")]
221
        rows[0].update(returncode=77, skipped=True, skip_reason="git_head_instrument_unavailable",
222
                       workflow_integrity_passed=None)
223
        self.assertTrue(workflow_evidence_failures(rows))
224
        with tempfile.TemporaryDirectory() as temporary:
225
            path = Path(temporary) / "rows.jsonl"
226
            path.write_text("\n".join(json.dumps(row) for row in rows))
227
            output = io.StringIO()
228
            with contextlib.redirect_stdout(output):
229
                self.assertEqual(publish_gate.main([str(path)]), 1)
230
            self.assertIn("FAIL   workflow-evidence", output.getvalue())
231
        rows[1]["agent"] = {**rows[1]["agent"], "model": "different"}
232
        self.assertTrue(workflow_evidence_failures(rows))
233
234
    def test_bugfix_real_producer_labels_retain_existing_publication_policy(self):
235
        rows = [{"subject": subject, "subject_kind": kind, "scenario": "bugfix_test_loop",
236
                 "operation": "workflow.total", "profile": "workflow", "returncode": 0,
237
                 "workflow_integrity_passed": True, "workflow_integrity_source": source,
238
                 "oracle_version": WORKFLOW_ORACLE_VERSION,
239
                 "source": {"oak_hash": "reviewed-revision", "oak_status": "clean"}}
240
                for subject, kind, source in (
241
                    ("git", "git", "worktree_payload_oracle;known_good_git_head_tree"),
242
                    ("oak", "oak", "worktree_payload_oracle;direct_repo_metadata_fingerprint"))]
243
        self.assertEqual(workflow_evidence_failures(rows), [])
244
        with tempfile.TemporaryDirectory() as temporary:
245
            path = Path(temporary) / "rows.jsonl"
246
            path.write_text("\n".join(json.dumps(row) for row in rows))
247
            output = io.StringIO()
248
            with contextlib.redirect_stdout(output):
249
                code = publish_gate.main([str(path)])
250
            self.assertEqual(code, 0, output.getvalue())
251
            self.assertNotIn("FAIL   workflow-evidence", output.getvalue())
252
253
    def test_trusted_workflows_require_measured_independent_same_version_evidence(self):
254
        for scenario in ("wide_config_refactor", "large_asset_manifest"):
255
            rows = [{"subject": subject, "scenario": scenario, "operation": "workflow.total",
256
                     "oracle_version": WORKFLOW_ORACLE_VERSION, "workflow_integrity_passed": True, "returncode": 0,
257
                     "workflow_integrity_evidence_class": "independent_committed_tree",
258
                     "workflow_integrity_source": source, "workflow_subject_binary_sha256": "b" * 64, "git_head_instrument_sha256": "a" * 64}
259
                    for subject, source in (("git", "trusted_exact_task_worktree;independent_committed_tree"),
260
                                            ("git_candidate", "trusted_exact_task_worktree;reviewed_external_reader"))]
261
            self.assertEqual(workflow_evidence_failures(rows), [])
262
            for change in ({"git_head_instrument_sha256": "b" * 64}, {"workflow_subject_binary_sha256": None}, {"oracle_version": "other"}, {"oracle_version": None},
263
                           {"workflow_integrity_evidence_class": None},
264
                           {"workflow_integrity_source": "trusted_exact_task_worktree;subject_produced_oak_head_export"},
265
                           {"workflow_integrity_evidence_class": "subject_produced_committed_tree"},
266
                           {"workflow_integrity_passed": None}, {"workflow_integrity_passed": False}):
267
                with self.subTest(scenario=scenario, change=change):
268
                    self.assertTrue(workflow_evidence_failures([rows[0], {**rows[1], **change}]))
269
            rows[1].update(subject="oak", workflow_integrity_source="trusted_exact_task_worktree;subject_produced_oak_head_export",
270
                           workflow_integrity_evidence_class="subject_produced_committed_tree")
271
            with tempfile.TemporaryDirectory() as temporary:
272
                path = Path(temporary) / "rows.jsonl"
273
                path.write_text("\n".join(json.dumps(row) for row in rows))
274
                output = io.StringIO()
275
                with contextlib.redirect_stdout(output):
276
                    self.assertEqual(publish_gate.main([str(path)]), 1)
277
                self.assertIn("FAIL   workflow-evidence", output.getvalue())
278
279
    def test_publication_entrypoint_enforces_evidence(self):
280
        rows = []
281
        for subject in ("git", "git_untracked_cache", "git_fsmonitor"):
282
            rows.append({
283
                "profile": "standard", "subject": subject, "scenario": "tiny_text",
284
                "operation": "diff.full.inforecall", "returncode": 0,
285
                "env_isolation_version": "1", "randomized_subject_order": True,
286
                "subject_order": ["git", "git_untracked_cache", "git_fsmonitor"],
287
                "benchmark_track": "core-equivalent", "bench_id": "gate-test", "run": 0,
288
                **exact_output(),
289
            })
290
        measured = [
291
            {key: value for key, value in row.items() if key not in exact_output()}
292
            for row in rows
293
        ]
294
        rows.extend({**row, "operation": "diff.dirty.inforecall",
295
                     **{key: value for key, value in exact_output().items() if not key.startswith("patch_")}}
296
                    for row in measured)
297
        rows.extend(
298
            {**row, "operation": "status.clean", "run": run}
299
            for row in measured for run in range(30)
300
        )
301
        with tempfile.TemporaryDirectory() as temporary:
302
            path = Path(temporary) / "rows.jsonl"
303
            path.write_text("\n".join(json.dumps(row) for row in rows))
304
            with contextlib.redirect_stdout(io.StringIO()):
305
                self.assertEqual(publish_gate.main([str(path)]), 0)
306
            rows[0]["patch_apply_ok"] = None
307
            rows[0]["patch_skip_reason"] = "git_unavailable"
308
            path.write_text("\n".join(json.dumps(row) for row in rows))
309
            output = io.StringIO()
310
            with contextlib.redirect_stdout(output):
311
                self.assertEqual(publish_gate.main([str(path)]), 1)
312
            self.assertIn("FAIL   output-evidence", output.getvalue())
313
314
315
if __name__ == "__main__":
316
    unittest.main()