Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathtest_evals_runtime.py
More file actions
1638 lines (1342 loc) · 63.7 KB
/
Copy pathtest_evals_runtime.py
File metadata and controls
1638 lines (1342 loc) · 63.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Runtime tests for the reviewer-eval harness (no codex, no network).
These exercise the real ``CodexReviewer.review()`` return contract and the
experiment-identity keying that resume relies on — the two bugs an earlier local
AI review caught (the ``ReviewOutput`` kwarg mismatch and run-artifact aliasing
across models) live here, so this is where they get a regression test.
``call_codex`` and the git worktree are stubbed.
"""
import pathlib
import sys
import pytest
_REPO = pathlib.Path(__file__).resolve().parent.parent
_EVAL_ROOT = _REPO / "tools" / "reviewer-eval"
pytestmark = pytest.mark.skipif(
not _EVAL_ROOT.exists(),
reason="reviewer-eval harness not present (isolated install)",
)
if _EVAL_ROOT.exists() and str(_EVAL_ROOT) not in sys.path:
sys.path.insert(0, str(_EVAL_ROOT))
# --------------------------------------------------------------------------- #
# Helpers
# --------------------------------------------------------------------------- #
def _make_reviewer(monkeypatch, review_md="## Overall Assessment\n✅ Looks good\n"):
"""A CodexReviewer with call_codex + worktree stubbed (no codex, no git)."""
from adapters import codex_reviewer as cr
from adapters import worktree
r = cr.CodexReviewer(
repo_root=str(_REPO), runs_root="/tmp/reviewer-eval-test", prompt_text="BASE PROMPT BODY"
)
# Stub the codex call and the worktree materialize/cleanup so review() is
# exercised end-to-end without spawning codex or touching git.
monkeypatch.setattr(
r._mod,
"call_codex",
lambda prompt, model, repo_root: (review_md, {"backend": "codex"}),
raising=True,
)
monkeypatch.setattr(
r,
"build_prompt_for_case",
lambda case, worktree_key=None: ("PROMPT", "/tmp/reviewer-eval-test/wt", "deadbeef"),
raising=True,
)
monkeypatch.setattr(worktree, "cleanup", lambda *a, **k: None, raising=True)
return r
def _case():
from engine.models import STRATUM_HISTORICAL, Case
return Case(id="c1", stratum=STRATUM_HISTORICAL)
# --------------------------------------------------------------------------- #
# Bug 1 (was P1): CodexReviewer.review() must return a valid ReviewOutput.
# --------------------------------------------------------------------------- #
def test_codex_reviewer_review_returns_ok(monkeypatch):
from engine.models import Config, ReviewOutput
r = _make_reviewer(monkeypatch)
out = r.review(_case(), Config(id="B", model="gpt-5.5"), 0)
assert isinstance(out, ReviewOutput)
assert out.review_markdown.startswith("## Overall Assessment")
assert out.cli_version # recorded
assert out.latency_s >= 0.0
def test_run_matrix_produces_ok_runresult(monkeypatch):
"""A successful review must yield an ok RunResult, not an INFRA_ERROR."""
from engine.models import Config
from engine.runner import run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch)
store = RunStore("/tmp/reviewer-eval-test/runs-ok")
# fresh store each run
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
results = run_matrix(
[_case()],
[Config(id="B", model="gpt-5.5")],
r,
store,
k=1,
max_parallel=1,
)
assert len(results) == 1
assert results[0].ok, f"expected ok RunResult, got infra_error={results[0].infra_error}"
assert results[0].review_markdown
# --------------------------------------------------------------------------- #
# Bug 2 (was P0): experiment identity must not alias across different models
# sharing the same config id.
# --------------------------------------------------------------------------- #
def test_experiment_tag_differs_by_model(monkeypatch):
from engine.models import Config
r = _make_reviewer(monkeypatch)
tag_a = r.experiment_tag(Config(id="B", model="gpt-5.4"))
tag_b = r.experiment_tag(Config(id="B", model="gpt-5.5"))
assert tag_a != tag_b, "same config id + different model must yield distinct tags"
def test_run_key_no_alias_across_models(monkeypatch):
from engine.models import Config
from engine.store import run_key
r = _make_reviewer(monkeypatch)
k4 = run_key("c1", "B", 0, r.experiment_tag(Config(id="B", model="gpt-5.4")))
k5 = run_key("c1", "B", 0, r.experiment_tag(Config(id="B", model="gpt-5.5")))
assert k4 != k5, "run files for different models must not collide under one config id"
def test_runresult_carries_run_id_and_prompt_sha(monkeypatch):
"""The run artifact must record its own identity so compare can key on it."""
from engine.models import Config
from engine.runner import run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch)
store = RunStore("/tmp/reviewer-eval-test/runs-id")
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
results = run_matrix(
[_case()],
[Config(id="B", model="gpt-5.5")],
r,
store,
k=1,
max_parallel=1,
)
rr = results[0]
assert rr.run_id, "RunResult must carry a stable run_id"
assert rr.prompt_sha, "RunResult must record the prompt_sha it reviewed"
def test_resume_reruns_when_model_changes(monkeypatch):
"""Changing the model under the same config id must NOT resume stale runs."""
from engine.models import Config
from engine.runner import run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch, review_md="## A\n✅ first\n")
store = RunStore("/tmp/reviewer-eval-test/runs-resume")
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
run_matrix(
[_case()],
[Config(id="B", model="gpt-5.4")],
r,
store,
k=1,
max_parallel=1,
)
# Now rerun the SAME config id but a DIFFERENT model. Must not reuse the
# gpt-5.4 artifact; a new run file must appear.
r2 = _make_reviewer(monkeypatch, review_md="## B\n✅ second\n")
run_matrix(
[_case()],
[Config(id="B", model="gpt-5.5")],
r2,
store,
k=1,
max_parallel=1,
)
files = sorted(pathlib.Path(store.root).glob("*.json"))
assert len(files) == 2, f"expected 2 distinct run files (one per model), got {len(files)}"
def _ns(**kw):
import argparse
return argparse.Namespace(**kw)
# --------------------------------------------------------------------------- #
# Case-aware run identity (P1 #1): editing a case must invalidate its cache.
# --------------------------------------------------------------------------- #
def test_case_tag_changes_with_case_content():
from adapters.codex_reviewer import CodexReviewer
from engine.models import STRATUM_HISTORICAL, Case
r = CodexReviewer(repo_root=str(_REPO), runs_root="/tmp/reviewer-eval-test", prompt_text="X")
fx = {"kind": "git_range", "base_sha": "aaa"}
base = Case(id="c", stratum=STRATUM_HISTORICAL, fixture=dict(fx))
same = Case(id="c", stratum=STRATUM_HISTORICAL, fixture=dict(fx))
edited = Case(
id="c", stratum=STRATUM_HISTORICAL, fixture={"kind": "git_range", "base_sha": "bbb"}
)
assert r.case_tag(base) == r.case_tag(same) # stable; no patch read (git_range)
assert r.case_tag(base) != r.case_tag(edited) # base_sha edit -> new tag
# the machine-local _case_dir must NOT affect the tag
with_dir = Case(id="c", stratum=STRATUM_HISTORICAL, fixture={**fx, "_case_dir": "/wherever"})
assert r.case_tag(base) == r.case_tag(with_dir)
def test_case_tag_reads_patch_bytes_and_fails_loud(tmp_path):
from adapters.codex_reviewer import CodexReviewer
from engine.models import STRATUM_SYNTHETIC, Case
r = CodexReviewer(repo_root=str(_REPO), runs_root=str(tmp_path / "runs"), prompt_text="X")
patch = tmp_path / "inject.diff"
patch.write_text("AAA")
fx = {
"kind": "stored_patch",
"base_sha": "x",
"patch": "inject.diff",
"_case_dir": str(tmp_path),
}
t1 = r.case_tag(Case(id="c", stratum=STRATUM_SYNTHETIC, fixture=dict(fx)))
patch.write_text("BBB") # editing the patch bytes must change the tag
assert r.case_tag(Case(id="c", stratum=STRATUM_SYNTHETIC, fixture=dict(fx))) != t1
patch.unlink() # a declared-but-missing patch must fail loud, not hash-around it
with pytest.raises(FileNotFoundError):
r.case_tag(Case(id="c", stratum=STRATUM_SYNTHETIC, fixture=dict(fx)))
def test_resume_reruns_when_case_changes(monkeypatch):
from engine.models import STRATUM_HISTORICAL, Case, Config
from engine.runner import run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch)
store = RunStore("/tmp/reviewer-eval-test/runs-case")
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
cfg = [Config(id="A", model="gpt-5.4")]
run_matrix(
[Case(id="x", stratum=STRATUM_HISTORICAL, fixture={"base_sha": "aaa"})],
cfg,
r,
store,
k=1,
max_parallel=1,
)
# Same case id, edited content -> must NOT resume the stale run.
run_matrix(
[Case(id="x", stratum=STRATUM_HISTORICAL, fixture={"base_sha": "bbb"})],
cfg,
r,
store,
k=1,
max_parallel=1,
)
files = sorted(pathlib.Path(store.root).glob("*.json"))
assert len(files) == 2, f"editing the case must rerun, not resume; got {len(files)}"
# --------------------------------------------------------------------------- #
# compare (P1 #2): the per-run manifest isolates one experiment.
# --------------------------------------------------------------------------- #
def test_compare_honors_manifest(tmp_path, monkeypatch):
import run_eval
from engine.models import RunResult
from engine.store import RunStore, write_json
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
store = RunStore(str(tmp_path / "runs" / "full"))
cid = "s1-coef-dict-collision" # a real corpus case so build_bundle renders it
store.save(
"keep",
RunResult(
case_id=cid,
config_id="A",
repeat_idx=0,
review_markdown="KEEP THIS REVIEW",
model="gpt-5.5",
run_id="keep",
),
)
store.save(
"drop",
RunResult(
case_id=cid,
config_id="A",
repeat_idx=0,
review_markdown="STALE DROP REVIEW",
model="gpt-5.4",
run_id="drop",
),
)
write_json(
str(tmp_path / "runs" / "full-manifest.json"), {"run_ids": ["keep"], "configs": ["A"]}
)
assert run_eval.cmd_compare(_ns(subdir="full")) == 0
out = (tmp_path / "runs" / "full" / "comparison.md").read_text()
assert "KEEP THIS REVIEW" in out
assert "STALE DROP REVIEW" not in out, "manifest must exclude the stale experiment's run"
def test_compare_without_manifest_fails_closed_unless_allow_mixed(tmp_path, monkeypatch, capsys):
import run_eval
from engine.models import RunResult
from engine.store import RunStore
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
store = RunStore(str(tmp_path / "runs" / "full"))
store.save(
"only",
RunResult(
case_id="s1-coef-dict-collision",
config_id="A",
repeat_idx=0,
review_markdown="SOLO REVIEW",
model="gpt-5.4",
run_id="only",
),
)
# No manifest -> refuse by default (one run = one experiment).
assert run_eval.cmd_compare(_ns(subdir="full", allow_mixed=False)) != 0
assert "no manifest" in capsys.readouterr().err.lower()
# --allow-mixed is the explicit override: compare ALL runs, with a warning.
assert run_eval.cmd_compare(_ns(subdir="full", allow_mixed=True)) == 0
assert "allow-mixed" in capsys.readouterr().err.lower()
assert "SOLO REVIEW" in (tmp_path / "runs" / "full" / "comparison.md").read_text()
def test_compare_fails_closed_on_rubric_drift(tmp_path, monkeypatch):
"""compare points graders at the live pr_review.md, so it must refuse if that
rubric changed since the run (stored base_prompt_sha != live)."""
import run_eval
from adapters import ci_prompt
from engine.models import RunResult
from engine.store import RunStore, write_json
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
store = RunStore(str(tmp_path / "runs" / "full"))
store.save(
"r1",
RunResult(
case_id="c", config_id="A", repeat_idx=0, review_markdown="x", model="m", run_id="r1"
),
)
write_json(
str(tmp_path / "runs" / "full-manifest.json"),
{"run_ids": ["r1"], "configs": ["A"], "base_prompt_sha": "deadbeefdeadbeef"},
)
# Live rubric hashes to something else -> drift -> refuse.
monkeypatch.setattr(
ci_prompt, "read_current_prompt", lambda *a, **k: "A DIFFERENT RUBRIC", raising=True
)
assert run_eval.cmd_compare(_ns(subdir="full", allow_mixed=False)) != 0
def test_compare_renders_from_run_snapshot_not_corpus(tmp_path, monkeypatch):
import run_eval
from engine.models import RunResult
from engine.store import RunStore, write_json
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
store = RunStore(str(tmp_path / "runs" / "full"))
# Ground truth whose marker exists ONLY in the artifact's snapshot — and a
# case_id that is NOT in the corpus — so a corpus reload could not produce it.
snap = {
"title": "Snapshot Case",
"stratum": "s2_historical",
"ground_truth": [
{
"id": "snap:b1",
"file": "z.py",
"line_window": [1, 2],
"bug_class": "x",
"expected_severity": "P1",
"rationale": "SNAPSHOT-ONLY-MARKER",
}
],
"expect_no_blockers": False,
"allow_severities": ["P2", "P3"],
"known_fp_topics": [],
}
store.save(
"k",
RunResult(
case_id="not-a-corpus-case",
config_id="A",
repeat_idx=0,
review_markdown="rev",
model="gpt-5.4",
run_id="k",
case_snapshot=snap,
),
)
write_json(str(tmp_path / "runs" / "full-manifest.json"), {"run_ids": ["k"], "configs": ["A"]})
assert run_eval.cmd_compare(_ns(subdir="full")) == 0
out = (tmp_path / "runs" / "full" / "comparison.md").read_text()
# Ground truth comes from the run's snapshot — compare never reads the corpus.
assert "SNAPSHOT-ONLY-MARKER" in out
assert "snap:b1" in out
assert "Snapshot Case" in out
def test_run_rejects_unknown_configs(tmp_path, monkeypatch):
import run_eval
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
# A typo'd config id must fail closed BEFORE any codex call (no reviewer built),
# rather than silently running 0/0 and writing an empty manifest.
rc = run_eval.cmd_run(_ns(configs="Z", strata=None, subdir="full", k=1, max_parallel=1))
assert rc == 1
assert not (tmp_path / "runs" / "full-manifest.json").exists()
def test_case_tag_changes_with_scoring_metadata():
"""A metadata-only case edit (ground truth, NOT the fixture) must bust the cache.
Regression for PR #510 P1: case_tag previously hashed only the fixture+patch, so
editing ground_truth/severity/negative-control flags left the run key unchanged
and `compare` graded against a stale snapshot.
"""
from adapters.codex_reviewer import CodexReviewer
from engine.models import STRATUM_HISTORICAL, Case, GroundTruthBug
r = CodexReviewer(repo_root=str(_REPO), runs_root="/tmp/reviewer-eval-test", prompt_text="X")
fx = {"kind": "git_range", "base_sha": "aaa"} # identical fixture across all three
base = Case(
id="c",
stratum=STRATUM_HISTORICAL,
fixture=dict(fx),
ground_truth=[
GroundTruthBug(
id="c:b1", file="f.py", line_window=(1, 5), bug_class="x", expected_severity="P1"
)
],
)
sev = Case(
id="c",
stratum=STRATUM_HISTORICAL,
fixture=dict(fx),
ground_truth=[
GroundTruthBug(
id="c:b1", file="f.py", line_window=(1, 5), bug_class="x", expected_severity="P0"
)
],
)
neg = Case(
id="c",
stratum=STRATUM_HISTORICAL,
fixture=dict(fx),
ground_truth=[],
expect_no_blockers=True,
)
assert r.case_tag(base) != r.case_tag(sev), "editing expected_severity must bust the cache"
assert r.case_tag(base) != r.case_tag(neg), "editing expect_no_blockers must bust the cache"
def test_run_and_smoke_fail_closed_on_empty_corpus(tmp_path, monkeypatch):
"""run/smoke must NOT report success (or write a manifest) on zero selected cases."""
import run_eval
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
# A stratum that matches no corpus directory -> zero cases (no codex reached).
rc_run = run_eval.cmd_run(
_ns(configs="A,B", strata=["no_such_stratum"], subdir="full", k=1, max_parallel=1)
)
assert rc_run == 1
assert not (tmp_path / "runs" / "full-manifest.json").exists(), "no manifest for a no-op run"
rc_smoke = run_eval.cmd_smoke(
_ns(configs="A", strata=["no_such_stratum"], k=1, limit=0, max_parallel=1)
)
assert rc_smoke == 1
def test_build_prompt_cleans_worktree_on_build_failure(monkeypatch):
"""A prompt-build failure after materialize (e.g. the notebook guard) must not
leak a detached worktree."""
from adapters import ci_prompt, worktree
from adapters import codex_reviewer as cr
from engine.models import STRATUM_SYNTHETIC, Case
r = cr.CodexReviewer(repo_root=str(_REPO), runs_root="/tmp/reviewer-eval-test", prompt_text="X")
class _Mat:
worktree_dir = "/tmp/reviewer-eval-test/wt-leaktest"
base_sha = "b"
head_sha = "h"
def _raise(**_kw):
raise NotImplementedError("notebook case unsupported")
cleaned = []
monkeypatch.setattr(worktree, "materialize", lambda *a, **k: _Mat(), raising=True)
monkeypatch.setattr(ci_prompt, "build_ci_prompt", _raise, raising=True)
monkeypatch.setattr(worktree, "cleanup", lambda wt, root: cleaned.append(wt), raising=True)
case = Case(id="c", stratum=STRATUM_SYNTHETIC, fixture={"_case_dir": "/x"})
with pytest.raises(NotImplementedError):
r.build_prompt_for_case(case, worktree_key="c.A.r0")
assert cleaned == ["/tmp/reviewer-eval-test/wt-leaktest"], "worktree must be cleaned on failure"
# --------------------------------------------------------------------------- #
# Verify-on-resume (PR #510 round 2): a cached run is reused ONLY if the model
# would see byte-identical input now — covers harness-code edits the run key
# can't fingerprint.
# --------------------------------------------------------------------------- #
def test_resume_reruns_when_built_prompt_changes(monkeypatch):
from engine.models import STRATUM_HISTORICAL, Case, Config
from engine.runner import run_matrix
from engine.store import RunStore
store = RunStore("/tmp/reviewer-eval-test/runs-promptchange")
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
cfg = [Config(id="A", model="gpt-5.4")]
case = Case(id="x", stratum=STRATUM_HISTORICAL)
# Run 1: the stub builds "PROMPT" (default) and caches review "## V1".
r1 = _make_reviewer(monkeypatch, review_md="## V1\n")
run_matrix([case], cfg, r1, store, k=1, max_parallel=1)
# Same case/config (=> same run key), but the BUILT PROMPT now differs.
r2 = _make_reviewer(monkeypatch, review_md="## V2\n")
# Pin the backend-contract term equal to r1's so the run KEY is identical:
# this test must exercise the prompt re-verify path, not a key miss from the
# backend-contract term (which _make_reviewer perturbs by stubbing call_codex).
r2.backend_contract_sha = r1.backend_contract_sha
monkeypatch.setattr(
r2,
"build_prompt_for_case",
lambda case, worktree_key=None: (
"PROMPT-CHANGED",
"/tmp/reviewer-eval-test/wt",
"deadbeef",
),
raising=True,
)
results = run_matrix([case], cfg, r2, store, k=1, max_parallel=1)
assert results[0].review_markdown.startswith(
"## V2"
), "stale cached review was reused despite the built prompt changing"
# --------------------------------------------------------------------------- #
# Backend-contract identity (PR #510 round 3 P1): experiment identity must also
# cover the codex-invocation wrapper (_build_codex_cmd / call_codex), not just
# the model/prompt/declared-config — else a wrapper edit silently resumes a stale
# artifact run under the OLD wrapper.
# --------------------------------------------------------------------------- #
def _wrapper_v2(model, repo_root, output_path):
# A _build_codex_cmd whose SOURCE differs from openai_review's (flips the
# sandbox + drops the effort/-o flags) -> a distinct backend_contract_sha.
return ["codex", "exec", "--model", model, "--sandbox", "workspace-write"]
def test_experiment_tag_differs_when_backend_wrapper_changes(monkeypatch):
from engine.models import Config
r = _make_reviewer(monkeypatch)
cfg = Config(id="B", model="gpt-5.4")
tag_before = r.experiment_tag(cfg)
# Same model/effort/sandbox/prompt/cli, but HOW codex is invoked changed.
monkeypatch.setattr(r._mod, "_build_codex_cmd", _wrapper_v2, raising=True)
r.backend_contract_sha = r._backend_contract_sha(r._mod)
assert (
r.experiment_tag(cfg) != tag_before
), "a codex-wrapper change must yield a distinct experiment tag"
def test_resume_reruns_when_backend_wrapper_changes(monkeypatch):
"""A cached run must NOT be resumed once the codex-invocation wrapper changed,
even when the case/config and the built prompt are byte-identical.
"""
from engine.models import STRATUM_HISTORICAL, Case, Config
from engine.runner import run_matrix
from engine.store import RunStore
store = RunStore("/tmp/reviewer-eval-test/runs-backendchange")
for f in pathlib.Path(store.root).glob("*.json"):
f.unlink()
cfg = [Config(id="A", model="gpt-5.4")]
case = Case(id="x", stratum=STRATUM_HISTORICAL)
# Run 1 caches "## V1" under a fixed backend-contract baseline.
r1 = _make_reviewer(monkeypatch, review_md="## V1\n")
r1.backend_contract_sha = "contract-v1"
run_matrix([case], cfg, r1, store, k=1, max_parallel=1)
# Control: an arm with the SAME contract (and same prompt) resumes V1 — proves
# the rerun below is caused by the contract change, not by something else.
r_same = _make_reviewer(monkeypatch, review_md="## SHOULD-NOT-APPEAR\n")
r_same.backend_contract_sha = "contract-v1"
res_same = run_matrix([case], cfg, r_same, store, k=1, max_parallel=1)
assert res_same[0].review_markdown.startswith(
"## V1"
), "identical backend contract + prompt must resume the cached run"
# Treatment: the wrapper source changed -> distinct identity -> rerun.
r2 = _make_reviewer(monkeypatch, review_md="## V2\n")
monkeypatch.setattr(r2._mod, "_build_codex_cmd", _wrapper_v2, raising=True)
r2.backend_contract_sha = r2._backend_contract_sha(r2._mod)
assert r2.backend_contract_sha != "contract-v1", "the wrapper edit must move identity"
res2 = run_matrix([case], cfg, r2, store, k=1, max_parallel=1)
assert res2[0].review_markdown.startswith(
"## V2"
), "stale cached review was reused despite the codex invocation wrapper changing"
class _InfraBoom:
# cli_version must match config/configs.json's pin so the A/B CLI-equality
# assert doesn't fire before we reach the infra path.
def cli_version(self):
return "codex-cli 0.130.0"
def experiment_tag(self, config):
return "tag"
def case_tag(self, case):
return "ctag"
def prompt_sha_for(self, case):
return "psha"
def review(self, case, config, repeat_idx):
raise RuntimeError("simulated codex failure")
def test_run_fails_closed_on_infra_error(tmp_path, monkeypatch):
"""cmd_run must exit non-zero and write a FAILURE-MARKER manifest (never a valid
run_ids manifest) when any run hits INFRA_ERROR, so `compare` can't present a
partial run as a valid A/B."""
import json as _json
import run_eval
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
monkeypatch.setattr(run_eval.CorpusLoader, "verify", lambda self, case: None, raising=True)
monkeypatch.setattr(run_eval, "_build_reviewer", lambda repo_root: _InfraBoom(), raising=True)
rc = run_eval.cmd_run(
_ns(configs="A", strata=["s1_synthetic"], subdir="full", k=1, max_parallel=1)
)
assert rc != 0, "run must fail closed on INFRA_ERROR"
manifest_path = tmp_path / "runs" / "full-manifest.json"
assert manifest_path.exists(), "infra-failed run must write a failure-marker manifest"
m = _json.loads(manifest_path.read_text())
assert m.get("failed") is True, "manifest must be marked failed"
assert not m.get("run_ids"), "a failed run must not record run_ids"
# --------------------------------------------------------------------------- #
# smoke --limit contract (PR #510 round 3 P2): bare `smoke` must run exactly ONE
# case (matching the README's "1 case, first codex call"), with `--limit 0` as
# the explicit "run the whole selected corpus" escape hatch.
# --------------------------------------------------------------------------- #
def test_smoke_cli_default_limits_to_one_case(tmp_path, monkeypatch):
import run_eval
from engine.models import STRATUM_SYNTHETIC, Case
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
# Three fake cases so "1 case" vs "all" is observable without loading the
# real corpus or spawning codex.
fake_cases = [Case(id=f"c{i}", stratum=STRATUM_SYNTHETIC) for i in range(3)]
monkeypatch.setattr(
run_eval.CorpusLoader, "load_cases", lambda self, strata: list(fake_cases), raising=True
)
# Not testing validation here: skip the (git-materializing) verify preflight.
monkeypatch.setattr(run_eval.CorpusLoader, "verify", lambda self, case: None, raising=True)
class _Rev:
def cli_version(self):
return "codex-cli 0.130.0"
monkeypatch.setattr(run_eval, "_build_reviewer", lambda repo_root: _Rev(), raising=True)
captured = {}
def _capture_run_matrix(cases, configs, *a, **k):
captured["n"] = len(cases)
return []
# cmd_smoke does `from engine.runner import run_matrix` at call time, so patch
# the source name, not run_eval's namespace.
monkeypatch.setattr("engine.runner.run_matrix", _capture_run_matrix, raising=True)
# Bare `smoke --configs A` (argparse default --limit) -> exactly one case.
monkeypatch.setattr(sys, "argv", ["run_eval.py", "smoke", "--configs", "A"])
assert run_eval.main() == 0
assert captured["n"] == 1, "bare `smoke` must run exactly one case (README contract)"
# `--limit 0` is the explicit "run all selected" escape hatch.
monkeypatch.setattr(sys, "argv", ["run_eval.py", "smoke", "--configs", "A", "--limit", "0"])
assert run_eval.main() == 0
assert captured["n"] == 3, "`smoke --limit 0` must run all selected cases"
# --------------------------------------------------------------------------- #
# Non-model confounds + manifest fail-closed (local codex round, PR #510): the
# model must be the ONLY variable across arms, and a failed rerun must not leave
# a prior run's manifest live for `compare` to render.
# --------------------------------------------------------------------------- #
def test_run_matrix_aborts_on_confound_mismatch(monkeypatch):
"""Arms that drift in any held-constant confound (effort/sandbox/action_version)
must abort up front — the model is the only intended variable."""
from engine.models import Config
from engine.runner import ConfoundMismatch, run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch)
store = RunStore("/tmp/reviewer-eval-test/runs-confound")
for field, a, b in [
("sandbox", "read-only", "workspace-write"),
("effort", "xhigh", "high"),
("action_version", "v1", "v2"),
]:
cfgs = [
Config(id="A", model="gpt-5.4", **{field: a}),
Config(id="B", model="gpt-5.5", **{field: b}),
]
with pytest.raises(ConfoundMismatch):
run_matrix([_case()], cfgs, r, store, k=1, max_parallel=1)
def test_review_rejects_non_readonly_sandbox(monkeypatch):
"""recorded==executed: _build_codex_cmd hardcodes read-only, so a config asking
for a different sandbox must fail closed (mirrors the effort guard)."""
from engine.models import Config
r = _make_reviewer(monkeypatch)
with pytest.raises(NotImplementedError):
r.review(_case(), Config(id="B", model="gpt-5.5", sandbox="workspace-write"), 0)
def test_failed_rerun_invalidates_stale_manifest(tmp_path, monkeypatch):
"""A successful run writes a manifest; a later FAILED rerun into the same subdir
must invalidate it (mark failed) so `compare` refuses instead of rendering the
stale experiment."""
import json as _json
import run_eval
from engine.models import ReviewOutput
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
monkeypatch.setattr(run_eval.CorpusLoader, "verify", lambda self, case: None, raising=True)
manifest_path = tmp_path / "runs" / "full-manifest.json"
class _Ok:
def cli_version(self):
return "codex-cli 0.130.0"
def experiment_tag(self, config):
return "tag"
def case_tag(self, case):
return "ctag-v1"
def prompt_sha_for(self, case):
return "psha"
def review(self, case, config, repeat_idx):
return ReviewOutput(
review_markdown="## ok",
cli_version="codex-cli 0.130.0",
latency_s=0.0,
usage={"prompt_sha": "psha"},
)
monkeypatch.setattr(run_eval, "_build_reviewer", lambda repo_root: _Ok(), raising=True)
rc_ok = run_eval.cmd_run(
_ns(configs="A", strata=["s1_synthetic"], subdir="full", k=1, max_parallel=1)
)
assert rc_ok == 0
assert _json.loads(manifest_path.read_text()).get("run_ids"), "success records run_ids"
# The case was edited (new case_tag) and now errors -> a failed rerun. The prior
# valid manifest must be invalidated, not left live for compare.
class _BoomEdited(_InfraBoom):
def case_tag(self, case):
return "ctag-v2" # edited case -> new key -> not resumed from cache
monkeypatch.setattr(run_eval, "_build_reviewer", lambda repo_root: _BoomEdited(), raising=True)
rc_fail = run_eval.cmd_run(
_ns(configs="A", strata=["s1_synthetic"], subdir="full", k=1, max_parallel=1)
)
assert rc_fail != 0
m = _json.loads(manifest_path.read_text())
assert m.get("failed") is True and not m.get("run_ids"), "stale manifest must be invalidated"
# compare must refuse the failed/incomplete experiment, not fall back to compare-all.
assert run_eval.cmd_compare(_ns(subdir="full")) != 0, "compare must refuse a failed run"
def test_run_aborts_on_invalid_case_before_any_codex_call(tmp_path, monkeypatch):
"""smoke/run must fail closed on a CorpusLoader.verify() failure BEFORE any
Codex call, so a stale/malformed case is never reviewed/graded against stale
ground truth."""
import run_eval
from engine.models import STRATUM_SYNTHETIC, Case
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
monkeypatch.setattr(
run_eval.CorpusLoader,
"load_cases",
lambda self, strata: [Case(id="bad", stratum=STRATUM_SYNTHETIC)],
raising=True,
)
monkeypatch.setattr(
run_eval.CorpusLoader,
"verify",
lambda self, case: "diff does not touch expected file(s)",
raising=True,
)
called = {"run": False}
def _no_run(*a, **k):
called["run"] = True
return []
monkeypatch.setattr("engine.runner.run_matrix", _no_run, raising=True)
monkeypatch.setattr(
run_eval,
"_build_reviewer",
lambda repo_root: (_ for _ in ()).throw(AssertionError),
raising=True,
)
rc = run_eval.cmd_run(
_ns(configs="A", strata=["s1_synthetic"], subdir="full", k=1, max_parallel=1)
)
assert rc != 0, "run must fail closed when a case fails validation"
assert not called["run"], "no review may run when a case fails validation"
# The up-front failure marker must remain (a preflight abort leaves the subdir in
# a failed state that compare refuses — never a prior run's live manifest).
import json as _json
m = _json.loads((tmp_path / "runs" / "full-manifest.json").read_text())
assert m.get("failed") is True and not m.get(
"run_ids"
), "preflight abort leaves a failed marker"
def test_run_matrix_fails_closed_on_experiment_tag_error(monkeypatch):
"""If experiment_tag() can't be computed, run_matrix must abort — never fall back
to an empty tag that could resume a stale experiment under an unchanged prompt."""
from engine.models import Config
from engine.runner import run_matrix
from engine.store import RunStore
r = _make_reviewer(monkeypatch)
monkeypatch.setattr(
r,
"experiment_tag",
lambda config: (_ for _ in ()).throw(RuntimeError("tag boom")),
raising=True,
)
store = RunStore("/tmp/reviewer-eval-test/runs-tagfail")
with pytest.raises(RuntimeError):
run_matrix([_case()], [Config(id="A", model="gpt-5.4")], r, store, k=1, max_parallel=1)
def test_compare_fails_closed_on_missing_artifact(tmp_path, monkeypatch):
"""compare must refuse when a manifest-listed run_id has no loadable artifact,
rather than silently emitting a partial bundle from the surviving subset."""
import run_eval
from engine.models import RunResult
from engine.store import RunStore, write_json
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
store = RunStore(str(tmp_path / "runs" / "full"))
store.save(
"present",
RunResult(
case_id="c",
config_id="A",
repeat_idx=0,
review_markdown="r",
model="m",
run_id="present",
),
)
# Manifest promises two runs, but only "present" has an artifact on disk.
write_json(
str(tmp_path / "runs" / "full-manifest.json"),
{"run_ids": ["present", "absent"], "configs": ["A", "B"]},
)
assert run_eval.cmd_compare(_ns(subdir="full")) != 0, "compare must refuse a missing artifact"
def test_stored_patch_path_must_be_contained(tmp_path):
"""A stored_patch's patch path must resolve inside its case directory; absolute or
traversal paths are rejected before any worktree work."""
from adapters import worktree
case_dir = str(tmp_path)
(tmp_path / "inject.diff").write_text("x")
assert worktree._resolve_patch_path("c", case_dir, "inject.diff").endswith("inject.diff")
with pytest.raises(worktree.MaterializeError):
worktree._resolve_patch_path("c", case_dir, "/etc/passwd")
with pytest.raises(worktree.MaterializeError):
worktree._resolve_patch_path("c", case_dir, "../../../../etc/passwd")
with pytest.raises(worktree.MaterializeError):
worktree._resolve_patch_path("c", case_dir, "")
def test_build_prompt_threads_rerun_state(monkeypatch):
"""A rerun case (fixture.rerun.previous_review) must be built as a CI re-review:
CodexReviewer threads is_rerun/prev_review into ci_prompt.build_ci_prompt."""
from adapters import ci_prompt, worktree
from adapters import codex_reviewer as cr
from engine.models import STRATUM_HISTORICAL, Case
r = cr.CodexReviewer(
repo_root=str(_REPO), runs_root="/tmp/reviewer-eval-test", prompt_text="BASE PROMPT"
)
class _Mat:
worktree_dir = "/tmp/reviewer-eval-test/wt"
base_sha = "base"
head_sha = "head"
monkeypatch.setattr(worktree, "materialize", lambda *a, **k: _Mat(), raising=True)
monkeypatch.setattr(worktree, "cleanup", lambda *a, **k: None, raising=True)
captured = {}
monkeypatch.setattr(
ci_prompt, "build_ci_prompt", lambda **kw: captured.update(kw) or "PROMPT", raising=True
)
rr_case = Case(
id="rr",
stratum=STRATUM_HISTORICAL,
fixture={"_case_dir": "", "rerun": {"previous_review": "## prior P1: foo"}},
)
r.build_prompt_for_case(rr_case, worktree_key="rr")
assert captured.get("is_rerun") is True, "rerun case must build with is_rerun=True"
assert "prior P1: foo" in captured.get("prev_review", ""), "prior review must be threaded"
captured.clear()
fresh = Case(id="nr", stratum=STRATUM_HISTORICAL, fixture={"_case_dir": ""})
r.build_prompt_for_case(fresh, worktree_key="nr")
assert captured.get("is_rerun") is False, "a non-rerun case must not set is_rerun"
def test_compare_bundle_header_reflects_configs():
"""The grading table is sized to the configs actually present — a single-arm run
must not be graded against a hardcoded A/B table."""
from engine.compare import build_bundle
from engine.models import RunResult
def _rr(cfg):
return RunResult(
case_id="c",
config_id=cfg,
repeat_idx=0,
review_markdown="## r",
model="m",
case_snapshot={"stratum": "s1_synthetic", "title": "t"},
)
single = build_bundle([_rr("A")])
assert "A caught?" in single and "B caught?" not in single, "single-arm: no B column"
ab = build_bundle([_rr("A"), _rr("B")])
assert "A caught?" in ab and "B caught?" in ab, "A/B run: both columns present"
def test_run_early_abort_writes_failure_marker(tmp_path, monkeypatch):
"""An early abort (e.g. ConfoundMismatch) after the manifest is removed must
leave a {failed:true} marker — NOT a missing manifest, which `compare` would
treat as 'no manifest -> compare ALL' over the prior run's stale artifacts."""
import json as _json
import run_eval
from engine.models import STRATUM_SYNTHETIC, Case
from engine.runner import ConfoundMismatch
monkeypatch.setattr(run_eval, "RUNS_DIR", str(tmp_path / "runs"))
monkeypatch.setattr(
run_eval.CorpusLoader,
"load_cases",
You can’t perform that action at this time.
