File size: 61,967 Bytes
b48c9f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
#!/usr/bin/env python3
"""Run stepmold's example packs against one real model, in two arms, and write JSONL.

    STEPMOLD_API_KEY=... python3 bench.py \\
        --model 'openai:http://localhost:8000/v1#Qwen/Qwen2.5-7B-Instruct' --label qwen2.5-7b

Arm `stepmold` is `stepmold eval`, case by case: every gold case goes through
`stepmold.eval.evaluate` with the model behind a recorder that writes each request down.

Arm `plain` runs the same walker over a copy of the pack with the checks taken out, behind
an adapter that sends no grammar and keeps the first JSON object of each answer. This is
the "unverified arm" of stepmold's tests/production/test_longhorizon.py, pointed at a real
model. README.md lists every difference between the arms.

Which node and stage a request belongs to, and what stepmold decided about it, is read
from stepmold's own structured log events (`stepmold.log`), routed to the case-run that
emitted them by thread. Nothing in stepmold is patched.

Standard library only. Python 3.9 or newer.
"""

import argparse
import dataclasses
import datetime
import hashlib
import importlib
import importlib.util
import json
import logging
import os
import platform
import re
import subprocess
import sys
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from types import SimpleNamespace

BENCH_VERSION = "0.1.0"
# `plain_schema` is opt-in: the plain arm plus the node's schema written into the answer
# prompt, the way stepmold's own json_object grammar mode writes it. See README.md.
ARMS = ("stepmold", "plain", "plain_schema")
DEFAULT_ARMS = "stepmold,plain"
STEPMOLD_GIT = "https://gitlab.com/ahkamboh/stepmold"
DEFAULT_STEPMOLD = os.path.join(os.path.expanduser("~"), "Documents", "GitHub", "stepmold")

# The host tools an example pack needs, relative to its own directory. A pack only names
# its actions (stepmold.tools); the host decides what those names run. For the shipped
# examples the bench is the host, so it says so here. `--tools PACK=SPEC` overrides.
PACK_TOOLS = {"refund_desk": "tools.py:registry"}

# The schema a plain-arm generate node is verified against: "is an object". The adapter
# always hands back an object, so verification never rejects anything in that arm. It is
# truthy on purpose: stepmold's codegen passes a truthy grammar to the answer call and
# None to the think call, which is how the adapter tells the two apart. It is never sent.
PLAIN_GRAMMAR = {"type": "object"}

# Request fields the bench will not take through --extra-body, and why.
REFUSED_EXTRA_BODY = {
    "model": "the model comes from --model",
    "messages": "the prompt is the pack's, rendered by stepmold",
    "max_tokens": "every node sets its own budget; use --reasoning-reserve for headroom",
    "seed": "stepmold varies the seed per re-sample and per gate draw; a fixed seed would "
            "make every draw the same request",
    "n": "stepmold reads one choice per request",
    "stream": "the backend reads one JSON body per request",
}
# Constrained decoding belongs to the stepmold arm's --grammar-mode. Sent through
# --extra-body it would constrain the plain arm too.
CONSTRAINT_KEYS = ("response_format", "json_schema", "grammar", "guided_json", "guided_regex",
                   "guided_choice", "guided_grammar", "guided_decoding_backend",
                   "structured_outputs")


class BenchError(Exception):
    """A setup problem the operator has to fix. Printed, never a traceback."""


# --------------------------------------------------------------------------- stepmold


_SM = None


def load_stepmold(path=None):
    """Import stepmold once: from `path` when given, else whatever is installed.

    Returns a namespace of the stepmold modules the bench uses. Bytecode writing is
    turned off first, so running the bench leaves a stepmold checkout byte-for-byte as it
    was.
    """
    global _SM
    if _SM is not None:
        return _SM
    sys.dont_write_bytecode = True
    root = None
    if path:
        root = os.path.abspath(os.path.expanduser(path))
        if not os.path.isfile(os.path.join(root, "stepmold", "__init__.py")):
            raise BenchError("--stepmold %s: there is no stepmold/__init__.py there" % root)
        if root not in sys.path:
            sys.path.insert(0, root)
    try:
        package = importlib.import_module("stepmold")
    except ImportError:
        raise BenchError(
            "stepmold is not importable. Pass --stepmold PATH to a checkout, or "
            "pip install git+%s" % STEPMOLD_GIT
        )
    where = os.path.dirname(os.path.abspath(package.__file__))
    if root and not where.startswith(root + os.sep):
        raise BenchError(
            "stepmold was already imported from %s, not from --stepmold %s" % (where, root)
        )
    names = ("errors", "eval", "graph", "verify", "codegen", "grammar", "pack", "cli",
             "log", "model")
    modules = {name: importlib.import_module("stepmold." + name) for name in names}
    modules["openai"] = importlib.import_module("stepmold.backends.openai_compat")
    _SM = SimpleNamespace(package=package, root=os.path.dirname(where), **modules)
    return _SM


def stepmold_provenance(sm):
    """Which stepmold produced these numbers: version, commit, and where it came from."""
    info = {"version": getattr(sm.package, "__version__", None), "path": sm.root,
            "commit": None, "dirty": None, "source": "checkout"}
    if os.path.isdir(os.path.join(sm.root, ".git")):
        info["commit"] = _git(sm.root, "rev-parse", "HEAD")
        status = _git(sm.root, "status", "--porcelain", "--untracked-files=no")
        info["dirty"] = None if status is None else bool(status)
        return info
    info["source"] = "installed"
    try:
        from importlib import metadata
        direct = json.loads(metadata.distribution("stepmold").read_text("direct_url.json")
                            or "{}")
        info["commit"] = (direct.get("vcs_info") or {}).get("commit_id")
        info["url"] = direct.get("url")
    except Exception:
        pass
    return info


def _git(root, *args):
    try:
        out = subprocess.run(("git", "-C", root) + args, capture_output=True, text=True,
                             timeout=10)
    except (OSError, subprocess.SubprocessError):
        return None
    return out.stdout.strip() if out.returncode == 0 else None


# ------------------------------------------------------------------- lenient parsing


def _refuse_constant(name):
    raise ValueError("%s is not JSON" % name)


_DECODER = json.JSONDecoder(parse_constant=_refuse_constant)


def first_json_object(text):
    """The first JSON object in `text`, reading left to right, or None.

    Lenient about where the object is (prose before it, a code fence, text after it),
    strict about what it is: standard JSON, no NaN or Infinity. A `{` that does not
    start a valid object is skipped and the search moves on.

    This is the opposite end from stepmold's own `verify.extract_json`, which takes the
    last object on purpose. The plain arm is the pipeline people write first.
    """
    if not isinstance(text, str):
        return None
    index = text.find("{")
    while index != -1:
        try:
            value, _ = _DECODER.raw_decode(text, index)
        except (ValueError, RecursionError):
            value = None
        if isinstance(value, dict):
            return value
        index = text.find("{", index + 1)
    return None


# ------------------------------------------------------------------------- recording


_LOCAL = threading.local()


def _current():
    return getattr(_LOCAL, "recorder", None)


def _now():
    return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")


def _sha(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]


class Recorder:
    """What one case-run leaves behind: its requests, and what stepmold said about them.

    Requests are written down by the model wrappers below. Everything else (which node
    and stage a request served, rungs, gate draws, rejections, the path, the escalation
    edges, the end node) comes from stepmold's own log events, delivered here by
    `EventRouter` because the case-run's thread emitted them.
    """

    def __init__(self, stamp, pack, sm, record_prompts=False, record_reasoning=False):
        self.stamp = stamp
        self.pack = pack                # the ORIGINAL pack: grammars, asserts, node types
        self.sm = sm
        self.record_prompts = record_prompts
        self.record_reasoning = record_reasoning
        self.arm = stamp["arm"]
        self.calls = []
        self.path = []
        self.escalations = []
        self.gates = []
        self.retries = 0
        self.end_node = None
        self.steps = None
        self.generations = None
        self.run_error = None
        self._stage = None
        self._node = None
        self._corrected = False
        self._rung = 0
        self._draw = 0
        self._failed = None
        self._http_attempt = None
        self._http_errors = 0
        self._started = None

    # ---------------------------------------------------------------- stepmold events

    def on_event(self, name, fields):
        node = fields.get("node")
        if name == "node.think":
            self._stage, self._node, self._corrected = "think", node, False
        elif name == "node.emit":
            self._stage, self._node = "answer", node
            self._corrected = bool(fields.get("corrected"))
        elif name == "node.retry":
            self.retries += 1
            self._rung = max(0, int(fields.get("attempt") or 1) - 1)
        elif name == "node.rejected":
            self._rejected(fields)
        elif name == "node.sample":
            self._draw = int(fields.get("draw") or 0)
            self._rung = 0
        elif name in ("node.agreed", "node.unsure"):
            self.gates.append({
                "node": node, "outcome": name.split(".")[1],
                "agreed": fields.get("agreed"), "drawn": fields.get("of"),
                "required": fields.get("required"), "asked": fields.get("asked"),
                "distinct": fields.get("distinct"), "generations": fields.get("generations"),
            })
        elif name == "node.ok":
            self.path.append(node)
            self._reset()
        elif name == "node.failed":
            self.path.append(node)
            self._failed = dict(fields)
            self._reset()
        elif name == "node.assert":
            self.path.append(node)
            if not fields.get("passed"):
                # An assert node with an `on_fail` diverts here. One without raises
                # instead and leaves `node.failed`, not this event.
                self.escalations.append({
                    "node": node, "node_type": "assert", "edge": "on_fail",
                    "to": fields.get("to"), "error": "assert",
                    "reason": "expr was false or could not be evaluated: %s"
                              % fields.get("expr"),
                })
        elif name in ("edge.on_fail", "edge.on_unsure"):
            failed = self._failed if (self._failed or {}).get("node") == node else {}
            target = self.pack.nodes.get(node)
            self.escalations.append({
                "node": node, "node_type": getattr(target, "type", None),
                "edge": name.split(".")[1], "to": fields.get("to"),
                "error": failed.get("error"), "reason": failed.get("reason"),
            })
        elif name == "run.end":
            self.end_node = fields.get("end_node")
            self.path.append(self.end_node)
            self.steps = fields.get("steps")
            self.generations = fields.get("generations")
        elif name == "run.error":
            self.run_error = {"node": node, "error": fields.get("error"),
                              "reason": fields.get("reason")}
        elif name == "backend.response":
            self._http_attempt = fields.get("attempt")
        elif name in ("backend.http_error", "backend.transport_error"):
            self._http_errors += 1

    def _reset(self):
        self._stage = self._node = None
        self._rung = self._draw = 0
        self._corrected = False

    def _rejected(self, fields):
        """stepmold refused the request just made. It is always the latest one."""
        if not self.calls:
            return
        call = self.calls[-1]
        call["accepted"] = False
        call["reject_reason"] = fields.get("reason")
        if fields.get("cause") == "empty_completion":
            call["reject_kind"] = "empty"
        elif not call.get("parsed_ok"):
            call["reject_kind"] = "parse"
        elif call.get("schema_ok") is False:
            call["reject_kind"] = "schema"
        else:
            call["reject_kind"] = "assert"

    # ---------------------------------------------------------------------- requests

    def start_call(self, prompt, grammar_sent, max_tokens, temperature=None, seed=None):
        # The stage normally comes from the event stepmold emits just before the call.
        # Without one, a grammar on the call is the only other sign of an answer call.
        stage = self._stage or ("answer" if grammar_sent else "think")
        call = {"kind": "call"}
        call.update(self.stamp)
        call.update({
            "seq": len(self.calls), "node": self._node, "stage": stage,
            "attempt": self._rung + 1, "draw": self._draw + 1,
            "corrected": bool(self._corrected) if stage == "answer" else False,
            "grammar_sent": bool(grammar_sent), "max_tokens": max_tokens,
            "temperature": temperature, "seed": seed,
            "prompt_sha256": _sha(prompt or ""), "prompt_chars": len(prompt or ""),
            "timestamp": _now(),
        })
        if self.record_prompts:
            call["prompt"] = prompt
        self._stage = None
        self._http_attempt = None
        self._http_errors = 0
        self.calls.append(call)
        return call

    def end_call(self, call, started, text=None, response=None, error=None):
        call["latency_ms"] = round((time.monotonic() - started) * 1000.0, 1)
        if self._http_attempt is not None:
            call["http_attempts"] = self._http_attempt
        elif response is not None or self._http_errors:
            call["http_attempts"] = self._http_errors + (1 if response is not None else 0)
        else:
            call["http_attempts"] = None
        usage, choice, message = {}, {}, {}
        if isinstance(response, dict):
            usage = response.get("usage") or {}
            choices = response.get("choices") or []
            choice = choices[0] if choices and isinstance(choices[0], dict) else {}
            message = choice.get("message") or {}
        details = usage.get("completion_tokens_details") or {}
        reasoning = message.get("reasoning") or message.get("reasoning_content")
        call.update({
            "prompt_tokens": usage.get("prompt_tokens"),
            "completion_tokens": usage.get("completion_tokens"),
            "reasoning_tokens": details.get("reasoning_tokens"),
            "total_tokens": usage.get("total_tokens"),
            "finish_reason": choice.get("finish_reason"),
            "output": text,
            "output_chars": len(text) if isinstance(text, str) else None,
            "reasoning_chars": len(reasoning) if isinstance(reasoning, str) else None,
            "parsed_ok": None, "schema_ok": None, "assert_ok": None, "accepted": None,
            "reject_kind": None, "reject_reason": None, "error": None,
        })
        if self.record_reasoning:
            call["reasoning"] = reasoning if isinstance(reasoning, str) else None
        if error is not None:
            call["error"] = "%s: %s" % (type(error).__name__, _clip(str(error), 500))
        if call["stage"] == "answer" and self.arm == "stepmold":
            # The first two of stepmold's three checks, run with stepmold's own functions
            # on the text it is about to verify. The verdict that counts arrives as an
            # event (`node.rejected`); these say which check a rejection came from.
            value = None
            parsed = False
            if isinstance(text, str):
                try:
                    value = self.sm.verify.extract_json(text)
                    parsed = isinstance(value, dict)
                except Exception:
                    parsed = False
            call["parsed_ok"] = parsed
            if parsed:
                call["schema_ok"] = self._schema_ok(call["node"], value)

    def plain_answer(self, value, empty):
        """The plain adapter's verdict on the answer it just read. Nothing is rejected."""
        if not self.calls:
            return
        call = self.calls[-1]
        call["parsed_ok"] = value is not None
        call["accepted"] = value is not None
        if value is None:
            call["reject_kind"] = "empty" if empty else "parse"
            call["reject_reason"] = ("the reply was empty; nothing committed" if empty
                                     else "no JSON object in the reply; nothing committed")
        else:
            # Diagnostic only: what stepmold's schema check would have said. The plain
            # arm commits the object either way.
            call["schema_ok"] = self._schema_ok(call.get("node"), value)

    def _schema_ok(self, node_name, value):
        node = self.pack.nodes.get(node_name)
        if node is None:
            return None
        try:
            self.sm.grammar.validate_against(node.grammar or {}, value)
        except self.sm.grammar.ValidationError:
            return False
        except Exception:
            return None
        return True

    def finalize(self):
        """Settle every verdict that no event contradicted."""
        for call in self.calls:
            if call.get("stage") != "answer" or self.arm != "stepmold":
                continue
            if call.get("accepted") is None and not call.get("error"):
                call["accepted"] = True
            node = self.pack.nodes.get(call.get("node"))
            if call.get("parsed_ok") and call.get("schema_ok") and node is not None \
                    and node.assert_expr:
                call["assert_ok"] = call.get("reject_kind") != "assert"


def _clip(text, limit):
    text = " ".join(str(text).split())
    return text if len(text) <= limit else text[:limit] + "..."


class EventRouter(logging.Handler):
    """Hands each stepmold log event to the recorder of the thread that emitted it."""

    def __init__(self, event_attr, fields_attr):
        logging.Handler.__init__(self, level=logging.DEBUG)
        self.event_attr = event_attr
        self.fields_attr = fields_attr

    def emit(self, record):
        recorder = _current()
        if recorder is None:
            return
        name = getattr(record, self.event_attr, None)
        if name is None:
            return
        try:
            recorder.on_event(name, getattr(record, self.fields_attr, None) or {})
        except Exception:
            # Bookkeeping must never change the run it is watching.
            pass


class capture_events(object):
    """Route stepmold's events to recorders while the block runs, then put logging back.

    stepmold logs nothing unless asked (rule 1 of `stepmold.log`), so the package logger
    is set to DEBUG here, which is what makes `node.think` and `node.emit` fire. It stops
    propagating meanwhile, so a host that configured the root logger is not flooded.
    """

    def __init__(self, sm):
        self.sm = sm
        self.logger = logging.getLogger(sm.log.ROOT)
        self.handler = EventRouter(getattr(sm.log, "EVENT_ATTR", "stepmold_event"),
                                   getattr(sm.log, "FIELDS_ATTR", "stepmold_fields"))

    def __enter__(self):
        self.saved = (self.logger.level, self.logger.propagate)
        self.logger.addHandler(self.handler)
        self.logger.setLevel(logging.DEBUG)
        self.logger.propagate = False
        return self

    def __exit__(self, *exc):
        self.logger.removeHandler(self.handler)
        self.logger.setLevel(self.saved[0])
        self.logger.propagate = self.saved[1]
        return False


# --------------------------------------------------------------------------- models


_BACKEND = {}


def backend_class(sm):
    """stepmold's OpenAICompatModel with one change: each request is written down.

    `generate` here is the parent's two lines (build the payload, post it, read the
    content) with a recorder around them, so the request on the wire is byte-for-byte
    the one stepmold would send. The signature keeps `sampling`, so stepmold still sends
    its re-sample and gate-draw hints.
    """
    if "class" in _BACKEND:
        return _BACKEND["class"]
    base = sm.openai.OpenAICompatModel
    content_of = sm.openai._content

    class BenchBackend(base):
        def generate(self, prompt, grammar=None, max_tokens=512, sampling=None):
            payload = self.build_payload(prompt, grammar, max_tokens, sampling=sampling)
            recorder = _current()
            call = None
            if recorder is not None:
                messages = payload.get("messages") or [{}]
                call = recorder.start_call(
                    messages[0].get("content"),
                    grammar_sent=any(key in payload for key in CONSTRAINT_KEYS),
                    max_tokens=payload.get("max_tokens"),
                    temperature=payload.get("temperature"), seed=payload.get("seed"))
            started = time.monotonic()
            response = None
            try:
                response = self._post(payload)
                text = content_of(response)
            except BaseException as exc:
                if call is not None:
                    recorder.end_call(call, started, response=response, error=exc)
                raise
            if call is not None:
                recorder.end_call(call, started, text=text, response=response)
            return text

    _BACKEND["class"] = BenchBackend
    return BenchBackend


class RecordingModel(object):
    """A transparent recorder around a model without a `sampling` keyword (FakeModel)."""

    def __init__(self, inner):
        self.inner = inner

    def generate(self, prompt, grammar=None, max_tokens=512):
        return _recorded(self.inner, prompt, grammar, max_tokens, None)


class RecordingSampledModel(RecordingModel):
    """The same, for a model that takes stepmold's per-call sampling hint."""

    def generate(self, prompt, grammar=None, max_tokens=512, sampling=None):
        return _recorded(self.inner, prompt, grammar, max_tokens, sampling)


def _recorded(inner, prompt, grammar, max_tokens, sampling):
    recorder = _current()
    call = None
    if recorder is not None:
        call = recorder.start_call(
            prompt, grammar_sent=grammar is not None, max_tokens=max_tokens,
            temperature=getattr(sampling, "temperature", None),
            seed=getattr(sampling, "seed", None))
    started = time.monotonic()
    try:
        if sampling is None:
            text = inner.generate(prompt, grammar=grammar, max_tokens=max_tokens)
        else:
            text = inner.generate(prompt, grammar=grammar, max_tokens=max_tokens,
                                  sampling=sampling)
    except BaseException as exc:
        if call is not None:
            recorder.end_call(call, started, error=exc)
        raise
    if call is not None:
        recorder.end_call(call, started, text=text)
    return text


def recording(model, sm):
    if sm.codegen.accepts_sampling(model):
        return RecordingSampledModel(model)
    return RecordingModel(model)


class PlainModel(object):
    """The plain arm's model: no grammar, one draw, and the first JSON object wins.

    stepmold's walker calls this exactly as it calls any model. The think call arrives
    with grammar None and its text goes back untouched (an empty one becomes empty
    notes). The answer call arrives with the plain pack's permissive grammar, which is
    dropped: the request goes out with grammar None. Its reply is reduced to its first
    JSON object, re-serialised, so stepmold's verify (which checks only "is an object" in
    the plain pack) accepts it. A reply with no JSON object becomes `{}`, which commits
    nothing, so the walk goes on with whatever state it has.

    No `sampling` keyword: the plain pack never re-samples and never draws twice, so
    stepmold never has a hint to send.

    With `schema_hint` (the plain_schema arm), the answer prompt also gets the node's
    real schema appended, in the words stepmold's json_object grammar mode uses. The
    text is built by stepmold's own backend (`build_payload` in json_object mode), so it
    is exactly what stepmold would add, and nothing is sent but the text.
    """

    def __init__(self, inner, sm, schema_hint=False):
        self.inner = inner
        self.sm = sm
        self.schema_hint = schema_hint

    def _hinted(self, prompt):
        recorder = _current()
        node = recorder.pack.nodes.get(recorder._node) if recorder is not None else None
        if node is None or not node.grammar:
            # Without the node there is no schema to show, and an unhinted call would
            # quietly turn this arm into the plain one. Not a result: an infra error.
            raise BenchError("plain_schema: could not tell which node this answer is for")
        writer = _hint_writer(self.sm)
        grammar = self.sm.grammar.schema_to_grammar(node.grammar)
        return writer.build_payload(prompt, grammar, 1)["messages"][0]["content"]

    def generate(self, prompt, grammar=None, max_tokens=512):
        answer = grammar is not None
        empty = False
        if answer and self.schema_hint:
            prompt = self._hinted(prompt)
        try:
            text = self.inner.generate(prompt, grammar=None, max_tokens=max_tokens)
        except self.sm.errors.BackendError as exc:
            if not getattr(exc, "empty_content", False):
                raise
            text, empty = None, True
        if not answer:
            return text if isinstance(text, str) else ""
        value = first_json_object(text)
        recorder = _current()
        if recorder is not None:
            recorder.plain_answer(value, empty)
        return json.dumps(value) if value is not None else "{}"


_HINT = {}


def _hint_writer(sm):
    """An OpenAICompatModel in json_object mode, used only to write stepmold's schema text.

    Constructing one performs no IO, and only `build_payload` is ever called on it.
    """
    if "writer" not in _HINT:
        _HINT["writer"] = sm.openai.OpenAICompatModel(
            base_url="http://unused.invalid/v1", model="unused", api_key="",
            grammar_mode="json_object")
    return _HINT["writer"]


def plain_pack(pack):
    """The pack the plain arm walks: same graph, prompts and edges, no checks.

    Every generate node loses its schema (replaced by PLAIN_GRAMMAR), its `assert:`, its
    retries, its gate (`samples`/`agree`) and its `on_fail`/`on_unsure` edges, which
    only the retry ladder and the gate can take. `two_stage`, both prompts, `max_tokens`
    and `output` stay. Tool, assert and end nodes, the edges and `max_steps` are
    untouched.
    """
    nodes = {}
    for name, node in pack.nodes.items():
        if node.type == "generate":
            node = dataclasses.replace(
                node, grammar=dict(PLAIN_GRAMMAR), assert_expr=None, retries=0,
                samples=None, agree=None, on_fail=None, on_unsure=None)
        nodes[name] = node
    return dataclasses.replace(pack, nodes=nodes)


# ----------------------------------------------------------------------- model specs


def parse_model_spec(spec, grammar_modes):
    """Read a model spec the way `stepmold.cli.resolve_model` does.

        openai:<base_url>#<model>[#<grammar_mode>[#<reasoning_reserve>]]
        fake:<path>        a scripted FakeModel, resolved inside each pack
    """
    scheme, _, rest = (spec or "").partition(":")
    if scheme == "fake":
        if not rest:
            raise BenchError("fake: needs a script path, e.g. fake:fakes/script.json")
        return SimpleNamespace(scheme="fake", spec=spec, model=spec, base_url=None,
                               grammar_mode=None, reasoning_reserve=None)
    if scheme != "openai":
        raise BenchError("--model: unknown scheme %r (known: openai, fake)" % scheme)
    parts = rest.split("#")
    base_url = parts[0].strip()
    name = parts[1].strip() if len(parts) > 1 else ""
    if not base_url or not name:
        raise BenchError("--model: openai: needs a base url and a model name, e.g. "
                         "openai:http://localhost:8000/v1#Qwen/Qwen2.5-7B-Instruct")
    mode = parts[2].strip() if len(parts) > 2 and parts[2].strip() else None
    if mode is not None and mode not in grammar_modes:
        raise BenchError("--model: unknown grammar mode %r (known: %s)"
                         % (mode, ", ".join(grammar_modes)))
    reserve = None
    if len(parts) > 3 and parts[3].strip():
        try:
            reserve = int(parts[3].strip())
        except ValueError:
            raise BenchError("--model: reasoning reserve must be an integer, got %r"
                             % parts[3].strip())
    return SimpleNamespace(scheme="openai", spec=spec, model=name, base_url=base_url,
                           grammar_mode=mode, reasoning_reserve=reserve)


def _settle(flag_value, spec_value, default, what):
    if flag_value is not None and spec_value is not None and flag_value != spec_value:
        raise BenchError("--%s %r disagrees with the %s in --model (%r); give one"
                         % (what, flag_value, what.replace("-", " "), spec_value))
    if flag_value is not None:
        return flag_value
    return spec_value if spec_value is not None else default


def parse_extra_body(text):
    """--extra-body as a dict, with `temperature` split out (see README)."""
    if not text:
        return {}, None
    try:
        body = json.loads(text)
    except ValueError as exc:
        raise BenchError("--extra-body is not valid JSON (%s)" % exc)
    if not isinstance(body, dict):
        raise BenchError("--extra-body must be a JSON object")
    for key in sorted(body):
        if key in REFUSED_EXTRA_BODY:
            raise BenchError("--extra-body may not set %r: %s" % (key, REFUSED_EXTRA_BODY[key]))
        if key in CONSTRAINT_KEYS:
            raise BenchError(
                "--extra-body may not set %r: constrained decoding is the stepmold arm's "
                "--grammar-mode, and through --extra-body it would constrain the plain arm "
                "too" % key)
    temperature = body.pop("temperature", None)
    if temperature is not None and (isinstance(temperature, bool)
                                    or not isinstance(temperature, (int, float))):
        raise BenchError("--extra-body temperature must be a number")
    return body, temperature


# --------------------------------------------------------------------------- records


def case_key(record):
    return (record.get("label"), record.get("arm"), record.get("pack"), record.get("case"),
            record.get("run"))


def read_records(path):
    """Every well-formed record in a JSONL file. A torn last line is skipped."""
    if not os.path.exists(path):
        return
    with open(path, "r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            try:
                record = json.loads(line)
            except ValueError:
                continue
            if isinstance(record, dict):
                yield record


def _jsonable(value):
    if isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))):
        return repr(value)
    if isinstance(value, dict):
        return dict((str(key), _jsonable(item)) for key, item in value.items())
    if isinstance(value, (list, tuple)):
        return [_jsonable(item) for item in value]
    return value


def dumps(record):
    try:
        return json.dumps(record, ensure_ascii=False, allow_nan=False, default=str)
    except ValueError:
        return json.dumps(_jsonable(record), ensure_ascii=False, allow_nan=False,
                          default=str)


class JsonlWriter(object):
    """Appends whole case-runs to the results file, one locked write each."""

    def __init__(self, path, secret=None):
        self.path = path
        # Belt and braces: no record carries the key, and if one ever did it is cut out
        # here. Too short a string would match ordinary text, so only a real key counts.
        self.secret = secret if secret and len(secret) >= 8 else None
        self.lock = threading.Lock()
        parent = os.path.dirname(os.path.abspath(path))
        os.makedirs(parent, exist_ok=True)
        # A run killed mid-write can leave a torn last line. Start ours on a fresh one.
        if os.path.exists(path) and os.path.getsize(path):
            with open(path, "rb") as handle:
                handle.seek(-1, os.SEEK_END)
                torn = handle.read(1) != b"\n"
            if torn:
                with open(path, "a", encoding="utf-8") as handle:
                    handle.write("\n")
        self.handle = open(path, "a", encoding="utf-8")

    def write(self, records):
        text = "".join(dumps(record) + "\n" for record in records)
        if self.secret and self.secret in text:
            text = text.replace(self.secret, "<redacted>")
        with self.lock:
            self.handle.write(text)
            self.handle.flush()
            try:
                os.fsync(self.handle.fileno())
            except OSError:
                pass

    def close(self):
        self.handle.close()


def _sum(calls, key):
    values = [call.get(key) for call in calls if isinstance(call.get(key), (int, float))]
    return sum(values) if values else None


def pack_digest(path):
    """A fingerprint of a pack's files, so a result names exactly what it ran."""
    digest = hashlib.sha256()
    for folder, dirs, files in os.walk(path):
        dirs[:] = sorted(d for d in dirs if d != "__pycache__")
        for name in sorted(files):
            if name.endswith(".pyc"):
                continue
            full = os.path.join(folder, name)
            digest.update(os.path.relpath(full, path).encode("utf-8") + b"\0")
            with open(full, "rb") as handle:
                digest.update(handle.read())
            digest.update(b"\0")
    return digest.hexdigest()[:16]


def load_tools(spec):
    """Execute a host tools file afresh and return its registry.

    Fresh every time on purpose: refund_desk's registry closes over an order store that
    remembers refunds, and a second refund of the same order raises. Each case-run gets
    its own store, so no case-run can see another's side effects.
    """
    target, _, attribute = spec.partition(":")
    full = os.path.abspath(target)
    if not os.path.isfile(full):
        raise BenchError("tools: no such file %s" % full)
    module_spec = importlib.util.spec_from_file_location(
        "_bench_tools_%s" % uuid.uuid4().hex[:12], full)
    module = importlib.util.module_from_spec(module_spec)
    module_spec.loader.exec_module(module)
    names = [attribute] if attribute else ["registry", "REGISTRY"]
    for name in names:
        found = getattr(module, name, None)
        if found is not None:
            if callable(found) and not hasattr(found, "get"):
                found = found()
            return found
    raise BenchError("tools: %s defines none of %s" % (full, ", ".join(names)))


# ------------------------------------------------------------------------------ bench


class Bench(object):
    def __init__(self, args, sm, opener=None, sleeper=None, stream=None):
        self.args = args
        self.sm = sm
        self.opener = opener
        self.sleeper = sleeper
        self.stream = stream or sys.stderr
        self.print_lock = threading.Lock()
        self.stop = threading.Event()

        modes = tuple(sm.openai.GRAMMAR_MODES)
        self.spec = parse_model_spec(args.model, modes)
        self.grammar_mode = _settle(args.grammar_mode, self.spec.grammar_mode,
                                    "response_format", "grammar-mode")
        if self.grammar_mode not in modes:
            raise BenchError("--grammar-mode %r is not one of %s"
                             % (self.grammar_mode, ", ".join(modes)))
        self.reasoning_reserve = _settle(args.reasoning_reserve, self.spec.reasoning_reserve,
                                         0, "reasoning-reserve")
        self.extra_body, self.temperature = parse_extra_body(args.extra_body)
        if self.temperature is None:
            self.temperature = 0.0
        self.arms = [arm.strip() for arm in args.arms.split(",") if arm.strip()]
        unknown = [arm for arm in self.arms if arm not in ARMS]
        if unknown or not self.arms:
            raise BenchError("--arms: unknown arm(s) %s (known: %s)"
                             % (", ".join(unknown) or "none given", ", ".join(ARMS)))
        if args.runs < 1 or args.concurrency < 1:
            raise BenchError("--runs and --concurrency must be at least 1")
        self.api_key = os.environ.get("STEPMOLD_API_KEY") or ""
        default_label = "fake" if self.spec.scheme == "fake" else self.spec.model.split("/")[-1]
        self.label = args.label or re.sub(r"[^A-Za-z0-9._-]+", "_", default_label).strip("_")
        if not self.label:
            raise BenchError("--label is required for this model spec")
        self.out = args.out or os.path.join(
            "results", re.sub(r"[^A-Za-z0-9._-]+", "_", self.label) + ".jsonl")

        self.examples = self._examples_dir(args.examples)
        self.packs = self._load_packs(args.packs, args.tools or [])
        if self.spec.scheme == "openai":
            # Built once now so a bad --extra-body or grammar mode fails before any request.
            for arm in self.arms:
                self._backend(arm)
        self.jobs = self._plan(args.limit, args.runs)

    # ---------------------------------------------------------------------- setup

    def _examples_dir(self, given):
        candidates = [given] if given else [os.path.join(self.sm.root, "examples")]
        for candidate in candidates:
            if candidate and os.path.isdir(candidate):
                return os.path.abspath(candidate)
        raise BenchError(
            "no example packs at %s. pip install does not ship examples/; clone %s and "
            "pass --stepmold (or --examples) pointing at the clone"
            % (candidates[0], STEPMOLD_GIT))

    def _load_packs(self, packs_arg, tools_args):
        available = sorted(
            name for name in os.listdir(self.examples)
            if os.path.isfile(os.path.join(self.examples, name, "manifest.yaml")))
        if packs_arg in (None, "", "all"):
            chosen = available
        else:
            chosen = [name.strip() for name in packs_arg.split(",") if name.strip()]
            missing = [name for name in chosen if name not in available]
            if missing:
                raise BenchError("--packs: no pack %s in %s (have: %s)"
                                 % (", ".join(missing), self.examples, ", ".join(available)))
        overrides = {}
        for item in tools_args:
            name, sep, spec = item.partition("=")
            if not sep or not spec:
                raise BenchError("--tools takes PACK=FILE.py[:ATTR], got %r" % item)
            overrides[name.strip()] = spec.strip()
        packs = {}
        for name in chosen:
            path = os.path.join(self.examples, name)
            tools_spec = overrides.get(name)
            if tools_spec is None and name in PACK_TOOLS:
                target, _, attribute = PACK_TOOLS[name].partition(":")
                tools_spec = os.path.join(path, target) + (":" + attribute if attribute else "")
            try:
                registry = load_tools(tools_spec) if tools_spec else None
                pack = self.sm.pack.load_pack(path, tools=registry)
                checker = getattr(self.sm.cli, "_check_output_shapes", None)
                if checker is not None:
                    checker(pack)
            except BenchError:
                raise
            except Exception as exc:
                raise BenchError("pack %s does not load: %s: %s"
                                 % (name, type(exc).__name__, exc))
            if registry is None and any(n.type == "tool" for n in pack.nodes.values()):
                raise BenchError("pack %s has tool nodes; pass --tools %s=FILE.py[:ATTR]"
                                 % (name, name))
            if not pack.evalset:
                raise BenchError("pack %s has no evalset cases" % name)
            packs[name] = SimpleNamespace(name=pack.name, dir=name, path=path, pack=pack,
                                          plain=plain_pack(pack), tools=tools_spec,
                                          digest=pack_digest(path))
        return packs

    def _plan(self, limit, runs):
        jobs = []
        for run in range(1, runs + 1):
            for name in sorted(self.packs):
                entry = self.packs[name]
                cases = list(entry.pack.evalset)
                if limit:
                    cases = cases[:limit]
                seen = {}
                for index, case in enumerate(cases, start=1):
                    label = case.name or "case %d" % index
                    seen[label] = seen.get(label, 0) + 1
                    if seen[label] > 1:  # names are the resume key, so keep them unique
                        label = "%s #%d" % (label, index)
                    for arm in self.arms:
                        jobs.append(SimpleNamespace(arm=arm, pack=name, case=case,
                                                    case_name=label, case_index=index,
                                                    run=run, done=False))
        return jobs

    def setup(self):
        """What has to stay fixed for results to be resumed into the same label."""
        return {
            "model": self.spec.model, "base_url": self.spec.base_url,
            "scheme": self.spec.scheme, "grammar_mode": self.grammar_mode,
            "reasoning_reserve": self.reasoning_reserve, "temperature": self.temperature,
            "extra_body": self.extra_body, "stepmold_version": self.provenance.get("version"),
            "stepmold_commit": self.provenance.get("commit"),
        }

    def pack_digests(self):
        return dict((entry.name, entry.digest) for entry in self.packs.values())

    def _check_resume(self):
        """Refuse to mix results from two different setups under one label.

        More packs, more runs or another --limit may be added to a label later. A
        different model, grammar mode, extra body, reserve, temperature, stepmold commit,
        or a pack whose files changed, may not.
        """
        if self.args.allow_config_change:
            return
        setup, digests = self.setup(), self.pack_digests()
        for record in read_records(self.out):
            if record.get("kind") != "run" or record.get("label") != self.label:
                continue
            changed = [key for key in sorted(setup)
                       if (record.get("setup") or {}).get(key) != setup[key]]
            changed += ["pack %s" % name for name, digest in sorted(digests.items())
                        if (record.get("pack_digests") or {}).get(name, digest) != digest]
            if changed:
                raise BenchError(
                    "%s already holds results for label %r made with a different setup "
                    "(%s differs). Use another --label or --out, or pass "
                    "--allow-config-change." % (self.out, self.label, ", ".join(changed)))

    # ---------------------------------------------------------------------- models

    def _backend(self, arm):
        options = dict(
            base_url=self.spec.base_url, model=self.spec.model, api_key=self.api_key,
            grammar_mode=self.grammar_mode if arm == "stepmold" else "none",
            reasoning_reserve=self.reasoning_reserve, temperature=self.temperature,
            timeout=self.args.timeout, extra_body=dict(self.extra_body))
        if self.args.http_retries is not None:
            options["max_retries"] = self.args.http_retries
        if self.opener is not None:
            options["opener"] = self.opener
        if self.sleeper is not None:
            options["sleeper"] = self.sleeper
        try:
            return backend_class(self.sm)(**options)
        except ValueError as exc:
            raise BenchError(str(exc))

    def _model(self, arm, shared):
        if self.spec.scheme == "fake":
            model = recording(shared, self.sm)
        else:
            model = self._backend(arm)
        if arm == "stepmold":
            return model
        return PlainModel(model, self.sm, schema_hint=(arm == "plain_schema"))

    # ------------------------------------------------------------------------- run

    def run(self):
        self.provenance = stepmold_provenance(self.sm)
        self._check_resume()
        done = set(case_key(record) for record in read_records(self.out)
                   if record.get("kind") == "case")
        for job in self.jobs:
            job.done = (self.label, job.arm, self.packs[job.pack].name, job.case_name,
                        job.run) in done
        todo = sum(1 for job in self.jobs if not job.done)
        self._say("%s: %d case-runs planned (%s x %d run%s), %d already in %s, %d to run"
                  % (self.label, len(self.jobs), "+".join(self.arms), self.args.runs,
                     "" if self.args.runs == 1 else "s", len(self.jobs) - todo, self.out,
                     todo))
        if self.args.dry_run or not todo:
            return 0

        self.invocation = uuid.uuid4().hex[:12]
        self.writer = JsonlWriter(self.out, secret=self.api_key)
        self.writer.write([self._run_record()])
        self.totals = {}
        self.finished = 0
        self.todo = todo
        units = self._units()
        try:
            with capture_events(self.sm):
                pool = ThreadPoolExecutor(max_workers=self.args.concurrency)
                futures = [pool.submit(self._run_unit, unit) for unit in units]
                try:
                    for future in as_completed(futures):
                        try:
                            future.result()
                        except Exception as exc:  # one unit failing stops only that unit
                            self._say("bench: a worker stopped: %s: %s"
                                      % (type(exc).__name__, _clip(str(exc), 300)))
                except KeyboardInterrupt:
                    self.stop.set()
                    pool.shutdown(wait=False, cancel_futures=True)
                    self._say("interrupted: finished case-runs are saved in %s; run the "
                              "same command again to resume" % self.out)
                    return 130
                pool.shutdown(wait=True)
        finally:
            self.writer.close()
        self._report_totals()
        return 0

    def _units(self):
        """What one worker runs in order. Real models: one case-run each.

        A scripted fake is one FakeModel per (arm, pack, run), consumed in evalset order
        the way `stepmold eval` consumes it, so those case-runs stay together in order.
        Finished case-runs in such a group are replayed and not written again.
        """
        if self.spec.scheme != "fake":
            return [[job] for job in self.jobs if not job.done]
        groups = {}
        order = []
        for job in self.jobs:
            key = (job.arm, job.pack, job.run)
            if key not in groups:
                groups[key] = []
                order.append(key)
            groups[key].append(job)
        return [groups[key] for key in order if any(not job.done for job in groups[key])]

    def _run_unit(self, unit):
        shared = None
        if self.spec.scheme == "fake":
            entry = self.packs[unit[0].pack]
            shared = self.sm.cli.resolve_model(self.spec.spec, entry.pack)
        for job in unit:
            if self.stop.is_set():
                return
            records = self._run_one(job, shared)
            if not job.done:
                self.writer.write(records)
                self._progress(job, records[-1])

    def _stamp(self, job):
        return {
            "invocation": self.invocation, "case_run_id": uuid.uuid4().hex[:16],
            "label": self.label, "model": self.spec.model, "arm": job.arm,
            "pack": self.packs[job.pack].name, "case": job.case_name,
            "case_index": job.case_index, "run": job.run,
        }

    def _run_one(self, job, shared):
        entry = self.packs[job.pack]
        stamp = self._stamp(job)
        recorder = Recorder(stamp, entry.pack, self.sm, self.args.record_prompts,
                            self.args.record_reasoning)
        pack = entry.pack if job.arm == "stepmold" else entry.plain
        started = time.monotonic()
        result = None
        failure = None
        _LOCAL.recorder = recorder
        try:
            tools = load_tools(entry.tools) if entry.tools else None
            model = self._model(job.arm, shared)
            report = self.sm.eval.evaluate(pack, model, cases=[job.case], tools=tools)
            result = report.cases[0]
        except Exception as exc:
            failure = "%s: %s" % (type(exc).__name__, _clip(str(exc), 500))
        finally:
            _LOCAL.recorder = None
        wall_ms = (time.monotonic() - started) * 1000.0
        try:
            recorder.finalize()
            if failure is None:
                failure = self._infrastructure(result, recorder)
            if failure is None:
                return recorder.calls + [
                    self._case_record(stamp, job.case, result, recorder, wall_ms)]
        except Exception as exc:  # a bug here must cost this case-run, not the bench
            failure = "bench error building the record: %s: %s" % (type(exc).__name__, exc)
        record = {"kind": "infra_error"}
        record.update(stamp)
        record.update({"error": failure, "calls": len(recorder.calls),
                       "wall_ms": round(wall_ms, 1), "timestamp": _now()})
        return recorder.calls + [record]

    @staticmethod
    def _infrastructure(result, recorder):
        """Why a case-run says nothing about the model, or None when it does.

        A run that reached an end node, or stopped on one of stepmold's own run errors,
        is a result. A backend that could not be reached or kept failing (stepmold's
        `BackendError` escaping the run) is not, and neither is anything that is not a
        stepmold error at all, except a scripted model running out of answers. Those get
        an `infra_error` record instead of a `case` record, so a re-run retries them.
        """
        if recorder.end_node is not None:
            return None
        error = (recorder.run_error or {}).get("error")
        text = (result.error or "") if result is not None else ""
        if error:
            return (text or error) if error == "BackendError" else None
        if text.startswith("ModelExhausted"):
            return None
        return text or "the run stopped without saying why"

    def _case_record(self, stamp, case, result, recorder, wall_ms):
        completed = recorder.end_node is not None
        misses = [m for m in result.mismatches if m.field != "<ending>"]
        total = len(case.expect)
        if not completed:
            outcome = "crashed"
        elif result.passed:
            outcome = "passed"
        elif recorder.escalations:
            outcome = "escalated"
        else:
            outcome = "silently_wrong"
        calls = recorder.calls
        answers = [call for call in calls if call.get("stage") == "answer"]
        record = {"kind": "case"}
        record.update(stamp)
        record.update({
            "outcome": outcome,
            "passed": bool(result.passed),
            "tier": result.tier,
            "end_node": recorder.end_node,
            "expected_end": case.end,
            "end_ok": None if case.end is None else recorder.end_node == case.end,
            "rescued_expected": bool(case.rescued),
            "input": dict(case.input),
            "output": dict(result.actual) if completed else None,
            "expected": dict(case.expect),
            "fields_total": total,
            "fields_matched": total - len(misses) if completed else 0,
            "mismatches": [{"field": m.field, "expected": m.expected, "actual": m.actual,
                            "node": m.node, "note": m.note} for m in result.mismatches],
            "blame_node": result.node,
            "error": result.error,
            "escalated": bool(recorder.escalations),
            "escalations": recorder.escalations,
            "path": recorder.path,
            "steps": recorder.steps,
            "generations": recorder.generations if recorder.generations is not None
            else len(answers),
            "calls": len(calls),
            "think_calls": len(calls) - len(answers),
            "answer_calls": len(answers),
            "rejected_calls": sum(1 for call in answers if call.get("accepted") is False),
            "retries": recorder.retries,
            "extra_draws": sum(max(0, (gate.get("drawn") or 1) - 1) for gate in recorder.gates),
            "gates": recorder.gates,
            "prompt_tokens": _sum(calls, "prompt_tokens"),
            "completion_tokens": _sum(calls, "completion_tokens"),
            "reasoning_tokens": _sum(calls, "reasoning_tokens"),
            "grammar_mode": self.grammar_mode if stamp["arm"] == "stepmold" else "none",
            "wall_ms": round(wall_ms, 1),
            "timestamp": _now(),
        })
        return record

    def _run_record(self):
        bench_file = os.path.abspath(__file__)
        with open(bench_file, "rb") as handle:
            bench_sha = hashlib.sha256(handle.read()).hexdigest()[:16]
        return {
            "kind": "run", "invocation": self.invocation, "label": self.label,
            "model": self.spec.model, "base_url": self.spec.base_url,
            "model_spec": self.spec.spec, "arms": self.arms, "runs": self.args.runs,
            "packs": sorted(entry.name for entry in self.packs.values()),
            "limit": self.args.limit, "concurrency": self.args.concurrency,
            "grammar_mode": self.grammar_mode, "reasoning_reserve": self.reasoning_reserve,
            "temperature": self.temperature, "extra_body": self.extra_body,
            "timeout_s": self.args.timeout, "http_retries": self.args.http_retries,
            "api_key_set": bool(self.api_key), "setup": self.setup(),
            "pack_digests": self.pack_digests(),
            "stepmold": self.provenance, "bench": {"version": BENCH_VERSION,
                                                   "sha256": bench_sha},
            "python": platform.python_version(), "platform": platform.platform(),
            "started": _now(),
        }

    # --------------------------------------------------------------------- output

    def _say(self, text):
        with self.print_lock:
            self.stream.write(text + "\n")
            self.stream.flush()

    def _progress(self, job, record):
        with self.print_lock:
            self.finished += 1
            finished = self.finished
            bucket = self.totals.setdefault(job.arm, {})
            outcome = record.get("outcome") or record.get("kind")
            bucket[outcome] = bucket.get(outcome, 0) + 1
        status = {"passed": "PASS", "escalated": "ESCALATED", "silently_wrong": "WRONG",
                  "crashed": "CRASHED"}.get(record.get("outcome"), "INFRA ERROR")
        line = "[%*d/%d] %-8s %-18s run %d  case %-3d %-10s %2d calls %7.1fs" % (
            len(str(self.todo)), finished, self.todo, job.arm, job.pack, job.run,
            job.case_index, status, record.get("calls") or 0,
            (record.get("wall_ms") or 0) / 1000.0)
        if record.get("kind") == "infra_error":
            line += "  " + _clip(record.get("error"), 160)
        self._say(line)

    def _report_totals(self):
        for arm in self.arms:
            bucket = self.totals.get(arm, {})
            count = sum(bucket.values())
            if not count:
                continue
            self._say("%-8s %d case-runs: %s" % (arm, count, ", ".join(
                "%d %s" % (bucket[key], key.replace("_", " "))
                for key in ("passed", "escalated", "silently_wrong", "crashed", "infra_error")
                if bucket.get(key))))
        self._say("results: %s" % self.out)


# ------------------------------------------------------------------------------- CLI


def build_parser():
    parser = argparse.ArgumentParser(
        prog="bench.py",
        description="Run stepmold's example packs against one model, in two arms "
                    "(stepmold, plain; plain_schema is opt-in), and write one JSONL record "
                    "per request and per case-run. The API key is read from "
                    "STEPMOLD_API_KEY.")
    parser.add_argument("--model", required=True,
                        help="stepmold model spec: openai:<base_url>#<model>[#<grammar_mode>"
                             "[#<reasoning_reserve>]], or fake:<script> for offline runs")
    parser.add_argument("--label", help="name for this model in the results "
                                        "(default: the model name)")
    parser.add_argument("--grammar-mode", dest="grammar_mode", default=None,
                        help="how the stepmold arm sends its grammar (default: the one in "
                             "--model, else response_format). The plain arm always uses none")
    parser.add_argument("--reasoning-reserve", dest="reasoning_reserve", type=int,
                        default=None, help="tokens added to every request's max_tokens, for "
                                           "models that think before answering (default 0)")
    parser.add_argument("--arms", default=DEFAULT_ARMS,
                        help="comma list of stepmold, plain, plain_schema "
                             "(default: %s)" % DEFAULT_ARMS)
    parser.add_argument("--runs", type=int, default=3, help="runs per case (default 3)")
    parser.add_argument("--packs", default="all", help="all, or a comma list of pack names")
    parser.add_argument("--limit", type=int, default=None,
                        help="only the first N gold cases of each pack")
    parser.add_argument("--concurrency", type=int, default=8,
                        help="case-runs in flight at once (default 8)")
    parser.add_argument("--extra-body", dest="extra_body", default=None,
                        help="JSON object merged into every request, e.g. "
                             "'{\"chat_template_kwargs\": {\"enable_thinking\": false}}'")
    parser.add_argument("--out", help="results file (default: results/<label>.jsonl)")
    parser.add_argument("--stepmold", default=None,
                        help="path to a stepmold checkout (default: %s if it exists, else "
                             "the installed stepmold)" % DEFAULT_STEPMOLD)
    parser.add_argument("--examples", default=None,
                        help="directory of packs (default: <stepmold checkout>/examples)")
    parser.add_argument("--tools", action="append", metavar="PACK=FILE.py[:ATTR]",
                        help="host tools for a pack (refund_desk's are found by default)")
    parser.add_argument("--timeout", type=float, default=120.0,
                        help="seconds per HTTP request (default 120)")
    parser.add_argument("--http-retries", dest="http_retries", type=int, default=None,
                        help="HTTP retries on 429/5xx (default: stepmold's, 2)")
    parser.add_argument("--record-prompts", dest="record_prompts", action="store_true",
                        help="store each rendered prompt in its call record")
    parser.add_argument("--record-reasoning", dest="record_reasoning", action="store_true",
                        help="store the model's reasoning text, when the server returns it")
    parser.add_argument("--allow-config-change", dest="allow_config_change",
                        action="store_true",
                        help="resume into a file whose earlier runs used another setup")
    parser.add_argument("--dry-run", dest="dry_run", action="store_true",
                        help="print the plan and what is already done, then stop")
    return parser


def main(argv=None, opener=None, sleeper=None, stream=None):
    args = build_parser().parse_args(argv)
    path = args.stepmold
    if path is None and os.path.isfile(os.path.join(DEFAULT_STEPMOLD, "stepmold",
                                                    "__init__.py")):
        path = DEFAULT_STEPMOLD
    try:
        sm = load_stepmold(path)
        bench = Bench(args, sm, opener=opener, sleeper=sleeper, stream=stream)
        return bench.run()
    except BenchError as exc:
        (stream or sys.stderr).write("bench: %s\n" % exc)
        return 2


if __name__ == "__main__":
    sys.exit(main())