File size: 87,432 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
"""Executable TRL backend for the frozen Qwen3.5-2B training plans.

Heavy GPU libraries are imported only inside :func:`run`.  The artifact,
prompt, reward, image-integrity, and token-budget preparation below remains
CPU-testable and fails closed before a trainer can touch a GPU.
"""

from __future__ import annotations

import copy
import hashlib
import json
import os
import random
import re
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast

from ..atomic_io import (
    JsonlAppender,
    atomic_write_bytes,
    atomic_write_json,
    read_jsonl,
)
from ..hashing import canonical_json_hash, sha256_file
from ..paths import repo_root
from ..vcs import current_code_commit
from .answers import answers_equal, parse_answer
from .artifacts import ANSWER_SCHEMA_REGEX
from .evi_po_contract import (
    EVIContractError,
    EVIGroupContract,
    build_evi_group_contracts,
    evidence_spec_for_view,
)
from .ledger import CompletionEntry, CompletionTokenLedger, completion_id
from .peft_contract import (
    adapter_checkpoint_errors,
    trainable_parameter_errors,
    trainable_parameter_manifest,
)
from .rewards import (
    ArmPlan,
    RewardTrace,
    RewardWeights,
    arm_trainer_kind,
    canonical_arm,
    plan_arm,
    score_completion,
)
from .slots import (
    comparison_slot_from_row,
    comparison_slot_manifest_sha256,
)

BACKEND_ENTRYPOINT = "explicit_learning.training.backend:run"


class BackendContractError(RuntimeError):
    """Raised before training when a frozen input cannot be executed safely."""


@dataclass(frozen=True)
class PreparedRecords:
    """Framework-neutral records plus their immutable input identity."""

    rows: tuple[dict[str, Any], ...]
    dataset_sha256: str
    record_count: int
    assistant_token_count: int | None = None


def _state_digest(value: Any) -> str:
    """Hash nested optimizer/scheduler/RNG state independent of device."""

    digest = hashlib.sha256()

    def visit(item: Any) -> None:
        if item is None or isinstance(item, bool | int | float | str):
            digest.update(f"{type(item).__name__}:{item!r}\n".encode())
            return
        if isinstance(item, Mapping):
            digest.update(b"mapping{\n")
            for key in sorted(item, key=lambda candidate: str(candidate)):
                visit(str(key))
                visit(item[key])
            digest.update(b"}\n")
            return
        if isinstance(item, Sequence) and not isinstance(item, str | bytes | bytearray):
            digest.update(f"sequence:{len(item)}[\n".encode())
            for child in item:
                visit(child)
            digest.update(b"]\n")
            return
        try:
            import numpy as np

            if isinstance(item, np.ndarray):
                digest.update(f"numpy:{item.dtype}:{item.shape}:".encode())
                digest.update(item.tobytes())
                return
        except ImportError:
            pass
        try:
            import torch

            if isinstance(item, torch.Tensor):
                # Flatten before the uint8 byte-view: ``.view(torch.uint8)`` reinterprets
                # element bytes, which requires >=1 dim, so a 0-dim scalar (e.g. an AdamW
                # ``step`` counter, a 0-dim float) would otherwise raise
                # "self.dim() cannot be 0 to view Float as Byte". ``reshape(-1)`` is a no-op
                # view on the already-contiguous tensor and yields the same bytes for any
                # rank/dtype, including bfloat16 (which has no native numpy dtype).
                tensor = item.detach().contiguous().reshape(-1).view(torch.uint8).cpu()
                digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode())
                digest.update(tensor.numpy().tobytes())
                return
        except ImportError:
            pass
        digest.update(
            f"fallback:{type(item).__module__}.{type(item).__qualname__}:{item!r}\n".encode()
        )

    visit(value)
    return digest.hexdigest()


def _mapping(value: Any, label: str) -> Mapping[str, Any]:
    if not isinstance(value, Mapping):
        raise BackendContractError(f"{label} must be an object")
    return value


def _dataset_identity(runtime: Mapping[str, Any], path: Path) -> str:
    """Use the frozen manifest identity; hash bytes only in unfrozen unit use."""

    launch = runtime.get("_launch_manifest")
    if isinstance(launch, Mapping):
        identity = launch.get("dataset_manifest_sha256")
        if isinstance(identity, str) and identity:
            return identity
    return sha256_file(path)


def _assert_output_contract(value: str, *, label: str) -> None:
    rendered = f"<answer>{value}</answer>"
    if re.fullmatch(ANSWER_SCHEMA_REGEX, rendered) is None:
        raise BackendContractError(
            f"{label} cannot be represented by the constrained answer schema"
        )


def _safe_asset(root: Path, image: Mapping[str, Any]) -> Path:
    raw = image.get("path")
    if not isinstance(raw, str) or not raw:
        raise BackendContractError("image path must be a non-empty string")
    relative = Path(raw)
    if relative.is_absolute() or ".." in relative.parts or "\\" in raw:
        raise BackendContractError(f"unsafe training image path: {raw!r}")
    root = root.resolve()
    resolved = (root / relative).resolve()
    try:
        resolved.relative_to(root)
    except ValueError as exc:
        raise BackendContractError(f"training image escapes dataset root: {raw!r}") from exc
    if not resolved.is_file():
        raise BackendContractError(f"training image does not exist: {resolved}")
    return resolved


def _system_prompt() -> str:
    path = repo_root() / "prompts" / "common_system.txt"
    try:
        prompt = path.read_text(encoding="utf-8").strip()
    except OSError as exc:
        raise BackendContractError(f"cannot read common system prompt: {exc}") from exc
    if not prompt:
        raise BackendContractError("common system prompt is empty")
    return prompt


def _user_text(question: str, choices: Sequence[Mapping[str, Any]]) -> str:
    if not question:
        raise BackendContractError("training question is empty")
    if not choices:
        return question
    rendered: list[str] = []
    for choice in choices:
        if "key" not in choice or "text" not in choice:
            raise BackendContractError("choice requires key and text")
        rendered.append(f"{choice['key']}. {choice['text']}")
    return question + "\n\nChoices:\n" + "\n".join(rendered)


def _prompt(
    question: str,
    choices: Sequence[Mapping[str, Any]],
    *,
    image_count: int,
) -> list[dict[str, Any]]:
    if image_count <= 0:
        raise BackendContractError("a VLM training record must contain an image")
    content = [{"type": "image"} for _ in range(image_count)]
    content.append({"type": "text", "text": _user_text(question, choices)})
    return [
        {"role": "system", "content": [{"type": "text", "text": _system_prompt()}]},
        {"role": "user", "content": content},
    ]


def _images_for_view(view: Mapping[str, Any], root: Path) -> tuple[Path, ...]:
    raw_images = view.get("images")
    if not isinstance(raw_images, list) or not raw_images:
        raise BackendContractError("training view has no images")
    images = tuple(_mapping(image, "image") for image in raw_images)
    indices = [image.get("image_index") for image in images]
    if indices != list(range(len(images))):
        raise BackendContractError("training image indices are not contiguous")
    return tuple(_safe_asset(root, image) for image in images)


def _evi_group_payload(
    group: EVIGroupContract,
    root: Path,
    *,
    require_evidence: bool,
) -> dict[str, Any]:
    """Materialize the loader-side grouped relationship for one EVI base item."""

    targets = {
        "FULL": group.full_answer,
        "CONTROL": group.full_answer,
        "MISSING": "<UNANSWERABLE>",
    }
    if group.substitute_answer is not None:
        targets["SUBSTITUTE"] = group.substitute_answer
    relationships: list[dict[str, Any]] = []
    for relation, slot in group.relations:
        view = slot.selected_view
        image_paths = _images_for_view(view, root)
        evidence = (
            evidence_spec_for_view(
                view,
                dataset_root=root,
            )
            if relation == "FULL" and require_evidence
            else None
        )
        relationships.append(
            {
                "relation": relation,
                "state": str(view["state"]),
                "source_role": str(view["role"]),
                "view_id": str(view["view_id"]),
                "prompt": _prompt(
                    group.question,
                    [copy.deepcopy(choice) for choice in group.choices],
                    image_count=len(image_paths),
                ),
                "image_paths": [str(path) for path in image_paths],
                "target": targets[relation],
                "evidence": evidence,
            }
        )
    return {
        "schema_version": 1,
        "group_id": group.group_id,
        "base_id": group.base_id,
        "answer_type": group.answer_type,
        "choices": [copy.deepcopy(choice) for choice in group.choices],
        "candidate_targets": list(group.candidates),
        "relationships": relationships,
        "evidence_supervision_relation": "FULL",
    }


def prepare_rl_records(runtime: Mapping[str, Any]) -> PreparedRecords:
    """Validate a v2 slot manifest and map it to one frozen comparison arm."""

    dataset_path = Path(str(runtime.get("dataset_path", ""))).resolve()
    if not dataset_path.is_file():
        raise BackendContractError(f"comparison-slot dataset not found: {dataset_path}")
    try:
        raw_rows = tuple(_mapping(row, "comparison slot") for row in read_jsonl(dataset_path))
        slots = tuple(comparison_slot_from_row(row) for row in raw_rows)
    except (OSError, json.JSONDecodeError, ValueError) as exc:
        raise BackendContractError(f"invalid comparison-slot dataset: {exc}") from exc
    if not slots:
        raise BackendContractError("comparison-slot dataset is empty")
    expected_manifest = runtime.get("comparison_slot_manifest_sha256")
    launch = runtime.get("_launch_manifest")
    if isinstance(launch, Mapping):
        # Production runs already bind this identity in the frozen plan and
        # launcher.  Re-canonicalizing all 46K slots in every rank/run only
        # repeated a large hash with no additional experimental signal.
        if launch.get("comparison_slot_manifest_sha256", expected_manifest) != expected_manifest:
            raise BackendContractError("comparison-slot identity differs from frozen launch plan")
    else:
        # Direct library/unit use has no frozen launcher contract, so retain the
        # local consistency check there.
        actual_manifest = comparison_slot_manifest_sha256(slots)
        if actual_manifest != expected_manifest:
            raise BackendContractError(
                f"comparison-slot manifest mismatch: {actual_manifest} != {expected_manifest}"
            )
    try:
        arm = canonical_arm(str(runtime.get("arm", "")))
    except ValueError as exc:
        raise BackendContractError(str(exc)) from exc
    trainer_kind = str(runtime.get("trainer_kind") or arm_trainer_kind(arm))
    root = Path(str(runtime.get("dataset_asset_root", ""))).resolve()
    if not root.is_dir():
        raise BackendContractError(f"dataset asset root not found: {root}")
    evi_payloads: dict[str, dict[str, Any]] = {}
    # Every EVI trainer variant needs the same grouped relationship payload.
    # The ablation arm name changes one objective coefficient, not the loader
    # contract.  Restricting this to the literal ``evi_po`` arm made all EVI
    # ablations fail only after the GPU trainer started.
    if trainer_kind == "evi_po":
        evi_config = _mapping(runtime.get("evi_po_config"), "frozen EVI-PO config")
        try:
            lambda_direction = float(evi_config["lambda_direction"])
            lambda_evidence = float(evi_config["lambda_evidence"])
        except (KeyError, TypeError, ValueError) as exc:
            raise BackendContractError("frozen EVI-PO weights are malformed") from exc
        if lambda_direction > 0.0 or lambda_evidence > 0.0:
            try:
                evi_groups = build_evi_group_contracts(slots)
                evi_payloads = {
                    group_id: _evi_group_payload(
                        group,
                        root,
                        require_evidence=lambda_evidence > 0.0,
                    )
                    for group_id, group in evi_groups.items()
                }
            except EVIContractError as exc:
                raise BackendContractError(f"invalid grouped EVI-PO dataset: {exc}") from exc
    prepared: list[dict[str, Any]] = []
    for slot in slots:
        if slot.split != "train":
            raise BackendContractError(
                f"evaluation leakage: slot {slot.slot_id} has split={slot.split!r}"
            )
        plan = plan_arm(slot, arm)
        _assert_output_contract(plan.gold_target, label=f"slot {slot.slot_id} gold target")
        view = (
            slot.full_view
            if plan.input_view_id == slot.full_view.get("view_id")
            else slot.selected_view
        )
        if view.get("view_id") != plan.input_view_id:
            raise BackendContractError(f"slot {slot.slot_id}: planned view is not persisted")
        image_paths = _images_for_view(view, root)
        choices = [copy.deepcopy(choice) for choice in slot.choices]
        row = {
            "prompt": _prompt(slot.question, choices, image_count=len(image_paths)),
            "image_paths": [str(path) for path in image_paths],
            "slot_id": slot.slot_id,
            "group_id": slot.group_id,
            "base_id": slot.base_id,
            "gold_target": plan.gold_target,
            "answer_type": plan.answer_type,
            "choices": choices,
            "arm": plan.arm,
        }
        if trainer_kind == "evi_po" and evi_payloads:
            try:
                row["evi_group"] = copy.deepcopy(evi_payloads[slot.group_id])
            except KeyError as exc:
                raise BackendContractError(
                    f"slot {slot.slot_id}: no complete EVI group payload"
                ) from exc
        prepared.append(row)
    return PreparedRecords(
        rows=tuple(prepared),
        dataset_sha256=_dataset_identity(runtime, dataset_path),
        record_count=len(prepared),
    )


def prepare_sft_records(runtime: Mapping[str, Any]) -> PreparedRecords:
    """Validate certificate-target prompt/completion records for SFT."""

    dataset_path = Path(str(runtime.get("dataset_path", ""))).resolve()
    if not dataset_path.is_file():
        raise BackendContractError(f"SFT dataset not found: {dataset_path}")
    expected_kind = str(runtime.get("arm", ""))
    root = Path(str(runtime.get("dataset_asset_root", ""))).resolve()
    if not root.is_dir():
        raise BackendContractError(f"dataset asset root not found: {root}")
    prepared: list[dict[str, Any]] = []
    try:
        rows = tuple(_mapping(row, "SFT row") for row in read_jsonl(dataset_path))
    except (OSError, json.JSONDecodeError) as exc:
        raise BackendContractError(f"invalid SFT dataset: {exc}") from exc
    if not rows:
        raise BackendContractError("SFT dataset is empty")
    seen: set[tuple[str, str]] = set()
    for row in rows:
        if row.get("schema_version") != 2:
            raise BackendContractError("SFT row must use schema_version=2")
        if row.get("record_kind") != expected_kind:
            raise BackendContractError(
                f"SFT record kind {row.get('record_kind')!r} != frozen arm {expected_kind!r}"
            )
        if row.get("split") != "train":
            raise BackendContractError("evaluation leakage: SFT row is not split=train")
        question = row.get("question")
        choices = row.get("choices")
        images = row.get("images")
        response = row.get("assistant_response")
        target = row.get("target")
        answer_type = row.get("answer_type")
        if not isinstance(question, str) or not isinstance(choices, list):
            raise BackendContractError("SFT question/choices are malformed")
        if not isinstance(images, list) or not images:
            raise BackendContractError("SFT row has no images")
        if not isinstance(response, str) or not isinstance(target, str):
            raise BackendContractError("SFT response/target is malformed")
        _assert_output_contract(target, label=f"SFT row {row.get('view_id')} target")
        if re.fullmatch(ANSWER_SCHEMA_REGEX, response) is None:
            raise BackendContractError("SFT response violates the constrained answer schema")
        if not isinstance(answer_type, str):
            raise BackendContractError("SFT answer_type is malformed")
        parsed = parse_answer(response)
        if not parsed.valid or not answers_equal(
            parsed.require_content(),
            target,
            answer_type,
            choices=choices,
        ):
            raise BackendContractError("SFT response does not exactly encode its target")
        identity = (str(row.get("group_id", "")), str(row.get("view_id", "")))
        if not all(identity) or identity in seen:
            raise BackendContractError("SFT group/view identity is empty or duplicated")
        seen.add(identity)
        image_rows = [_mapping(image, "SFT image") for image in images]
        image_paths = tuple(_safe_asset(root, image) for image in image_rows)
        choice_rows = [copy.deepcopy(dict(choice)) for choice in choices]
        prepared.append(
            {
                "prompt": _prompt(question, choice_rows, image_count=len(image_paths)),
                "completion": [
                    {
                        "role": "assistant",
                        "content": [{"type": "text", "text": response}],
                    }
                ],
                "image_paths": [str(path) for path in image_paths],
                "group_id": identity[0],
                "base_id": str(row.get("base_id", "")),
                "view_id": identity[1],
                "assistant_response": response,
            }
        )
    return PreparedRecords(
        rows=tuple(prepared),
        dataset_sha256=_dataset_identity(runtime, dataset_path),
        record_count=len(prepared),
    )


def _completion_text(value: Any) -> str:
    if isinstance(value, str):
        return value
    if isinstance(value, Mapping):
        if "content" in value:
            return _completion_text(value["content"])
        if "text" in value:
            return str(value["text"])
    if isinstance(value, Sequence) and not isinstance(value, bytes | bytearray):
        return "".join(_completion_text(item) for item in value)
    raise BackendContractError(f"unsupported completion structure: {type(value)!r}")


def _aligned(values: Sequence[Any], length: int, label: str) -> list[Any]:
    items = list(values)
    if len(items) == length:
        return items
    if items and length % len(items) == 0:
        repeat = length // len(items)
        return [item for item in items for _ in range(repeat)]
    raise BackendContractError(
        f"reward metadata {label} has length {len(items)}, expected a divisor of {length}"
    )


def sft_loss_token_count(processor: Any, row: Mapping[str, Any]) -> int:
    """Count the exact labels used by TRL's VLM prompt-completion collator.

    TRL 1.9.1 renders the conversational prompt and completion separately,
    tokenizes the rendered completion with ``add_special_tokens=False``, and
    applies its attention mask as the completion-only loss mask. Consequently
    assistant turn delimiters and the end-of-turn newline are loss-bearing;
    tokenizing only ``assistant_response`` is not equivalent.
    """

    try:
        from trl.data_utils import apply_chat_template, prepare_multimodal_messages
    except ImportError as exc:
        raise BackendContractError(
            "TRL 1.9.1 is required for exact SFT loss-token accounting"
        ) from exc
    prompt = row.get("prompt")
    completion = row.get("completion")
    raw_paths = row.get("image_paths")
    if (
        not isinstance(prompt, list)
        or not isinstance(completion, list)
        or not isinstance(raw_paths, list)
        or not raw_paths
    ):
        raise BackendContractError(
            "SFT loss-token accounting requires prompt, completion, and image_paths"
        )
    images = [_load_pil(str(path)) for path in raw_paths]
    try:
        rendered = apply_chat_template(
            {
                "prompt": prepare_multimodal_messages(
                    copy.deepcopy(prompt),
                    images=images,
                ),
                "completion": prepare_multimodal_messages(copy.deepcopy(completion)),
            },
            processor,
        )
    except (KeyError, TypeError, ValueError) as exc:
        raise BackendContractError(f"TRL SFT chat-template rendering failed: {exc}") from exc
    completion_text = rendered.get("completion")
    if not isinstance(completion_text, str) or not completion_text:
        raise BackendContractError("TRL SFT chat template produced an empty completion")
    encoded = processor(
        text=[completion_text],
        padding=True,
        padding_side="right",
        return_tensors="pt",
        add_special_tokens=False,
    )
    if not isinstance(encoded, Mapping) or "attention_mask" not in encoded:
        raise BackendContractError("processor did not return an SFT completion attention mask")
    attention = encoded["attention_mask"]
    try:
        count = int(attention[0].sum().item())
    except (AttributeError, IndexError, TypeError, ValueError) as exc:
        raise BackendContractError(
            "processor returned an unsupported SFT completion attention mask"
        ) from exc
    if count <= 0:
        raise BackendContractError("SFT completion has no loss-bearing tokens")
    return count


def _completion_id_count(processor: Any, value: Any) -> tuple[int, bool]:
    """Return ``(non-pad token count, terminated)`` for one completion id sequence.

    ``terminated`` is False iff the sequence was truncated — its last token is
    neither EOS nor PAD, i.e. generation hit the token cap without closing. Under
    ``truncation_policy: reject_sample`` (experiment.yaml) that is a rejection
    signal handled by the caller, NOT a fatal contract error: a missing tokenizer
    terminal id or empty sequence still raises, but truncation no longer does.
    """
    if hasattr(value, "tolist"):
        value = value.tolist()
    if (
        isinstance(value, Sequence)
        and value
        and isinstance(value[0], Sequence)
        and not isinstance(value[0], str | bytes | bytearray)
    ):
        if len(value) != 1:
            raise BackendContractError("one completion must have exactly one token-id sequence")
        value = value[0]
    if not isinstance(value, Sequence) or isinstance(value, str | bytes | bytearray):
        raise BackendContractError("completion_ids must contain token-id sequences")
    tokenizer = getattr(processor, "tokenizer", processor)
    pad_id = getattr(tokenizer, "pad_token_id", None)
    ids = [int(token) for token in value]
    if not ids:
        raise BackendContractError("completion_ids contains no sampled tokens")
    eos_value = getattr(tokenizer, "eos_token_id", None)
    eos_ids = (
        {int(token) for token in eos_value}
        if isinstance(eos_value, Sequence) and not isinstance(eos_value, str | bytes)
        else ({int(eos_value)} if eos_value is not None else set())
    )
    terminal_ids = set(eos_ids)
    if pad_id is not None:
        terminal_ids.add(int(pad_id))
    if not terminal_ids:
        raise BackendContractError("tokenizer exposes neither eos_token_id nor pad_token_id")
    terminated = ids[-1] in terminal_ids
    if pad_id is not None:
        ids = [token for token in ids if token != int(pad_id)]
    if not ids:
        raise BackendContractError("completion_ids contains no sampled tokens")
    return len(ids), terminated


def make_reward_function(
    runtime: Mapping[str, Any],
    *,
    processor: Any,
    ledger: CompletionTokenLedger,
    ledger_path: Path,
    trace_path: Path,
) -> Callable[..., list[float]]:
    """Create the sole reward function, including exact sampled-token accounting."""

    arm = canonical_arm(str(runtime["arm"]))
    run_id = str(runtime["run_id"])
    generations = int(runtime["generations_per_prompt"])
    weights = RewardWeights(answer=1.0, format=0.0, invalid_format_penalty=-1.0)
    # Per-row provenance state: tag every emitted reward-trace row with the
    # code commit and frozen-plan identity that produced it, so a merged
    # multi-run analysis file is self-describing and rows from a corrupted /
    # superseded code state (e.g. an arm whose first half ran before a trainer
    # fix) are distinguishable from clean rows. ``code_commit`` is the ACTUAL
    # running commit (git HEAD at process start, best-effort), not the frozen
    # manifest's provenance commit -- the two can diverge when an arm is
    # frozen under one commit but launched under a later fix, and the running
    # commit is what determines whether a row is clean. ``frozen_config_sha256``
    # is the stable frozen-plan identity from the verified launch manifest.
    # Neither value mutates the runtime dict, so config_sha256 (and thus
    # checkpoint resume) is unaffected.
    launch_state = _mapping(
        runtime.get("_launch_manifest"), "verified launch manifest"
    )
    row_code_commit = current_code_commit()
    row_frozen_config_sha256 = str(launch_state["frozen_config_sha256"])

    def reward(
        completions: Sequence[Any],
        completion_ids: Sequence[Any],
        gold_target: Sequence[Any],
        answer_type: Sequence[Any],
        choices: Sequence[Any],
        slot_id: Sequence[Any],
        group_id: Sequence[Any],
        base_id: Sequence[Any],
        **_: Any,
    ) -> list[float]:
        texts = [_completion_text(completion) for completion in completions]
        size = len(texts)
        token_id_rows = _aligned(completion_ids, size, "completion_ids")
        golds = _aligned(gold_target, size, "gold_target")
        types = _aligned(answer_type, size, "answer_type")
        choice_rows = _aligned(choices, size, "choices")
        slot_ids = _aligned(slot_id, size, "slot_id")
        group_ids = _aligned(group_id, size, "group_id")
        base_ids = _aligned(base_id, size, "base_id")
        entries: list[CompletionEntry] = []
        traces: list[dict[str, Any]] = []
        rewards: list[float] = []
        slot_generation: dict[str, int] = {}
        for index, text in enumerate(texts):
            current_slot = str(slot_ids[index])
            generation_index = slot_generation.get(current_slot, 0)
            slot_generation[current_slot] = generation_index + 1
            if generation_index >= generations:
                raise BackendContractError(
                    f"slot {current_slot} produced more than {generations} generations"
                )
            raw_choices = choice_rows[index]
            if not isinstance(raw_choices, Sequence) or isinstance(
                raw_choices, str | bytes | bytearray
            ):
                raise BackendContractError("reward choices metadata is malformed")
            plan = ArmPlan(
                arm=arm,
                slot_id=current_slot,
                group_id=str(group_ids[index]),
                base_id=str(base_ids[index]),
                comparison_role="PERSISTED",
                input_view_id="PERSISTED",
                input_state="PERSISTED",
                gold_target=str(golds[index]),
                answer_type=str(types[index]),
                choices=tuple(dict(_mapping(choice, "reward choice")) for choice in raw_choices),
            )
            token_count, terminated = _completion_id_count(processor, token_id_rows[index])
            if terminated:
                trace = score_completion(plan, text, weights=weights)
            else:
                # truncation_policy=reject_sample: a completion that hit the token
                # cap without EOS is rejected as malformed (penalty reward, and
                # loss-masked by TRL's mask_truncated_completions) rather than
                # crashing the run. Its sampled tokens still count toward the
                # budget ceiling, so the ledger entry is always recorded below.
                trace = RewardTrace(
                    arm=arm,
                    slot_id=current_slot,
                    parser_valid=False,
                    parser_error="truncated_completion",
                    parsed_answer=None,
                    normalized_prediction=None,
                    normalized_gold="",
                    answer_component=0.0,
                    format_component=0.0,
                    total_reward=weights.invalid_format_penalty,
                    normalizer_branch="truncation_reject",
                )
            current_completion_id = completion_id(run_id, current_slot, generation_index)
            entries.append(
                CompletionEntry(
                    completion_id=current_completion_id,
                    token_count=token_count,
                    slot_id=current_slot,
                    generation_index=generation_index,
                )
            )
            trace_row = {
                **trace.__dict__,
                "group_id": str(group_ids[index]),
                "base_id": str(base_ids[index]),
                "completion_id": current_completion_id,
                "generation_index": generation_index,
                "completion_tokens": token_count,
                "terminated": terminated,
                "code_commit": row_code_commit,
                "frozen_config_sha256": row_frozen_config_sha256,
            }
            traces.append(trace_row)
            rewards.append(trace.total_reward)
        ledger.record_many(entries)
        with JsonlAppender(trace_path) as appender:
            appender.extend(traces)
        return rewards

    return reward


def _input_length(processor: Any, messages: Sequence[Mapping[str, Any]]) -> int:
    apply_template = getattr(processor, "apply_chat_template", None)
    if not callable(apply_template):
        raise BackendContractError("processor has no apply_chat_template")
    encoded = apply_template(
        list(messages),
        tokenize=True,
        add_generation_prompt=False,
        return_dict=True,
    )
    input_ids = encoded.get("input_ids") if isinstance(encoded, Mapping) else encoded
    if input_ids is None:
        raise BackendContractError("processor did not return input_ids")
    shape = getattr(input_ids, "shape", None)
    if shape is not None:
        return int(shape[-1])
    if isinstance(input_ids, Sequence) and input_ids and isinstance(input_ids[0], Sequence):
        return len(input_ids[0])
    if isinstance(input_ids, Sequence):
        return len(input_ids)
    raise BackendContractError("processor returned unsupported input_ids")


def _load_pil(path: str) -> Any:
    from PIL import Image

    with Image.open(path) as image:
        return image.convert("RGB").copy()


def _materialize_images(rows: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
    materialized: list[dict[str, Any]] = []
    for source in rows:
        row = copy.deepcopy(dict(source))
        paths = row.pop("image_paths", None)
        if not isinstance(paths, list) or not paths:
            raise BackendContractError("prepared row has no image paths")
        images = [_load_pil(str(path)) for path in paths]
        if len(images) == 1:
            row["image"] = images[0]
        else:
            row["images"] = images
        row.pop("assistant_response", None)
        materialized.append(row)
    return materialized


def cap_sft_records(
    rows: Sequence[Mapping[str, Any]],
    *,
    processor: Any,
    max_assistant_tokens: int,
    loss_token_counter: Callable[[Any, Mapping[str, Any]], int] = sft_loss_token_count,
) -> PreparedRecords:
    """Take at most one deterministic epoch without exceeding the loss-token cap."""

    if max_assistant_tokens <= 0:
        raise BackendContractError("SFT assistant-token cap must be positive")
    scheduled: list[dict[str, Any]] = []
    consumed = 0
    for row in rows:
        count = loss_token_counter(processor, row)
        if count <= 0:
            raise BackendContractError("SFT row has no loss-bearing completion tokens")
        if consumed + count > max_assistant_tokens:
            break
        scheduled.append(copy.deepcopy(dict(row)))
        consumed += count
    if not scheduled:
        raise BackendContractError("SFT token cap is smaller than the first admitted response")
    return PreparedRecords(
        rows=tuple(scheduled),
        dataset_sha256="",
        record_count=len(scheduled),
        assistant_token_count=consumed,
    )


def _rank_budget(runtime: Mapping[str, Any]) -> tuple[int, int]:
    world_size = int(runtime["world_size"])
    rank = int(os.environ.get("RANK", "0"))
    if not 0 <= rank < world_size:
        raise BackendContractError(f"RANK {rank} is outside world_size={world_size}")
    total = int(runtime["max_completion_tokens_per_run"])
    share, remainder = divmod(total, world_size)
    return rank, share + (1 if rank < remainder else 0)


def _load_or_create_ledger(
    runtime: Mapping[str, Any],
    *,
    dataset_sha256: str,
    ledger_path: Path,
) -> CompletionTokenLedger:
    rank, rank_cap = _rank_budget(runtime)
    identity = canonical_json_hash(dict(runtime))
    if ledger_path.exists():
        return CompletionTokenLedger.load(
            ledger_path,
            expected_run_id=f"{runtime['run_id']}:rank-{rank}",
            expected_max_tokens=rank_cap,
            expected_config_sha256=identity,
            expected_data_manifest_sha256=dataset_sha256,
            expected_comparison_slot_manifest_sha256=str(
                runtime["comparison_slot_manifest_sha256"]
            ),
        )
    return CompletionTokenLedger(
        run_id=f"{runtime['run_id']}:rank-{rank}",
        max_tokens=rank_cap,
        config_sha256=identity,
        data_manifest_sha256=dataset_sha256,
        comparison_slot_manifest_sha256=str(runtime["comparison_slot_manifest_sha256"]),
    )


def _accounting_frontier_paths(
    checkpoint: Path,
    *,
    rank: int,
) -> tuple[Path, Path, Path]:
    root = checkpoint / "accounting"
    return (
        root / f"rank-{rank}.ledger.json",
        root / f"rank-{rank}.reward-trace.jsonl",
        root / f"rank-{rank}.frontier.json",
    )


def _snapshot_accounting_frontier(
    *,
    checkpoint: Path,
    rank: int,
    optimizer_step: int,
    ledger_path: Path,
    trace_path: Path,
) -> None:
    """Atomically bind reward accounting to one Trainer checkpoint frontier."""

    if not ledger_path.is_file() or not trace_path.is_file():
        raise BackendContractError("cannot checkpoint missing ledger/reward trace")
    ledger_snapshot, trace_snapshot, frontier_path = _accounting_frontier_paths(
        checkpoint, rank=rank
    )
    atomic_write_bytes(ledger_snapshot, ledger_path.read_bytes())
    atomic_write_bytes(trace_snapshot, trace_path.read_bytes())
    ledger_value = json.loads(ledger_snapshot.read_text(encoding="utf-8"))
    entries = ledger_value.get("entries") if isinstance(ledger_value, dict) else None
    if not isinstance(entries, list):
        raise BackendContractError("checkpoint ledger snapshot has no entries list")
    atomic_write_json(
        frontier_path,
        {
            "schema_version": 2,
            "optimizer_step": optimizer_step,
            "rank": rank,
            "ledger_completion_count": len(entries),
            "ledger_consumed_tokens": ledger_value.get("consumed_tokens"),
            "reward_trace_rows": sum(1 for _ in read_jsonl(trace_snapshot)),
        },
    )


def _restore_accounting_frontier(
    *,
    checkpoint: Path,
    output: Path,
    rank: int,
) -> None:
    """Rollback live accounting to the exact last durable Trainer checkpoint."""

    ledger_snapshot, trace_snapshot, frontier_path = _accounting_frontier_paths(
        checkpoint, rank=rank
    )
    try:
        frontier = json.loads(frontier_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise BackendContractError(
            f"cannot resume without accounting frontier {frontier_path}: {exc}"
        ) from exc
    expected_step = int(checkpoint.name.removeprefix("checkpoint-"))
    if (
        not isinstance(frontier, dict)
        or frontier.get("schema_version") != 2
        or frontier.get("optimizer_step") != expected_step
        or frontier.get("rank") != rank
    ):
        raise BackendContractError("checkpoint accounting frontier identity mismatch")
    if not ledger_snapshot.is_file() or not trace_snapshot.is_file():
        raise BackendContractError("checkpoint accounting snapshot is incomplete")
    loaded_ledger = CompletionTokenLedger.load(ledger_snapshot)
    if (
        loaded_ledger.completion_count != frontier.get("ledger_completion_count")
        or loaded_ledger.consumed_tokens != frontier.get("ledger_consumed_tokens")
    ):
        raise BackendContractError("checkpoint ledger counts differ from its frontier")
    if sum(1 for _ in read_jsonl(trace_snapshot)) != frontier.get("reward_trace_rows"):
        raise BackendContractError("checkpoint reward-trace row count mismatch")
    atomic_write_bytes(
        output / "token-ledgers" / f"rank-{rank}.json",
        ledger_snapshot.read_bytes(),
    )
    atomic_write_bytes(
        output / "reward-traces" / f"rank-{rank}.jsonl",
        trace_snapshot.read_bytes(),
    )


def _model_and_processor(runtime: Mapping[str, Any], *, sft: bool) -> tuple[Any, Any, Any]:
    from peft import LoraConfig, PeftModel
    from transformers import AutoModelForMultimodalLM, AutoProcessor

    model_path = str(runtime["model_path"])
    processor = AutoProcessor.from_pretrained(
        model_path,
        revision=str(runtime["model_revision"]),
    )
    # Note: do NOT pass use_cache here. Qwen3.5's constructor
    # (Qwen3_5ForConditionalGeneration.__init__) accepts only `config`, and its
    # config has no use_cache field, so the kwarg is rejected by from_pretrained.
    # KV cache is disabled for training automatically via gradient_checkpointing.
    model = AutoModelForMultimodalLM.from_pretrained(
        model_path,
        revision=str(runtime["model_revision"]),
        dtype="bfloat16",
        attn_implementation=str(runtime["attention_implementation"]),
    )
    if sft:
        peft_config = LoraConfig(
            task_type="CAUSAL_LM",
            r=int(runtime["lora_rank"]),
            lora_alpha=int(runtime["lora_alpha"]),
            lora_dropout=float(runtime["lora_dropout"]),
            target_modules=runtime["lora_target_modules"][0]
            if runtime["lora_target_modules"] == ["all-linear"]
            else list(runtime["lora_target_modules"]),
            exclude_modules=["lm_head"],
            bias="none",
        )
        return model, processor, peft_config
    initial = Path(str(runtime["initial_checkpoint_path"]))
    adapter_errors = adapter_checkpoint_errors(initial, runtime)
    if adapter_errors:
        raise BackendContractError("; ".join(adapter_errors))
    model = PeftModel.from_pretrained(model, initial, is_trainable=True)
    trainable_errors = trainable_parameter_errors(model)
    if trainable_errors:
        raise BackendContractError("; ".join(trainable_errors))
    return model, processor, None


def _common_trainer_args(runtime: Mapping[str, Any]) -> dict[str, Any]:
    return {
        "output_dir": str(runtime["output_dir"]),
        "per_device_train_batch_size": int(runtime["per_device_train_batch_size"]),
        "gradient_accumulation_steps": int(runtime["gradient_accumulation_steps"]),
        "num_train_epochs": 1.0,
        "max_steps": int(runtime["max_optimizer_steps"]),
        "learning_rate": float(runtime["learning_rate"]),
        "lr_scheduler_type": "cosine",
        "warmup_ratio": 0.03,
        "optim": "adamw_torch",
        "weight_decay": 0.0,
        "adam_beta1": 0.9,
        "adam_beta2": 0.999,
        "adam_epsilon": 1.0e-8,
        "max_grad_norm": 1.0,
        "bf16": True,
        "gradient_checkpointing": True,
        "save_strategy": "steps",
        "save_steps": int(runtime["checkpoint_interval"]),
        "save_total_limit": 2,
        "logging_steps": 1,
        # TensorBoard logging is opt-in and gated to verified execute runs only:
        # the default stays "none" so CPU contracts, dry-runs, and plan-freezes
        # never emit traces. Set EXPLICIT_REPORT_TO=tensorboard only when
        # launching a real training backend (launcher execute); tfevent files
        # land under the run's output_dir, no network egress required.
        "report_to": os.environ.get("EXPLICIT_REPORT_TO", "none"),
        "run_name": str(runtime["run_id"]),
        "seed": int(runtime["seed"]),
        "data_seed": int(runtime["seed"]),
        "dataloader_num_workers": 4,
        "dataloader_pin_memory": True,
        "remove_unused_columns": False,
    }


def _validate_prompt_envelope(
    runtime: Mapping[str, Any],
    rows: Sequence[Mapping[str, Any]],
    *,
    processor: Any,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> None:
    # Safety gate: every row's prompt/SFT envelope must fit the frozen token
    # budget. The per-row check (image decode + token count) is delegated to
    # ``preflight`` which parallelizes it across a thread pool and memoizes the
    # verdict by a fingerprint of the frozen inputs, removing the multi-minute
    # serial GPU-idle stall. The gate stays bit-identical: the check body and
    # the lowest-index failure message are unchanged, and any pool fault falls
    # back to the original serial scan. See ``training.preflight``.
    from .preflight import run_preflight

    run_preflight(
        runtime,
        rows,
        processor,
        sft=sft,
        max_prompt_tokens=max_prompt_tokens,
        total_context_tokens=total_context_tokens,
    )


def _train_sft(runtime: Mapping[str, Any]) -> tuple[Any, PreparedRecords, Any]:
    from datasets import Dataset
    from trl import SFTConfig, SFTTrainer

    prepared = prepare_sft_records(runtime)
    model, processor, peft_config = _model_and_processor(runtime, sft=True)
    capped = cap_sft_records(
        prepared.rows,
        processor=processor,
        max_assistant_tokens=int(runtime["max_completion_tokens_per_run"]),
    )
    _validate_prompt_envelope(
        runtime,
        capped.rows,
        processor=processor,
        sft=True,
        max_prompt_tokens=int(runtime["max_prompt_tokens"]),
        total_context_tokens=int(runtime["total_context_tokens"]),
    )
    dataset = Dataset.from_list(_materialize_images(capped.rows))
    args = SFTConfig(
        **_common_trainer_args(runtime),
        max_length=None,
        completion_only_loss=True,
        assistant_only_loss=False,
        packing=False,
        shuffle_dataset=False,
    )
    trainer = SFTTrainer(
        model=model,
        args=args,
        train_dataset=dataset,
        processing_class=processor,
        peft_config=peft_config,
    )
    return (
        trainer,
        PreparedRecords(
            rows=capped.rows,
            dataset_sha256=prepared.dataset_sha256,
            record_count=capped.record_count,
            assistant_token_count=capped.assistant_token_count,
        ),
        processor,
    )


def _train_rl(runtime: Mapping[str, Any]) -> tuple[Any, PreparedRecords, Any, Path]:
    from transformers import TrainerCallback
    from trl import GRPOConfig

    from .lazy_dataset import LazyImageRLDataset

    prepared = prepare_rl_records(runtime)
    model, processor, _ = _model_and_processor(runtime, sft=False)
    _validate_prompt_envelope(
        runtime,
        prepared.rows,
        processor=processor,
        sft=False,
        max_prompt_tokens=int(runtime["max_prompt_tokens"]),
        total_context_tokens=int(runtime["total_context_tokens"]),
    )
    cache_dir = os.environ.get("EXPLICIT_IMAGE_CACHE_DIR") or None
    dataset = LazyImageRLDataset(prepared.rows, cache_dir=cache_dir)
    output = Path(str(runtime["output_dir"]))
    rank, _ = _rank_budget(runtime)
    ledger_path = output / "token-ledgers" / f"rank-{rank}.json"
    trace_path = output / "reward-traces" / f"rank-{rank}.jsonl"
    ledger = _load_or_create_ledger(
        runtime,
        dataset_sha256=prepared.dataset_sha256,
        ledger_path=ledger_path,
    )
    reward = make_reward_function(
        runtime,
        processor=processor,
        ledger=ledger,
        ledger_path=ledger_path,
        trace_path=trace_path,
    )
    next_step_upper_bound = (
        int(runtime["per_device_train_batch_size"])
        * int(runtime["gradient_accumulation_steps"])
        * int(runtime["max_completion_tokens"])
    )

    class CompletionBudgetCallback(TrainerCallback):  # type: ignore[misc]
        def on_step_end(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
            del args, kwargs
            can_continue = ledger.remaining_tokens >= next_step_upper_bound
            import torch

            distributed = torch.distributed
            if distributed.is_available() and distributed.is_initialized():
                device = (
                    torch.device("cuda", torch.cuda.current_device())
                    if torch.cuda.is_available()
                    else torch.device("cpu")
                )
                flag = torch.tensor(
                    [1 if can_continue else 0],
                    dtype=torch.int32,
                    device=device,
                )
                distributed.all_reduce(flag, op=distributed.ReduceOp.MIN)
                can_continue = bool(flag.item())
            if not can_continue:
                control.should_training_stop = True
            if (
                runtime.get("run_mode") == "smoke"
                and int(state.global_step) == 5
                and not (output / "smoke-resume-boundary.json").exists()
            ):
                control.should_save = True
                control.should_training_stop = True
            return control

        def on_save(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
            del kwargs
            checkpoint = Path(str(args.output_dir)) / f"checkpoint-{state.global_step}"
            # Persist accounting only at the same durable frontier as Trainer.
            # A crash before this callback resumes the preceding checkpoint and
            # legitimately regenerates the intervening rollouts.
            ledger.save(ledger_path)
            _snapshot_accounting_frontier(
                checkpoint=checkpoint,
                rank=rank,
                optimizer_step=int(state.global_step),
                ledger_path=ledger_path,
                trace_path=trace_path,
            )
            return control

        def on_train_end(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
            del args, state, kwargs
            ledger.save(ledger_path)
            return control

    common = _common_trainer_args(runtime)
    vllm = _mapping(runtime.get("vllm_config"), "frozen vLLM config")
    rl_kwargs = {
        **common,
        "dataloader_drop_last": True,
        "shuffle_dataset": False,
        "dataloader_prefetch_factor": 2,
        "dataloader_persistent_workers": True,
        "num_generations": int(runtime["generations_per_prompt"]),
        "max_completion_length": int(runtime["max_completion_tokens"]),
        "temperature": float(runtime["temperature"]),
        "top_p": float(runtime["top_p"]),
        "beta": float(runtime["beta"]),
        "loss_type": str(runtime["loss_type"]),
        "mask_truncated_completions": True,
        "scale_rewards": "group",
        "use_vllm": bool(runtime["use_vllm"]),
        "vllm_mode": str(vllm["mode"]),
        "vllm_gpu_memory_utilization": float(vllm["gpu_memory_utilization"]),
        "vllm_max_model_length": int(vllm["max_model_length"]),
        "vllm_tensor_parallel_size": int(vllm["tensor_parallel_size"]),
        "vllm_enable_sleep_mode": bool(vllm["enable_sleep_mode"]),
        "vllm_structured_outputs_regex": str(vllm["structured_outputs_regex"]),
        "chat_template_kwargs": {"enable_thinking": bool(runtime["enable_thinking"])},
    }
    trainer_kind = str(runtime["trainer_kind"])
    trainer_class: Any
    if trainer_kind == "papo":
        from .papo import PAPOTrainer
        from .papo_contract import (
            PAPO_ADAPTER_VERSION,
            PAPO_UPSTREAM_SOURCE_SHA256,
        )

        papo = _mapping(runtime.get("papo_config"), "frozen PAPO config")
        if (
            papo.get("adapter_version") != PAPO_ADAPTER_VERSION
            or papo.get("upstream_source_sha256") != PAPO_UPSTREAM_SOURCE_SHA256
        ):
            raise BackendContractError("frozen PAPO adapter identity mismatch")
        args = GRPOConfig(**rl_kwargs)
        trainer_class = PAPOTrainer
        trainer_extra = {"papo_config": papo}
    elif trainer_kind == "evi_po":
        from .evi_po import EVITrainer
        from .evi_po_contract import EVI_PO_ADAPTER_VERSION

        evi_po = _mapping(runtime.get("evi_po_config"), "frozen EVI-PO config")
        if evi_po.get("adapter_version") != EVI_PO_ADAPTER_VERSION:
            raise BackendContractError("frozen EVI-PO adapter identity mismatch")
        # EVI-PO fires a RANK-DEPENDENT number of extra DDP forwards per step:
        # _candidate_scores (evi_po.py:566) runs for every active group and
        # _evidence_loss (:669) additionally for groups whose evidence is
        # available (:778). With per_device_train_batch_size=1 a rank whose
        # sharded micro-batch has no active group (raw_groups=[None]) fires 0
        # extra forwards while another fires 2-3. DDP's default
        # broadcast_buffers=True issues an NCCL buffer broadcast at the START of
        # every model() forward, so the per-step broadcast count mismatches
        # across ranks and NCCL deadlocks — deterministically, at the first step
        # where the two shards diverge (the step-4 hang: one rank frozen mid
        # candidate forward behind a buffer-broadcast, the other blocked at the
        # metric gather). The explicit gather count is already rank-invariant
        # (see evi_po._compute_loss), but the forward count is not. Disabling
        # broadcast_buffers removes the per-forward collective so the asymmetry
        # is harmless; the single per-step backward allreduce stays
        # rank-invariant because every rank's policy forward (super()._compute_loss)
        # exercises all LoRA parameters, so find_unused_parameters=False holds.
        # Safe for Qwen3.5-VL: RMSNorm/LayerNorm carry no running-stat buffers
        # and every rank loads the identical checkpoint, so buffers never
        # diverge during training.
        rl_kwargs = {**rl_kwargs, "ddp_broadcast_buffers": False}
        args = GRPOConfig(**rl_kwargs)
        trainer_class = EVITrainer
        trainer_extra = {"evi_po_config": evi_po}
    elif trainer_kind == "grpo":
        from .aligned_grpo import AlignedGRPOTrainer

        args = GRPOConfig(**rl_kwargs)
        trainer_class = AlignedGRPOTrainer
        trainer_extra = {}
    else:
        raise BackendContractError(f"unsupported RL trainer kind: {trainer_kind!r}")
    trainer = trainer_class(
        model=model,
        args=args,
        reward_funcs=reward,
        train_dataset=dataset,
        processing_class=processor,
        callbacks=[CompletionBudgetCallback()],
        **trainer_extra,
    )
    return trainer, prepared, processor, ledger_path


def _install_default_adapter_restore(
    trainer: Any,
    checkpoint: Path,
    *,
    rank: int,
) -> None:
    """Restore the trainable ``default`` (policy) adapter after a PEFT resume.

    TRL's ``GRPOTrainer`` creates a frozen ``ref`` LoRA adapter -- a copy of the
    pretrained init adapter used as the reference policy -- whenever ``beta != 0``
    and the model is a PEFT model being re-trained (the papo / any KL arm).  On
    save the active ``default`` adapter lands in the checkpoint *root*
    (``adapter_model.safetensors``) and the ``ref`` adapter lands in a ``ref/``
    subdirectory.  transformers' ``Trainer._load_from_checkpoint`` treats *any*
    adapter subdirectory as "all adapters live in subdirectories" and loads ONLY
    the subdirectories, skipping the root file -- so the trained policy adapter
    is never restored and the model silently resumes from the init adapter.

    This wrapper runs the pinned loader, then -- only when that broken
    multi-adapter layout is present (a root adapter file alongside an adapter
    subdirectory) -- explicitly loads the root adapter into ``default`` so the
    policy weights are restored.  For arms without a ``ref`` adapter (``beta ==
    0``: answer_grpo / defacto / intervention_grpo / evi_po) there is no
    subdirectory, the gate is False, and this is a no-op (the pinned loader
    already restored ``default`` from the root).  Installed for every RL resume
    so a crash-recovered main run restores the policy too, not just the smoke
    audit.

    Restore mechanism: ``peft_model.load_adapter(checkpoint, "default",
    is_trainable=True)`` -- the SAME robust path transformers' own
    ``_load_from_checkpoint`` takes for the single-adapter (``beta == 0``) case,
    which overwrites the existing ``default`` adapter in place with the trained
    root weights.  An earlier implementation used
    ``set_peft_model_state_dict``; on the pinned peft 0.19.1 + transformers v5
    stack its ``convert_peft_adapter_state_dict_for_transformers`` path silently
    failed to restore on the real (DDP) resume (the model stayed at the init
    adapter and the smoke resume-state audit caught it), even though it restored
    correctly in a CPU repro -- so we use ``load_adapter`` instead, which is
    exercised on every successful ``beta == 0`` resume and verified
    elementwise-equal to the checkpoint root on the pinned stack.  Optional
    before/after digest logging is gated behind ``EXPLICIT_RESUME_RESTORE_DIAG``.
    """

    # transformers.utils.ADAPTER_SAFE_WEIGHTS_NAME / ADAPTER_WEIGHTS_NAME, inlined
    # so the gate runs torch/transformers-free (the heavy imports stay lazy inside
    # the wrapper, exercised only on a real resume).
    adapter_names = ("adapter_model.safetensors", "adapter_model.bin")
    model_loader = getattr(trainer, "_load_from_checkpoint", None)
    if not callable(model_loader):
        return  # the resume audit below raises on the missing pinned API
    model_loader_fn = cast(Callable[..., Any], model_loader)

    root_adapter = next(
        (checkpoint / name for name in adapter_names if (checkpoint / name).is_file()),
        None,
    )
    adapter_subdirs = [
        child.name
        for child in checkpoint.iterdir()
        if child.is_dir() and any((child / name).is_file() for name in adapter_names)
    ]
    if root_adapter is None or not adapter_subdirs:
        return  # single-adapter (beta == 0) layout: pinned loader restores default

    def load_model(*args: Any, **kwargs: Any) -> Any:
        result = model_loader_fn(*args, **kwargs)
        # The pinned loader (transformers _load_from_checkpoint) took its
        # multi-adapter branch because of the ref/ subdir and loaded ONLY ref/,
        # skipping the root -- so `default` is still the init adapter. Restore
        # the trained policy by loading the root adapter into `default` via
        # peft's load_adapter (overwrite-in-place), the same path the beta == 0
        # arms take. Unwrap accelerate/DDP so load_adapter targets the PeftModel;
        # DDP shares parameter storage, so this writes the same tensors the
        # wrapped trainer (and the smoke resume audit) see.
        try:
            peft_model = trainer.model
            accelerator = getattr(trainer, "accelerator", None)
            unwrap = getattr(accelerator, "unwrap_model", None) if accelerator is not None else None
            if callable(unwrap):
                try:
                    peft_model = unwrap(peft_model)
                except Exception:  # pragma: no cover - fall back to wrapped model
                    peft_model = trainer.model
            _resume_restore_diag(rank, "before", _trainable_param_digest(trainer.model))
            peft_model.load_adapter(str(checkpoint), "default", is_trainable=True)
            _resume_restore_diag(rank, "after", _trainable_param_digest(trainer.model), ok=True)
        except Exception as exc:  # pragma: no cover - surfaces as a hard resume failure
            _resume_restore_diag(rank, "exception", repr(exc), ok=False)
            raise BackendContractError(
                f"failed to restore default adapter from {root_adapter}: {exc}"
            ) from exc
        return result

    trainer._load_from_checkpoint = load_model


def _trainable_param_digest(model: Any) -> str:
    """sha256 over the model's trainable params (the resume-audit selection)."""
    try:
        return _state_digest(
            {
                name: parameter.detach()
                for name, parameter in model.named_parameters()
                if parameter.requires_grad
            }
        )
    except Exception:  # pragma: no cover - diagnostic only
        return "unavailable"


def _resume_restore_diag(rank: int, stage: str, payload: Any, *, ok: bool = True) -> None:
    """Optional before/after digest log for the default-adapter restore.

    No-op unless ``EXPLICIT_RESUME_RESTORE_DIAG`` is set, so production main /
    ablation resumes pay nothing. Used to confirm the papo multi-adapter restore
    took effect on the real (DDP) resume when validating the fix.
    """
    if not os.environ.get("EXPLICIT_RESUME_RESTORE_DIAG"):
        return
    try:
        with open(f"/tmp/papo_restore_diag_r{rank}.log", "a") as fh:
            fh.write(f"{stage} ok={ok} {payload}\n")
    except OSError:  # pragma: no cover - diagnostic only
        pass


def _install_resume_load_audit(
    trainer: Any,
    checkpoint: Path,
    *,
    rank: int,
) -> dict[str, Any]:
    """Instrument the pinned Trainer loaders and prove state was restored."""

    import numpy as np
    import torch

    audit: dict[str, Any] = {
        "schema_version": 1,
        "status": "pending",
        "rank": rank,
        "checkpoint": str(checkpoint),
    }
    optimizer_loader = getattr(trainer, "_load_optimizer_and_scheduler", None)
    rng_loader = getattr(trainer, "_load_rng_state", None)
    model_loader = getattr(trainer, "_load_from_checkpoint", None)
    if not all(callable(loader) for loader in (optimizer_loader, rng_loader, model_loader)):
        raise BackendContractError(
            "pinned Trainer resume loader API is unavailable for smoke audit"
        )
    optimizer_loader_fn = cast(Callable[..., Any], optimizer_loader)
    rng_loader_fn = cast(Callable[..., Any], rng_loader)
    model_loader_fn = cast(Callable[..., Any], model_loader)

    def load_model(*args: Any, **kwargs: Any) -> Any:
        result = model_loader_fn(*args, **kwargs)
        phase_1_path = checkpoint.parent / "resume-audits" / (f"phase-1-rank-{rank}.json")
        try:
            phase_1 = json.loads(phase_1_path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise BackendContractError(
                f"cannot read phase-1 trainable state evidence: {exc}"
            ) from exc
        loaded_adapter = {
            name: parameter.detach()
            for name, parameter in trainer.model.named_parameters()
            if parameter.requires_grad
        }
        audit["phase_1_evidence_path"] = str(phase_1_path)
        audit["checkpoint_trainable_parameter_sha256"] = phase_1.get(
            "trainable_parameter_state_sha256"
        )
        audit["loaded_trainable_parameter_sha256"] = _state_digest(loaded_adapter)
        audit["model_state_equal"] = (
            audit["checkpoint_trainable_parameter_sha256"]
            == audit["loaded_trainable_parameter_sha256"]
        )
        audit["model_loader_called"] = True
        return result

    def load_optimizer(*args: Any, **kwargs: Any) -> Any:
        result = optimizer_loader_fn(*args, **kwargs)
        optimizer_file = checkpoint / "optimizer.pt"
        scheduler_file = checkpoint / "scheduler.pt"
        if not optimizer_file.is_file() or not scheduler_file.is_file():
            raise BackendContractError(
                "checkpoint lacks optimizer.pt or scheduler.pt for resume audit"
            )
        expected_optimizer = torch.load(
            optimizer_file,
            map_location="cpu",
            weights_only=False,
        )
        expected_scheduler = torch.load(
            scheduler_file,
            map_location="cpu",
            weights_only=False,
        )
        actual_optimizer = trainer.optimizer.state_dict()
        actual_scheduler = trainer.lr_scheduler.state_dict()
        audit["checkpoint_optimizer_sha256"] = _state_digest(expected_optimizer)
        audit["loaded_optimizer_sha256"] = _state_digest(actual_optimizer)
        audit["checkpoint_scheduler_sha256"] = _state_digest(expected_scheduler)
        audit["loaded_scheduler_sha256"] = _state_digest(actual_scheduler)
        audit["optimizer_state_equal"] = (
            audit["checkpoint_optimizer_sha256"] == audit["loaded_optimizer_sha256"]
        )
        audit["scheduler_state_equal"] = (
            audit["checkpoint_scheduler_sha256"] == audit["loaded_scheduler_sha256"]
        )
        return result

    def load_rng(*args: Any, **kwargs: Any) -> Any:
        result = rng_loader_fn(*args, **kwargs)
        candidates = (
            checkpoint / f"rng_state_{rank}.pth",
            checkpoint / "rng_state.pth",
        )
        rng_file = next((path for path in candidates if path.is_file()), None)
        if rng_file is None:
            raise BackendContractError("checkpoint lacks the rank RNG state file")
        expected = torch.load(rng_file, map_location="cpu", weights_only=False)
        current: dict[str, Any] = {
            "python": random.getstate(),
            "numpy": np.random.get_state(),
            "cpu": torch.random.get_rng_state(),
        }
        if torch.cuda.is_available():
            current["cuda"] = torch.cuda.random.get_rng_state_all()
        comparisons: dict[str, bool] = {}
        required_rng = {"python", "numpy", "cpu", "cuda"}
        for key in required_rng:
            comparisons[key] = (
                key in expected
                and key in current
                and _state_digest(expected[key]) == _state_digest(current[key])
            )
        audit["checkpoint_rng_sha256"] = _state_digest(expected)
        audit["loaded_rng_sha256"] = _state_digest(current)
        audit["rng_components_equal"] = comparisons
        audit["rng_state_equal"] = bool(comparisons) and all(comparisons.values())
        return result

    trainer._load_from_checkpoint = load_model
    trainer._load_optimizer_and_scheduler = load_optimizer
    trainer._load_rng_state = load_rng
    return audit


def run(runtime: Mapping[str, Any]) -> int:
    """Execute one frozen plan after launcher's environment gate succeeds."""

    output = Path(str(runtime["output_dir"])).resolve()
    output.mkdir(parents=True, exist_ok=True)
    completion_marker = output / "training-complete.json"
    if completion_marker.exists():
        raise BackendContractError(f"refusing to rerun completed training: {completion_marker}")
    from transformers.trainer_utils import get_last_checkpoint

    last_checkpoint = get_last_checkpoint(str(output))
    process_pid = os.getpid()
    trainer_kind = str(runtime["trainer_kind"])
    ledger_path: Path | None = None
    if trainer_kind != "sft":
        rank, _ = _rank_budget(runtime)
        live_ledger = output / "token-ledgers" / f"rank-{rank}.json"
        live_trace = output / "reward-traces" / f"rank-{rank}.jsonl"
        if last_checkpoint:
            _restore_accounting_frontier(
                checkpoint=Path(last_checkpoint),
                output=output,
                rank=rank,
            )
        elif live_ledger.exists() or live_trace.exists():
            raise BackendContractError(
                "uncheckpointed accounting exists without a Trainer checkpoint; "
                "start a fresh run directory"
            )
    if trainer_kind == "sft":
        trainer, prepared, _ = _train_sft(runtime)
    else:
        trainer, prepared, _, ledger_path = _train_rl(runtime)
    rank = int(os.environ.get("RANK", "0"))
    resume_load_audit: dict[str, Any] | None = None
    if trainer_kind != "sft" and last_checkpoint is not None:
        # Restores the policy adapter TRL's ref/ subdir makes the pinned loader
        # skip; no-op for beta == 0 arms. Composes under the smoke audit below.
        _install_default_adapter_restore(trainer, Path(last_checkpoint), rank=rank)
    if runtime.get("run_mode") == "smoke" and last_checkpoint is not None:
        resume_load_audit = _install_resume_load_audit(
            trainer,
            Path(last_checkpoint),
            rank=rank,
        )
    result = trainer.train(resume_from_checkpoint=last_checkpoint)
    actual_optimizer_steps = int(getattr(trainer.state, "global_step", -1))
    import torch

    distributed = torch.distributed
    boundary_path = output / "smoke-resume-boundary.json"
    if (
        runtime.get("run_mode") == "smoke"
        and last_checkpoint is None
        and actual_optimizer_steps == 5
        and not boundary_path.exists()
    ):
        if distributed.is_available() and distributed.is_initialized():
            distributed.barrier()
        checkpoint = output / "checkpoint-5"
        phase_memory_path = output / "resume-audits" / f"phase-1-rank-{rank}.json"
        atomic_write_json(
            phase_memory_path,
            {
                "rank": rank,
                "trainable_parameter_state_sha256": _state_digest(
                    {
                        name: parameter.detach()
                        for name, parameter in trainer.model.named_parameters()
                        if parameter.requires_grad
                    }
                ),
                "max_gpu_memory_allocated_bytes": int(torch.cuda.max_memory_allocated())
                if torch.cuda.is_available()
                else None,
                "max_gpu_memory_reserved_bytes": int(torch.cuda.max_memory_reserved())
                if torch.cuda.is_available()
                else None,
            },
        )
        if distributed.is_available() and distributed.is_initialized():
            distributed.barrier()
        if rank == 0:
            if not checkpoint.is_dir():
                raise BackendContractError("forced smoke resume boundary has no checkpoint-5")
            frontier_rows = []
            for ledger_rank in range(int(runtime["world_size"])):
                ledger_snapshot, trace_snapshot, frontier = _accounting_frontier_paths(
                    checkpoint,
                    rank=ledger_rank,
                )
                if not all(path.is_file() for path in (ledger_snapshot, trace_snapshot, frontier)):
                    raise BackendContractError(
                        f"checkpoint-5 accounting frontier missing for rank {ledger_rank}"
                    )
                frontier_rows.append(
                    {
                        "rank": ledger_rank,
                        "ledger": str(ledger_snapshot),
                        "reward_trace": str(trace_snapshot),
                        "frontier": str(frontier),
                    }
                )
            launch_manifest = _mapping(runtime.get("_launch_manifest"), "verified launch manifest")
            phase_memory = [
                {
                    **json.loads(
                        (output / "resume-audits" / f"phase-1-rank-{memory_rank}.json").read_text(
                            encoding="utf-8"
                        )
                    ),
                    "path": str(output / "resume-audits" / f"phase-1-rank-{memory_rank}.json"),
                }
                for memory_rank in range(int(runtime["world_size"]))
            ]
            atomic_write_json(
                boundary_path,
                {
                    "schema_version": 1,
                    "kind": "forced_new_process_smoke_resume_boundary",
                    "status": "awaiting_new_process_resume",
                    "optimizer_step": 5,
                    "first_process_pid": process_pid,
                    "checkpoint_path": str(checkpoint),
                    "accounting_frontiers": frontier_rows,
                    "phase_1_rank_memory": phase_memory,
                    "frozen_config_sha256": launch_manifest["frozen_config_sha256"],
                    "run_manifest_sha256": launch_manifest["run_manifest_sha256"],
                },
            )
        if distributed.is_available() and distributed.is_initialized():
            distributed.barrier()
        # The smoke matrix wrapper observes the durable boundary and launches
        # the exact same frozen plan in a new process.
        return 75
    if trainer_kind != "sft" and actual_optimizer_steps != int(runtime["max_optimizer_steps"]):
        raise BackendContractError(
            "RL run ended at "
            f"{actual_optimizer_steps} optimizer steps; expected "
            f"{runtime['max_optimizer_steps']}"
        )
    if resume_load_audit is not None:
        required = (
            resume_load_audit.get("model_loader_called") is True
            and resume_load_audit.get("model_state_equal") is True
            and resume_load_audit.get("optimizer_state_equal") is True
            and resume_load_audit.get("scheduler_state_equal") is True
            and resume_load_audit.get("rng_state_equal") is True
        )
        resume_load_audit["status"] = "passed" if required else "failed"
        if not required:
            raise BackendContractError(f"Trainer resume-state audit failed: {resume_load_audit}")
        atomic_write_json(
            output / "resume-audits" / f"phase-2-rank-{rank}.json",
            resume_load_audit,
        )
    final_adapter = output / "final-adapter"
    trainer.save_model(str(final_adapter))

    realized_completion_tokens = 0
    realized_completion_count = 0
    max_gpu_memory_allocated = (
        int(torch.cuda.max_memory_allocated()) if torch.cuda.is_available() else 0
    )
    max_gpu_memory_reserved = (
        int(torch.cuda.max_memory_reserved()) if torch.cuda.is_available() else 0
    )
    if ledger_path is not None:
        ledger_value = json.loads(ledger_path.read_text(encoding="utf-8"))
        realized_completion_tokens = int(ledger_value["consumed_tokens"])
        entries = ledger_value.get("entries")
        if not isinstance(entries, list):
            raise BackendContractError("completion ledger entries are malformed")
        realized_completion_count = len(entries)
    if torch.distributed.is_available() and torch.distributed.is_initialized():
        device = torch.device("cuda", torch.cuda.current_device())
        totals = torch.tensor(
            [realized_completion_tokens, realized_completion_count],
            dtype=torch.int64,
            device=device,
        )
        torch.distributed.all_reduce(totals, op=torch.distributed.ReduceOp.SUM)
        realized_completion_tokens = int(totals[0].item())
        realized_completion_count = int(totals[1].item())
        memory = torch.tensor(
            [max_gpu_memory_allocated, max_gpu_memory_reserved],
            dtype=torch.int64,
            device=device,
        )
        torch.distributed.all_reduce(memory, op=torch.distributed.ReduceOp.MAX)
        max_gpu_memory_allocated = int(memory[0].item())
        max_gpu_memory_reserved = int(memory[1].item())
        torch.distributed.barrier()
    if rank == 0:
        metrics = getattr(result, "metrics", {})
        launch_manifest = _mapping(runtime.get("_launch_manifest"), "verified launch manifest")
        parameter_rows, parameter_sha = trainable_parameter_manifest(trainer.model)
        ledger_manifest: list[dict[str, Any]] = []
        observed_slot_generations: dict[str, set[int]] = {}
        if trainer_kind != "sft":
            expected_config_sha = canonical_json_hash(dict(runtime))
            for ledger_rank in range(int(runtime["world_size"])):
                ledger_file = output / "token-ledgers" / f"rank-{ledger_rank}.json"
                _, remainder = divmod(
                    int(runtime["max_completion_tokens_per_run"]),
                    int(runtime["world_size"]),
                )
                base_cap = int(runtime["max_completion_tokens_per_run"]) // int(
                    runtime["world_size"]
                )
                expected_cap = base_cap + (1 if ledger_rank < remainder else 0)
                loaded = CompletionTokenLedger.load(
                    ledger_file,
                    expected_run_id=f"{runtime['run_id']}:rank-{ledger_rank}",
                    expected_max_tokens=expected_cap,
                    expected_config_sha256=expected_config_sha,
                    expected_data_manifest_sha256=prepared.dataset_sha256,
                    expected_comparison_slot_manifest_sha256=str(
                        runtime["comparison_slot_manifest_sha256"]
                    ),
                )
                ledger_value = json.loads(ledger_file.read_text(encoding="utf-8"))
                for entry in ledger_value["entries"]:
                    slot_id = entry.get("slot_id")
                    generation_index = entry.get("generation_index")
                    if not isinstance(slot_id, str) or not isinstance(generation_index, int):
                        raise BackendContractError("ledger lacks measured slot/generation identity")
                    observed_slot_generations.setdefault(slot_id, set()).add(generation_index)
                ledger_manifest.append(
                    {
                        "rank": ledger_rank,
                        "path": str(ledger_file),
                        "completion_count": loaded.completion_count,
                        "consumed_tokens": loaded.consumed_tokens,
                    }
                )
            if sum(row["consumed_tokens"] for row in ledger_manifest) != (
                realized_completion_tokens
            ):
                raise BackendContractError("rank ledger token totals disagree")
            if sum(row["completion_count"] for row in ledger_manifest) != (
                realized_completion_count
            ):
                raise BackendContractError("rank ledger completion totals disagree")
            expected_completion_count = (
                int(runtime["max_optimizer_steps"])
                * int(runtime["per_device_train_batch_size"])
                * int(runtime["gradient_accumulation_steps"])
                * int(runtime["world_size"])
            )
            if realized_completion_count != expected_completion_count:
                raise BackendContractError(
                    f"realized {realized_completion_count} completions; "
                    f"expected {expected_completion_count}"
                )
            expected_generations = set(range(int(runtime["generations_per_prompt"])))
            if any(
                generations != expected_generations
                for generations in observed_slot_generations.values()
            ):
                raise BackendContractError(
                    "one or more sampled slots lack the exact generation index set"
                )
            expected_unique_slots = expected_completion_count // int(
                runtime["generations_per_prompt"]
            )
            if len(observed_slot_generations) != expected_unique_slots:
                raise BackendContractError(
                    f"measured {len(observed_slot_generations)} unique slots; "
                    f"expected {expected_unique_slots}"
                )
        trace_manifest: list[dict[str, Any]] = []
        malformed_completion_count = 0
        completion_truncation_count = 0
        if trainer_kind != "sft":
            for trace_rank in range(int(runtime["world_size"])):
                trace_file = output / "reward-traces" / f"rank-{trace_rank}.jsonl"
                traces = list(read_jsonl(trace_file))
                ledger_row = ledger_manifest[trace_rank]
                if len(traces) != ledger_row["completion_count"]:
                    raise BackendContractError(
                        f"rank {trace_rank} reward trace/ledger row-count mismatch"
                    )
                invalid = sum(1 for trace in traces if trace.get("parser_valid") is not True)
                malformed_completion_count += invalid
                truncated = sum(1 for trace in traces if trace.get("terminated") is False)
                completion_truncation_count += truncated
                trace_manifest.append(
                    {
                        "rank": trace_rank,
                        "path": str(trace_file),
                        "row_count": len(traces),
                        "malformed_completion_count": invalid,
                        "completion_truncation_count": truncated,
                    }
                )
        checkpoint_manifest = []
        for checkpoint in sorted(
            output.glob("checkpoint-*"),
            key=lambda path: int(path.name.removeprefix("checkpoint-")),
        ):
            if checkpoint.is_dir():
                checkpoint_manifest.append(
                    {
                        "optimizer_step": int(checkpoint.name.removeprefix("checkpoint-")),
                        "path": str(checkpoint),
                    }
                )
        resume_probe: dict[str, Any] | None = None
        if runtime.get("run_mode") == "smoke":
            try:
                boundary = json.loads(boundary_path.read_text(encoding="utf-8"))
            except (OSError, json.JSONDecodeError) as exc:
                raise BackendContractError(
                    f"completed smoke lacks forced resume boundary: {exc}"
                ) from exc
            checkpoint_5 = output / "checkpoint-5"
            if (
                not isinstance(boundary, dict)
                or boundary.get("optimizer_step") != 5
                or boundary.get("first_process_pid") == process_pid
                or Path(str(last_checkpoint)).resolve() != checkpoint_5.resolve()
                or not checkpoint_5.is_dir()
            ):
                raise BackendContractError(
                    "smoke did not resume checkpoint-5 in a distinct process"
                )
            rank_resume_audits = []
            for resume_rank in range(int(runtime["world_size"])):
                audit_path = output / "resume-audits" / f"phase-2-rank-{resume_rank}.json"
                audit = json.loads(audit_path.read_text(encoding="utf-8"))
                rank_resume_audits.append(
                    {
                        **audit,
                        "path": str(audit_path),
                    }
                )
            if any(audit.get("status") != "passed" for audit in rank_resume_audits):
                raise BackendContractError("one or more rank resume-load audits failed")
            resume_probe = {
                "status": "passed",
                "checkpoint_step": 5,
                "resumed_to_step": actual_optimizer_steps,
                "first_process_pid": boundary["first_process_pid"],
                "resumed_process_pid": process_pid,
                "accounting_frontiers": boundary["accounting_frontiers"],
                "phase_1_rank_evidence": boundary["phase_1_rank_memory"],
                "rank_resume_load_audits": rank_resume_audits,
            }
            phase_1_memory = boundary.get("phase_1_rank_memory", [])
            if not isinstance(phase_1_memory, list):
                raise BackendContractError("smoke phase-1 memory evidence is malformed")
            max_gpu_memory_allocated = max(
                [max_gpu_memory_allocated]
                + [
                    int(row["max_gpu_memory_allocated_bytes"])
                    for row in phase_1_memory
                    if row.get("max_gpu_memory_allocated_bytes") is not None
                ]
            )
            max_gpu_memory_reserved = max(
                [max_gpu_memory_reserved]
                + [
                    int(row["max_gpu_memory_reserved_bytes"])
                    for row in phase_1_memory
                    if row.get("max_gpu_memory_reserved_bytes") is not None
                ]
            )
        log_history = [
            dict(row)
            for row in getattr(trainer.state, "log_history", [])
            if isinstance(row, Mapping)
        ]
        atomic_write_json(
            completion_marker,
            {
                "schema_version": 4,
                "status": "completed",
                "trained": True,
                "run_id": runtime["run_id"],
                "trainer_kind": trainer_kind,
                "run_mode": runtime["run_mode"],
                "arm": runtime["arm"],
                "dataset_sha256": prepared.dataset_sha256,
                "record_count": prepared.record_count,
                "assistant_token_count": prepared.assistant_token_count,
                "optimizer_steps": actual_optimizer_steps,
                "realized_sampled_completion_tokens": realized_completion_tokens
                if trainer_kind != "sft"
                else None,
                "realized_sampled_completion_count": realized_completion_count
                if trainer_kind != "sft"
                else None,
                "sampled_completion_token_safety_ceiling": runtime["max_completion_tokens_per_run"]
                if trainer_kind != "sft"
                else None,
                "comparison_slot_manifest_sha256": runtime.get("comparison_slot_manifest_sha256"),
                "rank_0_ledger": str(ledger_path) if ledger_path else None,
                "rank_ledger_manifest": ledger_manifest,
                "rank_reward_trace_manifest": trace_manifest,
                "prompt_truncation_count": 0,
                "completion_truncation_count": completion_truncation_count,
                "oom_count": 0,
                "malformed_completion_count": malformed_completion_count
                if trainer_kind != "sft"
                else None,
                "unique_prompt_groups_consumed": (
                    len(observed_slot_generations) if trainer_kind != "sft" else None
                ),
                "checkpoint_manifest": checkpoint_manifest,
                "forced_process_resume_probe": resume_probe,
                "final_adapter": str(final_adapter),
                "trainable_parameters": parameter_rows,
                "trainable_parameter_manifest_sha256": parameter_sha,
                "base_model_revision": runtime["model_revision"],
                "base_model_snapshot_sha256": runtime["model_snapshot_sha256"],
                "environment_lock_sha256": runtime["environment_lock_sha256"],
                "evaluation_manifest_sha256": runtime["evaluation_manifest_sha256"],
                "system_prompt_sha256": runtime["system_prompt_sha256"],
                "papo_config": runtime.get("papo_config"),
                "evi_po_config": runtime.get("evi_po_config"),
                "frozen_config_sha256": launch_manifest["frozen_config_sha256"],
                "run_manifest_sha256": launch_manifest["run_manifest_sha256"],
                "code_commit": launch_manifest["code_commit"],
                "metrics": metrics if isinstance(metrics, Mapping) else {},
                "log_history": log_history,
                "max_gpu_memory_allocated_bytes": (
                    max_gpu_memory_allocated if torch.cuda.is_available() else None
                ),
                "max_gpu_memory_reserved_bytes": (
                    max_gpu_memory_reserved if torch.cuda.is_available() else None
                ),
                "papo_gpu_contract_probe": getattr(
                    trainer,
                    "papo_gpu_contract_probe",
                    None,
                ),
                "evi_gpu_contract_probe": getattr(
                    trainer,
                    "evi_gpu_contract_probe",
                    None,
                ),
            },
        )
    # On completion of a real (non-smoke) run, amend the frozen run-manifest so
    # the pushed artifact reports ``completed`` / ``trained=True`` with the
    # realized optimizer step count, instead of the perpetual ``planned`` state
    # it was frozen with. The original frozen-plan hash is preserved verbatim
    # inside the ``completion`` block for provenance, and the smoke path is
    # excluded so smoke_gate's manifest-hash invariant stays intact. This
    # amendment happens only after the optimizer-step contract above has
    # passed and the completion marker is durable, so it never affects a run
    # that might still resume. The amendment writes a single shared run-manifest
    # file, so it must run on rank 0 only: ``launch_manifest`` is bound inside
    # the ``if rank == 0`` block above, and on multi-rank runs rank != 0 would
    # otherwise reach this reference unbound (UnboundLocalError) and also race
    # rank 0 on the same file.
    if rank == 0 and str(runtime["run_mode"]) != "smoke":
        manifest_path = Path(launch_manifest["run_manifest_path"])
        completed_manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        completed_manifest["status"] = "completed"
        completed_manifest["trained"] = True
        completed_manifest["completion"] = {
            "optimizer_steps": actual_optimizer_steps,
            "code_commit": current_code_commit(),
            "frozen_code_commit": launch_manifest["code_commit"],
            "run_manifest_sha256": launch_manifest["run_manifest_sha256"],
            "frozen_config_sha256": launch_manifest["frozen_config_sha256"],
        }
        atomic_write_json(manifest_path, completed_manifest)
    return 0