Repository navigation
Expand file tree
/
Copy pathagent_loop_benchmark.py
More file actions
1447 lines (1333 loc) · 59.8 KB
/
Copy pathagent_loop_benchmark.py
File metadata and controls
1447 lines (1333 loc) · 59.8 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
#!/usr/bin/env python3
"""Run reproducible paired Agent Loop benchmark samples over fresh Git worktrees.
The script is orchestration only. A caller-supplied Host driver performs the real
Direct/Code Mode task. This runner owns fresh worktrees, bounded annotation,
existing agent_loop_report summarization/comparison, fixture-side oracles, sample
status retention, and cleanup of its own temporary resources.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import signal
import stat
import shutil
import shlex
import subprocess
import sys
import tempfile
import time
import threading
from pathlib import Path
from typing import Any
try:
from scripts import agent_loop_report as report
from scripts import agent_temporal_evidence as temporal
from scripts.e2e_generic_agent_ws import GenericFixture, GENERIC_CASES, pressure_script, mixed_note_script, encoded_csv_script
except ModuleNotFoundError:
import agent_loop_report as report
import agent_temporal_evidence as temporal
from e2e_generic_agent_ws import GenericFixture, GENERIC_CASES, pressure_script, mixed_note_script, encoded_csv_script
STATUS_VALUES = frozenset(("pass", "fail", "partial", "unsupported"))
DEFAULT_CASES = ("readonly_review", "guarded_multi_file_edit", "long_validation_handoff")
DEFAULT_SELECTION_CASES = (
"selection_single_read",
"selection_batch_read",
"selection_cross_tool_review",
"selection_compound_source_context",
)
VARIANTS = ("direct", "code_mode")
# Selected, already-persisted metadata only. Model turns and raw payloads cannot
# be reconstructed from Agent Loop summaries.
PAIRED_DELTA_METRICS = (
"task_wall_time_ms",
"outer_calls.total",
"results.serialized_tool_result_bytes.total",
"repair_turns.total",
)
MAX_DRIVER_RECEIPT_BYTES = 64 * 1024
MAX_FIXTURE_ORACLE_BYTES = 1024 * 1024
MAX_CASE_MANIFEST_BYTES = 1024 * 1024
MAX_GIT_PATH_BYTES = 64 * 1024
MAX_GIT_PATHS = 512
CODE_MODE_TOOL_BY_SURFACE = {
"read_only": "execute_code_mode",
"validation": "execute_effectful_code_mode",
"guarded_edit": "execute_mutating_code_mode",
}
MAX_DRIVER_SECS = 30 * 60
class BenchmarkError(ValueError):
pass
class DriverTimeoutError(BenchmarkError):
pass
class DriverPlatformUnsupported(BenchmarkError):
pass
def _stable_json(value: Any) -> str:
return json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
def _run(argv: list[str], *, cwd: Path, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
argv,
cwd=cwd,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
def _terminate_driver_tree(process: subprocess.Popen[bytes]) -> None:
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
if process.poll() is None:
process.kill()
process.wait()
def _run_driver(argv: list[str], *, cwd: Path, env: dict[str, str]) -> subprocess.CompletedProcess[bytes]:
if os.name == "nt":
raise DriverPlatformUnsupported(
"paired benchmark Host driver requires POSIX process-group ownership"
)
try:
process = subprocess.Popen(
argv,
cwd=cwd,
env=env,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
except OSError as exc:
raise BenchmarkError("could not start benchmark Host driver") from exc
try:
returncode = process.wait(timeout=MAX_DRIVER_SECS)
except subprocess.TimeoutExpired as exc:
_terminate_driver_tree(process)
raise DriverTimeoutError("benchmark Host driver exceeded the 30 minute limit") from exc
except BaseException:
_terminate_driver_tree(process)
raise
_terminate_driver_tree(process)
return subprocess.CompletedProcess(argv, returncode)
def _require_exact_revision(repo: Path, revision: str) -> str:
completed = _run(["git", "rev-parse", "--verify", f"{revision}^{{commit}}"], cwd=repo)
if completed.returncode != 0:
raise BenchmarkError(f"could not resolve base revision: {revision}")
resolved = completed.stdout.strip()
if not report._is_exact_git_revision(resolved):
raise BenchmarkError("resolved base revision is not an exact 40-hex commit")
return resolved
def _git_root(path: Path) -> Path:
completed = _run(["git", "rev-parse", "--show-toplevel"], cwd=path)
if completed.returncode != 0:
raise BenchmarkError("benchmark repo must be inside a Git worktree")
return Path(completed.stdout.strip()).resolve()
def _head_revision(repo: Path) -> str:
completed = _run(["git", "rev-parse", "HEAD"], cwd=repo)
if completed.returncode != 0:
raise BenchmarkError("could not resolve current checkout HEAD")
head = completed.stdout.strip()
if not report._is_exact_git_revision(head):
raise BenchmarkError("current checkout HEAD is not an exact 40-hex commit")
return head
def _read_manifest_at_revision(repo: Path, revision: str) -> str:
object_name = f"{revision}:scripts/agent_loop_cases.json"
size_result = _run(["git", "cat-file", "-s", object_name], cwd=repo)
if size_result.returncode != 0:
raise BenchmarkError("could not read benchmark case manifest at base revision")
try:
size = int(size_result.stdout.strip())
except ValueError as exc:
raise BenchmarkError("benchmark case manifest size is invalid") from exc
if size < 0 or size > MAX_CASE_MANIFEST_BYTES:
raise BenchmarkError("benchmark case manifest exceeds the 1 MiB limit")
completed = subprocess.run(
["git", "show", object_name],
cwd=repo,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if completed.returncode != 0 or len(completed.stdout) != size:
raise BenchmarkError("could not read benchmark case manifest at base revision")
try:
return completed.stdout.decode("utf-8")
except UnicodeDecodeError as exc:
raise BenchmarkError("benchmark case manifest must be UTF-8 JSON") from exc
def _case(manifest: dict[str, Any], case_id: str) -> dict[str, Any]:
return report._case_by_id(manifest, case_id)
def _surface(case: dict[str, Any], variant: str) -> str:
if variant == report.TOOL_SELECTION_VARIANT:
if case.get("experiment") != "tool_selection":
raise BenchmarkError("free selection requires an explicit tool_selection case")
return report.TOOL_SELECTION_VARIANT
if variant == "direct":
return "direct"
if variant == "host_code_mode":
return report.HOST_CODE_MODE_SURFACE
surface = case.get("code_mode_surface")
canonical = report._canonical_code_mode_surface(surface)
if canonical is None:
raise BenchmarkError(f"case {case['id']} has no usable Code Mode surface")
return canonical
def _worktree_add(repo: Path, path: Path, base_revision: str) -> None:
completed = _run(["git", "worktree", "add", "--detach", str(path), base_revision], cwd=repo)
if completed.returncode == 0:
return
add_error = completed.stderr.strip() or "git worktree add failed"
try:
_worktree_remove(repo, path)
except BenchmarkError as cleanup_error:
raise BenchmarkError(f"{add_error}; owned worktree rollback failed: {cleanup_error}") from cleanup_error
raise BenchmarkError(add_error)
def _worktree_remove(repo: Path, path: Path) -> None:
completed = _run(["git", "worktree", "remove", "--force", str(path)], cwd=repo)
if completed.returncode == 0:
return
if path.exists():
shutil.rmtree(path, ignore_errors=True)
retry = _run(["git", "worktree", "remove", "--force", str(path)], cwd=repo)
if retry.returncode == 0:
return
if not path.exists() and "is not a working tree" in retry.stderr:
return
raise BenchmarkError(retry.stderr.strip() or "failed to remove owned benchmark worktree")
def _workspace_status(workspace: Path) -> bool:
try:
process = subprocess.Popen(
["git", "status", "--porcelain", "--untracked-files=all"],
cwd=workspace,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
except OSError as exc:
raise BenchmarkError("could not start git status") from exc
assert process.stdout is not None
with process.stdout:
first = process.stdout.read(1)
if first and process.poll() is None:
process.kill()
returncode = process.wait()
if first:
return True
if returncode != 0:
raise BenchmarkError("git status failed")
return False
def _bounded_git_paths(
argv: list[str],
*,
cwd: Path,
) -> tuple[bool, bool, list[bytes]]:
try:
process = subprocess.Popen(
["git", *argv],
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
except OSError as exc:
raise BenchmarkError("could not start bounded Git path query") from exc
assert process.stdout is not None
with process.stdout:
raw = process.stdout.read(MAX_GIT_PATH_BYTES + 1)
byte_overflow = len(raw) > MAX_GIT_PATH_BYTES
if byte_overflow and process.poll() is None:
process.kill()
returncode = process.wait()
if byte_overflow:
return returncode == 0, True, []
paths = [item for item in raw.split(b"\0") if item]
if len(paths) > MAX_GIT_PATHS:
return returncode == 0, True, []
return returncode == 0, False, paths
def _fixture_oracle(
case: dict[str, Any],
workspace: Path,
base_revision: str = "HEAD",
) -> dict[str, Any]:
spec = (case.get("correctness") or {}).get("fixture_oracle")
if not isinstance(spec, dict):
return {"available": False, "passed": None, "checks": [], "reason": "case has no fixture_oracle"}
checks: list[dict[str, Any]] = []
for rel_path, expected in sorted((spec.get("files") or {}).items()):
target = workspace / rel_path
try:
before = target.lstat()
except OSError:
checks.append({"path": rel_path, "passed": False, "reason": "file unavailable"})
continue
if not stat.S_ISREG(before.st_mode):
checks.append({"path": rel_path, "passed": False, "reason": "file is not regular"})
continue
flags = os.O_RDONLY
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
try:
fd = os.open(target, flags)
except OSError:
checks.append({"path": rel_path, "passed": False, "reason": "file unavailable"})
continue
try:
opened = os.fstat(fd)
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_dev != before.st_dev
or opened.st_ino != before.st_ino
):
checks.append({"path": rel_path, "passed": False, "reason": "file identity changed"})
continue
with os.fdopen(fd, "rb", closefd=True) as handle:
fd = -1
raw = handle.read(MAX_FIXTURE_ORACLE_BYTES + 1)
finally:
if fd >= 0:
os.close(fd)
if len(raw) > MAX_FIXTURE_ORACLE_BYTES:
checks.append({"path": rel_path, "passed": False, "reason": "file exceeds oracle byte limit"})
continue
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
checks.append({"path": rel_path, "passed": False, "reason": "file is not UTF-8"})
continue
expected_text = expected.get("expected_text")
if isinstance(expected_text, str):
passed = text == expected_text
else:
required = expected.get("required_text") or []
forbidden = expected.get("forbidden_text") or []
passed = all(item in text for item in required) and all(item not in text for item in forbidden)
checks.append({"path": rel_path, "passed": passed, "reason": None if passed else "text oracle mismatch"})
expected_changed = sorted(spec.get("changed_files") or [])
if expected_changed:
tracked_ok, tracked_overflow, tracked_paths = _bounded_git_paths(
["diff", "--name-only", "-z", base_revision, "--"],
cwd=workspace,
)
untracked_ok, untracked_overflow, untracked_paths = _bounded_git_paths(
["ls-files", "-z", "--others", "--exclude-standard"],
cwd=workspace,
)
overflow = tracked_overflow or untracked_overflow
changed_raw = sorted(set(tracked_paths) | set(untracked_paths)) if not overflow else []
expected_raw = sorted(item.encode("utf-8") for item in expected_changed)
changed = [
item.decode("utf-8", errors="backslashreplace")
for item in changed_raw
]
checks.append(
{
"kind": "changed_files",
"passed": tracked_ok and untracked_ok and not overflow and changed_raw == expected_raw,
"expected": expected_changed,
"actual": None if overflow else changed,
"reason": (
"changed path listing exceeds oracle limit"
if overflow
else "changed path query failed"
if not tracked_ok or not untracked_ok
else None
),
}
)
passed = bool(checks) and all(check.get("passed") is True for check in checks)
return {"available": True, "passed": passed, "checks": checks, "reason": None}
def _load_driver_receipt(path: Path) -> dict[str, Any]:
try:
before = path.lstat()
except OSError as exc:
raise BenchmarkError("driver did not create its result receipt") from exc
if not stat.S_ISREG(before.st_mode):
raise BenchmarkError("driver result must be a regular file")
if before.st_size > MAX_DRIVER_RECEIPT_BYTES:
raise BenchmarkError("driver result exceeds the 64 KiB receipt limit")
flags = os.O_RDONLY
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
try:
fd = os.open(path, flags)
except OSError as exc:
raise BenchmarkError("driver result must be a readable regular file") from exc
try:
opened = os.fstat(fd)
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_dev != before.st_dev
or opened.st_ino != before.st_ino
):
raise BenchmarkError("driver result changed identity before read")
with os.fdopen(fd, "rb", closefd=True) as handle:
fd = -1
raw = handle.read(MAX_DRIVER_RECEIPT_BYTES + 1)
finally:
if fd >= 0:
os.close(fd)
if len(raw) > MAX_DRIVER_RECEIPT_BYTES:
raise BenchmarkError("driver result exceeds the 64 KiB receipt limit")
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as exc:
raise BenchmarkError("driver result must be UTF-8 JSON") from exc
try:
value = json.loads(text)
except json.JSONDecodeError as exc:
raise BenchmarkError(f"driver result is not valid JSON: {exc}") from exc
except (RecursionError, ValueError) as exc:
raise BenchmarkError("driver result is not valid bounded JSON") from exc
if not isinstance(value, dict):
raise BenchmarkError("driver result must be a JSON object")
status = value.get("status")
if not isinstance(status, str) or status not in STATUS_VALUES:
raise BenchmarkError("driver result status must be pass, fail, partial, or unsupported")
return value
def _annotation(
case: dict[str, Any],
*,
variant: str,
surface: str,
base_revision: str,
receipt: dict[str, Any],
oracle: dict[str, Any],
) -> dict[str, Any]:
correctness = receipt.get("correctness")
if correctness is not None and not isinstance(correctness, dict):
raise BenchmarkError("driver correctness must be an object when present")
correctness = dict(correctness or {})
if oracle["available"]:
if oracle["passed"] is not True:
correctness["task_verdict"] = "fail"
elif correctness.get("task_verdict") is None and case.get("experiment") != "tool_selection":
correctness["task_verdict"] = "pass"
if case["validation"]["required"] is False and correctness.get("validation_verdict") is None:
correctness["validation_verdict"] = "not_required"
if correctness:
correctness.setdefault("task_verdict", "unavailable")
correctness.setdefault(
"validation_verdict",
"unavailable" if case["validation"]["required"] else "not_required",
)
value: dict[str, Any] = {
"schema_version": report.RUN_ANNOTATION_SCHEMA_VERSION,
"case_id": case["id"],
"variant": variant,
"surface": surface,
"base_revision": base_revision,
"case_fingerprint": report._case_fingerprint(case),
}
for field in ("repair_turns", "task_timing"):
if receipt.get(field) is not None:
value[field] = receipt[field]
if correctness:
value["correctness"] = correctness
return report.validate_run_annotation(value)
def _summary_for_receipt(
case: dict[str, Any],
*,
variant: str,
surface: str,
base_revision: str,
receipt: dict[str, Any],
annotation_path: Path,
case_manifest: Path,
workspace: Path,
) -> dict[str, Any] | None:
if receipt["status"] == "unsupported":
return None
audit_db = receipt.get("audit_db")
workflow_session_id = receipt.get("workflow_session_id")
trace_root = receipt.get("trace_root")
if not isinstance(audit_db, str) or not audit_db:
raise BenchmarkError("non-unsupported driver result requires audit_db")
if not isinstance(workflow_session_id, str) or not workflow_session_id:
raise BenchmarkError("non-unsupported driver result requires workflow_session_id")
audit_path = Path(audit_db)
if not audit_path.is_absolute():
audit_path = workspace / audit_path
trace_path: Path | None = None
if isinstance(trace_root, str) and trace_root:
trace_path = Path(trace_root)
if not trace_path.is_absolute():
trace_path = workspace / trace_path
return report.summarize(
trace_root=trace_path,
audit_db=audit_path,
workflow_session_id=workflow_session_id,
case_manifest=case_manifest,
case_id=case["id"],
variant=variant,
surface=surface,
base_revision=base_revision,
run_annotation=annotation_path,
)
def _tool_count(summary: dict[str, Any], variant: str, tool_name: str) -> int | None:
if variant in ("direct", "host_code_mode"):
value = report._get_path(summary, f"canonical_calls.by_name.{tool_name}")
return value if isinstance(value, int) else 0
if variant == "code_mode":
available = report._get_path(summary, "availability.code_mode_composition.available")
if available is not True:
return None
value = report._get_path(summary, f"composition.nested_tool_counts.{tool_name}")
return value if isinstance(value, int) else 0
return None
def _runtime_evidence_proven(
summary: dict[str, Any],
variant: str,
surface: str | None = None,
) -> bool:
outer_total = report._get_path(summary, "outer_calls.total")
if not isinstance(outer_total, int) or isinstance(outer_total, bool) or outer_total <= 0:
return False
composition_available = (
report._get_path(summary, "availability.code_mode_composition.available") is True
)
if variant == report.TOOL_SELECTION_VARIANT:
# Any admitted mix is valid here. The original forced-lane gate below
# still rejects mixtures; this experiment measures choice separately.
canonical_total = report._get_path(summary, "canonical_calls.total")
return (
surface == report.TOOL_SELECTION_VARIANT
and composition_available
and type(canonical_total) is int
and canonical_total == outer_total
)
if variant == "direct":
canonical_total = report._get_path(summary, "canonical_calls.total")
return (
composition_available
and isinstance(canonical_total, int)
and not isinstance(canonical_total, bool)
and canonical_total > 0
)
if variant == "host_code_mode":
# Canonical calls prove the runtime lane, not JavaScript-cell/model-turn
# identity. The caller separately records its actual Host configuration.
canonical_total = report._get_path(summary, "canonical_calls.total")
counts = report._get_path(summary, "canonical_calls.by_name")
return (surface == report.HOST_CODE_MODE_SURFACE and composition_available
and type(canonical_total) is int and canonical_total == outer_total
and isinstance(counts, dict)
and not any(counts.get(name, 0) for name in report.CODE_MODE_TOOLS))
if variant == "code_mode":
expected_tool = CODE_MODE_TOOL_BY_SURFACE.get(surface or "")
outer_code_mode = report._get_path(summary, "composition.outer_code_mode_calls")
outer_by_name = report._get_path(summary, "tools.outer_by_name")
if (
not composition_available
or expected_tool is None
or not isinstance(outer_code_mode, int)
or isinstance(outer_code_mode, bool)
or outer_code_mode <= 0
or not isinstance(outer_by_name, dict)
):
return False
code_mode_counts = {
name: count
for name in report.CODE_MODE_TOOLS
if isinstance((count := outer_by_name.get(name, 0)), int)
and not isinstance(count, bool)
and count > 0
}
if (
code_mode_counts.get(expected_tool) != outer_code_mode
or sum(code_mode_counts.values()) != outer_code_mode
):
return False
if surface == "read_only":
if any(
not isinstance(count, int)
or isinstance(count, bool)
or count < 0
for count in outer_by_name.values()
):
return False
bootstrap_count = outer_by_name.get("work_on_project", 0)
manifest_count = outer_by_name.get("read_tool_manifest", 0)
allowed = {expected_tool, "work_on_project", "read_tool_manifest"}
unexpected = {
name: count
for name, count in outer_by_name.items()
if name not in allowed and count > 0
}
return (
bootstrap_count == 1
and manifest_count in (0, 1)
and not unexpected
and outer_total
== outer_code_mode + bootstrap_count + manifest_count
)
return True
return False
def _long_handoff_terminal_proven(summary: dict[str, Any], variant: str) -> bool:
if _tool_count(summary, variant, "cargo_test") != 1:
return False
pending = report._get_path(summary, "job_convergence.pending_handoff_count")
known_followups = report._get_path(summary, "job_convergence.pending_followup_known_count")
terminal_samples = report._get_path(summary, "job_convergence.pending_to_terminal_ms.samples")
if (
not isinstance(pending, int)
or isinstance(pending, bool)
or pending != 1
or not isinstance(known_followups, int)
or isinstance(known_followups, bool)
or known_followups < 1
or not isinstance(terminal_samples, int)
or isinstance(terminal_samples, bool)
or terminal_samples < 1
):
return False
if variant in ("direct", "host_code_mode"):
origin = "cargo_test"
return (
report._get_path(
summary, f"job_convergence.pending_handoff_by_origin_tool.{origin}"
)
== 1
and report._get_path(
summary, f"job_convergence.pending_followup_known_by_origin_tool.{origin}"
)
== 1
and report._get_path(
summary,
f"job_convergence.pending_to_terminal_ms_by_origin_tool.{origin}.samples",
)
== 1
and report._get_path(
summary, f"job_convergence.selected_terminal_by_origin_tool.{origin}"
)
== 1
)
if variant == "code_mode":
origin = "execute_effectful_code_mode"
return (
report._get_path(summary, "composition.job_handoffs.total") == 1
and report._get_path(summary, "composition.consequential_calls.total") == 1
and report._get_path(summary, "composition.known_results.total") == 0
and report._get_path(summary, "composition.outcome_unknown.total") == 0
and report._get_path(
summary, f"job_convergence.pending_handoff_by_origin_tool.{origin}"
)
== 1
and report._get_path(
summary, f"job_convergence.pending_followup_known_by_origin_tool.{origin}"
)
== 1
and report._get_path(
summary,
f"job_convergence.pending_to_terminal_ms_by_origin_tool.{origin}.samples",
)
== 1
and report._get_path(
summary, f"job_convergence.selected_terminal_by_origin_tool.{origin}"
)
== 1
)
return False
def _guarded_multi_file_contract_proven(summary: dict[str, Any], variant: str) -> bool:
edit_count = _tool_count(summary, variant, "edit_project_files")
read_count = _tool_count(summary, variant, "read_files")
search_counts = [
count
for name in ("search_project_texts", "search_and_read")
if (count := _tool_count(summary, variant, name)) is not None
]
outer_failed = report._get_path(summary, "outer_calls.failed")
outer_unknown = report._get_path(summary, "outer_calls.timeout_or_unknown")
if (
not isinstance(outer_failed, int)
or isinstance(outer_failed, bool)
or outer_failed != 0
or not isinstance(outer_unknown, int)
or isinstance(outer_unknown, bool)
or outer_unknown != 0
):
return False
if variant in ("direct", "host_code_mode"):
if report._get_path(summary, "availability.edit_outcomes.available") is not True:
return False
if report._get_path(
summary,
"edit_outcomes.by_tool.edit_project_files.applied",
) != 1:
return False
if variant == "code_mode":
child_failed = report._get_path(summary, "child_calls.failed")
consequential = report._get_path(summary, "composition.consequential_calls.total")
known_results = report._get_path(summary, "composition.known_results.total")
job_handoffs = report._get_path(summary, "composition.job_handoffs.total")
outcome_unknown = report._get_path(summary, "composition.outcome_unknown.total")
mutation_changed = report._get_path(
summary, "composition.mutation_state_changed.total"
)
mutation_no_change = report._get_path(
summary, "composition.mutation_no_change.total"
)
if (
not isinstance(child_failed, int)
or isinstance(child_failed, bool)
or child_failed != 0
or consequential != 1
or known_results != 1
or job_handoffs != 0
or outcome_unknown != 0
or mutation_changed != 1
or mutation_no_change != 0
):
return False
return (
edit_count == 1
and read_count is not None
and read_count >= 2
and sum(search_counts) >= 1
)
class _GenericCoordinator:
"""Own the fixture-side external write, never a runtime operation or receipt."""
def __init__(self, fixture: GenericFixture, directory: Path):
self.fixture, self.directory = fixture, directory
self.stop = threading.Event()
self.error = False
self.thread = None
def start(self):
self.directory.mkdir()
if self.fixture.case_id != "generic_stale_read_revision":
return
def coordinate():
try:
while not self.stop.wait(0.01):
if not self.fixture.external_written and (self.directory / "first-read").is_file():
self.fixture.append_external()
(self.directory / "external-written").write_text("ready\n")
if self.fixture.external_written and not self.fixture.rejection_checked and (self.directory / "stale-rejected").is_file():
self.fixture.check_rejected_bytes()
(self.directory / "rejection-checked").write_text("ready\n")
except (OSError, ValueError):
self.error = True
(self.directory / "coordination-failed").write_text("failed\n")
self.thread = threading.Thread(target=coordinate, name="fixture-stale-coordinator", daemon=True)
self.thread.start()
def close(self):
self.stop.set()
if self.thread is not None:
self.thread.join(timeout=2)
if self.thread.is_alive():
raise BenchmarkError("fixture coordinator did not stop")
def _generic_temporal_evidence_proven(case, summary, variant, evidence=None, fixture_identity=None):
if case["id"] not in temporal.RUNTIME_CASES:
return False
identity = (summary or {}).get("benchmark") or {}
return (isinstance(evidence, dict) and type(evidence.get("schema_version")) is int and evidence.get("schema_version") == temporal.PROOF_SCHEMA_VERSION
and isinstance(fixture_identity, str) and re.fullmatch(r"[0-9a-f]{64}", fixture_identity) is not None
and evidence.get("fixture_identity") == fixture_identity
and evidence.get("available") is True and evidence.get("passed") is True
and evidence.get("case_id") == case["id"]
and evidence.get("case_fingerprint") == report._case_fingerprint(case)
and evidence.get("base_revision") == identity.get("base_revision")
and isinstance(evidence.get("checks"), dict)
and set(evidence["checks"]) == temporal.CHECK_NAMES[case["id"]]
and all(value is True for value in evidence["checks"].values()))
def _run_sample(
repo: Path,
root: Path,
driver_argv: list[str],
case: dict[str, Any],
*,
variant: str,
pair_index: int,
ordinal: int,
base_revision: str,
case_manifest: Path,
host_cell_policy: str | None = None,
) -> dict[str, Any]:
if host_cell_policy is not None and (variant != "host_code_mode" or
host_cell_policy not in ("host_single_call", "host_composition_allowed")):
raise BenchmarkError("Host cell policy requires an explicit Host lane")
label = f"{case['id']}-p{pair_index + 1}-{ordinal + 1}-{variant}"
workspace = root / "worktrees" / label
receipt_path = root / "receipts" / f"{label}.json"
annotation_path = root / "annotations" / f"{label}.json"
receipt_path.unlink(missing_ok=True)
annotation_path.unlink(missing_ok=True)
surface: str | None = None
worktree_added = False
generic = case.get("target") == "generic_agent_disposable_fixture"
coordinator = None
fixture = None
fixture_token = None
capture_root = None
completed: subprocess.CompletedProcess[bytes] | None = None
try:
surface = _surface(case, variant)
if generic:
workspace.mkdir(parents=True)
fixture = GenericFixture(workspace, case["id"]).prepare()
fixture_token = temporal.fixture_identity(workspace)
coordinator = _GenericCoordinator(fixture, root / "receipts" / (label + "-coordination"))
coordinator.start()
else:
_worktree_add(repo, workspace, base_revision)
worktree_added = True
if _workspace_status(workspace):
raise BenchmarkError("fresh benchmark worktree is not clean")
env = dict(os.environ)
env.pop("WEBCODEX_BENCH_HOST_CELL_POLICY", None)
env.update(
{
"WEBCODEX_BENCH_WORKSPACE": str(workspace),
"WEBCODEX_BENCH_CASE_ID": case["id"],
"WEBCODEX_BENCH_VARIANT": variant,
"WEBCODEX_BENCH_EXPERIMENT": case.get("experiment", "forced_lanes"),
"WEBCODEX_BENCH_SURFACE": surface,
"WEBCODEX_BENCH_BASE_REVISION": base_revision,
"WEBCODEX_BENCH_CASE_FINGERPRINT": report._case_fingerprint(case),
"WEBCODEX_BENCH_PROMPT": case["prompt"],
"WEBCODEX_BENCH_DRIVER_RESULT": str(receipt_path),
}
)
if host_cell_policy is not None:
env["WEBCODEX_BENCH_HOST_CELL_POLICY"] = host_cell_policy
if generic:
env.update({"WEBCODEX_BENCH_TARGET": "generic_agent_disposable_fixture",
"WEBCODEX_BENCH_FIXTURE_COORDINATION": str(coordinator.directory),
"WEBCODEX_BENCH_FIXTURE_ENVIRONMENT": json.dumps({"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "TZ": "UTC", "PYTHONHASHSEED": "0", "PYTHONNOUSERSITE": "1"}),
"WEBCODEX_BENCH_FIXTURE_COMMAND": pressure_script() if case["id"] == "generic_failure_repair" else ""})
if case["id"] == "generic_pending_independent_join":
env["WEBCODEX_BENCH_FIXTURE_COMMAND"] = temporal.PENDING_SCRIPT
if case["id"] == "generic_mixed_files_conflict":
env["WEBCODEX_BENCH_FIXTURE_COMMAND"] = mixed_note_script()
if case["id"] == "generic_encoded_csv":
env["WEBCODEX_BENCH_FIXTURE_COMMAND"] = encoded_csv_script()
if case["id"] in temporal.RUNTIME_CASES:
capture_root = root / "receipts" / (label + "-capture")
temporal.prepare_capture(capture_root, case["id"], base_revision, report._case_fingerprint(case), fixture_root=workspace)
env["WEBCODEX_BENCH_TEMPORAL_TRACE_ROOT"] = str(capture_root)
env.update({"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "TZ": "UTC", "PYTHONHASHSEED": "0", "PYTHONNOUSERSITE": "1"})
env.pop("PYTHONPATH", None)
env.pop("PYTHONHOME", None)
started = time.time_ns() // 1_000_000
completed = _run_driver(driver_argv, cwd=workspace, env=env)
ended = time.time_ns() // 1_000_000
if not receipt_path.exists():
return {
"case_id": case["id"],
"variant": variant,
"surface": surface,
"status": "fail",
"driver_exit_code": completed.returncode,
"reason_code": "driver_receipt_missing",
"fixture_oracle": {"available": False, "passed": None, "checks": [], "reason": "driver receipt missing"},
"summary": None,
}
receipt = _load_driver_receipt(receipt_path)
if "task_timing" not in receipt:
receipt["task_timing"] = {"started_at_ms": started, "ended_at_ms": ended}
if coordinator is not None:
coordinator.close()
head_changed = not generic and _head_revision(workspace) != base_revision
oracle = fixture.oracle() if fixture is not None else _fixture_oracle(case, workspace, base_revision)
if coordinator is not None and coordinator.error:
oracle = {"available": True, "passed": False, "checks": [], "reason": "fixture coordination failed"}
if generic:
oracle["fixture_identity"] = fixture_token
annotation = _annotation(
case,
variant=variant,
surface=surface,
base_revision=base_revision,
receipt=receipt,
oracle=oracle,
)
annotation_path.write_text(_stable_json(annotation), encoding="utf-8")
summary = _summary_for_receipt(
case,
variant=variant,
surface=surface,
base_revision=base_revision,
receipt=receipt,
annotation_path=annotation_path,
case_manifest=case_manifest,
workspace=workspace,
)
temporal_evidence = None
if capture_root is not None and summary is not None:
audit_path = Path(receipt["audit_db"])
temporal_evidence = temporal.verify(
capture_root=capture_root, audit_db=audit_path if audit_path.is_absolute() else workspace / audit_path,
workflow_session_id=receipt["workflow_session_id"], case_id=case["id"],
base_revision=base_revision, fingerprint=report._case_fingerprint(case), fixture_root=workspace)
effective_status = receipt["status"]
reason_code: str | None = None
if head_changed:
effective_status = "fail"
reason_code = "workspace_head_changed"
if completed.returncode != 0 and effective_status in ("pass", "partial"):
effective_status = "fail"
if oracle["available"] and oracle["passed"] is not True and effective_status in ("pass", "partial"):
effective_status = "fail"
if (
(case.get("correctness") or {}).get("workspace_must_remain_clean") is True
and _workspace_status(workspace)
and effective_status in ("pass", "partial")
):
effective_status = "fail"
if summary is not None and effective_status == "pass":
correctness = summary.get("correctness") or {}
task_verdict = correctness.get("task_verdict")
validation_verdict = correctness.get("validation_verdict")
if task_verdict == "fail" or validation_verdict == "fail":
effective_status = "fail"
elif task_verdict != "pass":
effective_status = "partial"
elif case["validation"]["required"] and validation_verdict != "pass":
effective_status = "partial"
elif not case["validation"]["required"] and validation_verdict not in ("pass", "not_required"):
effective_status = "partial"
if (
summary is not None
and effective_status == "pass"
and not _runtime_evidence_proven(summary, variant, surface)
):
effective_status = "partial"
if (
case["id"] == "long_validation_handoff"
and summary is not None
and effective_status == "pass"
and not _long_handoff_terminal_proven(summary, variant)
):
effective_status = "partial"
if (
case["id"] == "guarded_multi_file_edit"
and summary is not None