asupersync 0.4.8

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
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
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
//! Lab runtime for deterministic execution.
//!
//! The lab runtime executes tasks with:
//! - Virtual time (controlled advancement)
//! - Deterministic scheduling (seed-driven)
//! - Trace capture for replay
//! - Chaos injection for stress testing

use super::config::LabConfig;
use super::oracle::OracleSuite;
use crate::lab::chaos::{ChaosRng, ChaosStats};
use crate::record::ObligationKind;
use crate::record::task::TaskState;
use crate::runtime::RuntimeState;
use crate::runtime::config::ObligationLeakResponse;
use crate::runtime::deadline_monitor::{
    DeadlineMonitor, DeadlineWarning, MonitorConfig, default_warning_handler,
};
use crate::runtime::reactor::LabReactor;
use crate::runtime::scheduler::priority::ExactDispatchError;
use crate::runtime::scheduler::{DispatchLane, ScheduleCertificate};
use crate::time::VirtualClock;
use crate::trace::TraceBufferHandle;
use crate::trace::crashpack::{
    CrashPack, CrashPackConfig, CrashPackWriteError, CrashPackWriter, FailureInfo, FailureOutcome,
    FileCrashPackWriter, ReplayCommand, artifact_filename,
};
use crate::trace::event::TraceEventKind;
use crate::trace::recorder::TraceRecorder;
use crate::trace::replay::{CompactTaskId, ReplayEvent, ReplayTrace, TraceMetadata};
use crate::trace::scoring::seed_fingerprint;
use crate::trace::{TraceData, TraceEvent, check_refinement_firewall};
use crate::trace::{canonicalize::trace_fingerprint, certificate::TraceCertificate};
use crate::types::Time;
use crate::types::{ObligationId, RegionId, TaskId};
use crate::util::det_hash::{DetHashMap, DetHashSet};
use crate::util::{ArenaIndex, DetEntropy, DetRng};
use parking_lot::Mutex;
use sha2::{Digest, Sha256};
use std::path::PathBuf;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use std::{fmt, future::Future};

const AUTO_ARTIFACTS_ENV: &str = "ASUPERSYNC_AUTO_ARTIFACTS";
const TEST_ARTIFACTS_DIR_ENV: &str = "ASUPERSYNC_TEST_ARTIFACTS_DIR";
const LAB_TEST_SEED_ENV: &str = "ASUPERSYNC_LAB_TEST_SEED";
const LAB_TEST_WORKERS_ENV: &str = "ASUPERSYNC_WORKERS";
const LAB_TEST_MAX_STEPS_ENV: &str = "ASUPERSYNC_MAX_STEPS";
#[cfg(test)]
const PLAIN_RUNNER_FAILURE_PROBE_ENV: &str = "ASUPERSYNC_PLAIN_RUNNER_FAILURE_PROBE";

/// Summary of a trace certificate built from the current trace buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LabTraceCertificateSummary {
    /// Incremental hash of witnessed events.
    pub event_hash: u64,
    /// Total number of events witnessed.
    pub event_count: u64,
    /// Hash of scheduling decisions (from [`ScheduleCertificate`]).
    pub schedule_hash: u64,
}

/// Schema version for the exact lab dispatch projection.
pub const FORCED_SCHEDULE_SCHEMA_VERSION: u32 = 1;

/// Fixed magic prefix for a canonical [`ForcedSchedule`] artifact.
pub const FORCED_SCHEDULE_ARTIFACT_MAGIC: [u8; 8] = *b"ASUPFSC\0";

/// Canonical artifact codec version.
pub const FORCED_SCHEDULE_ARTIFACT_VERSION: u32 = 1;

/// Schema version for a reduced exact-dispatch candidate.
pub const FORCED_SCHEDULE_CANDIDATE_SCHEMA_VERSION: u32 = 1;

const FORCED_SCHEDULE_ARTIFACT_HEADER_LEN: usize = 40;
const FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN: usize = 29;
const FORCED_SCHEDULE_ARTIFACT_TERMINAL_LEN: usize = 26;
const FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN: usize = 32;
const FORCED_SCHEDULE_ARTIFACT_COUNT_OFFSET: usize = 32;

/// Caller-owned resource bounds for decoding one forced-schedule artifact.
///
/// The decoder checks all three limits before reserving the dispatch vector.
/// `max_decoded_dispatch_bytes` bounds the in-memory `ForcedDispatch`
/// storage independently of the more compact wire representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedScheduleDecodeLimits {
    /// Maximum admitted encoded artifact length.
    pub max_encoded_bytes: usize,
    /// Maximum admitted dispatch count.
    pub max_dispatches: usize,
    /// Maximum admitted decoded dispatch-vector storage.
    pub max_decoded_dispatch_bytes: usize,
}

impl ForcedScheduleDecodeLimits {
    /// Creates explicit encoded-byte, dispatch-count, and allocation bounds.
    #[must_use]
    pub const fn new(
        max_encoded_bytes: usize,
        max_dispatches: usize,
        max_decoded_dispatch_bytes: usize,
    ) -> Self {
        Self {
            max_encoded_bytes,
            max_dispatches,
            max_decoded_dispatch_bytes,
        }
    }
}

/// One scheduler choice captured before the selected task was polled.
///
/// Unlike [`ReplayEvent::TaskScheduled`], this lab-only projection retains the
/// modeled worker and authoritative lane. That distinction is load-bearing for
/// exact replay: a task chosen from the wrong lane can change cancellation and
/// fairness semantics even when the task ID happens to match.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedDispatch {
    task: CompactTaskId,
    worker: u32,
    lane: DispatchLane,
    at_step: u64,
    at_nanos: u64,
}

impl ForcedDispatch {
    /// Full arena identity (slot plus generation) of the selected task.
    #[must_use]
    pub const fn task(&self) -> CompactTaskId {
        self.task
    }

    /// Modeled worker that performed the dispatch.
    #[must_use]
    pub const fn worker(&self) -> u32 {
        self.worker
    }

    /// Authoritative lane used for the dispatch.
    #[must_use]
    pub const fn lane(&self) -> DispatchLane {
        self.lane
    }

    /// Deterministic lab step at which the task was selected.
    #[must_use]
    pub const fn at_step(&self) -> u64 {
        self.at_step
    }

    /// Virtual time observed when the task was selected.
    #[must_use]
    pub const fn at_nanos(&self) -> u64 {
        self.at_nanos
    }
}

/// Complete, versioned exact-dispatch projection from one lab execution.
///
/// The projection is deliberately not a production scheduler-control format.
/// It can only be applied to a fresh [`LabRuntime`] with the same configuration,
/// and every task generation, worker, lane, step, and virtual-time value is
/// revalidated before polling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForcedSchedule {
    version: u32,
    seed: u64,
    config_hash: u64,
    dispatches: Vec<ForcedDispatch>,
    terminal_steps: u64,
    terminal_nanos: u64,
    terminal_schedule_hash: u64,
    terminal_quiescent: bool,
    truncated: bool,
}

/// One retained source dispatch in a reduced schedule candidate.
///
/// The fields are private so a caller can delete source choices but cannot
/// synthesize a new task identity, worker, lane, step, or timestamp. Candidate
/// execution uses the task/worker/lane tuple as the scheduler authority; the
/// source step and time remain provenance rather than terminal expectations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedScheduleCandidateDispatch {
    source_index: usize,
    dispatch: ForcedDispatch,
}

impl ForcedScheduleCandidateDispatch {
    /// Index of this dispatch in the complete captured source schedule.
    #[must_use]
    pub const fn source_index(&self) -> usize {
        self.source_index
    }

    /// Exact task generation retained from the source schedule.
    #[must_use]
    pub const fn task(&self) -> CompactTaskId {
        self.dispatch.task
    }

    /// Modeled worker retained from the source schedule.
    #[must_use]
    pub const fn worker(&self) -> u32 {
        self.dispatch.worker
    }

    /// Authoritative scheduler lane retained from the source schedule.
    #[must_use]
    pub const fn lane(&self) -> DispatchLane {
        self.dispatch.lane
    }

    /// Source step retained for provenance only.
    #[must_use]
    pub const fn source_step(&self) -> u64 {
        self.dispatch.at_step
    }

    /// Source virtual time retained for provenance only.
    #[must_use]
    pub const fn source_nanos(&self) -> u64 {
        self.dispatch.at_nanos
    }
}

/// A bounded, deletion-only candidate derived from one complete schedule.
///
/// This is a lab delta-debugging authority, not a weaker form of exact replay.
/// [`LabRuntime::run_forced_schedule`] continues to validate the complete
/// source terminal receipt. A candidate instead executes only its retained
/// scheduler choices and reports whether that exact subsequence quiesced or
/// was exhausted with work remaining.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForcedScheduleCandidate {
    version: u32,
    source_version: u32,
    seed: u64,
    config_hash: u64,
    source_dispatch_count: usize,
    source_terminal_schedule_hash: u64,
    dispatches: Vec<ForcedScheduleCandidateDispatch>,
}

impl ForcedScheduleCandidate {
    /// Candidate schema version.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Source schedule schema version.
    #[must_use]
    pub const fn source_version(&self) -> u32 {
        self.source_version
    }

    /// Source lab seed.
    #[must_use]
    pub const fn seed(&self) -> u64 {
        self.seed
    }

    /// Stable source execution-configuration hash.
    #[must_use]
    pub const fn config_hash(&self) -> u64 {
        self.config_hash
    }

    /// Number of dispatches in the complete source schedule.
    #[must_use]
    pub const fn source_dispatch_count(&self) -> usize {
        self.source_dispatch_count
    }

    /// Complete source schedule certificate hash retained as provenance.
    #[must_use]
    pub const fn source_terminal_schedule_hash(&self) -> u64 {
        self.source_terminal_schedule_hash
    }

    /// Ordered retained source choices.
    #[must_use]
    pub fn dispatches(&self) -> &[ForcedScheduleCandidateDispatch] {
        &self.dispatches
    }
}

/// Caller-owned admission and execution limits for a reduced candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedScheduleCandidateLimits {
    /// Maximum complete source dispatch count admitted for derivation/replay.
    pub max_source_dispatches: usize,
    /// Maximum retained candidate dispatch count.
    pub max_candidate_dispatches: usize,
    /// Maximum bounded execution actions (scheduler steps or time/event pumps).
    pub max_work_units: u64,
}

impl ForcedScheduleCandidateLimits {
    /// Creates explicit source, candidate, and execution limits.
    #[must_use]
    pub const fn new(
        max_source_dispatches: usize,
        max_candidate_dispatches: usize,
        max_work_units: u64,
    ) -> Self {
        Self {
            max_source_dispatches,
            max_candidate_dispatches,
            max_work_units,
        }
    }
}

/// Terminal classification for a reduced candidate execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForcedScheduleCandidateTermination {
    /// Every retained choice executed and the runtime reached quiescence.
    Quiescent,
    /// Every retained choice executed, but runnable or live work remained.
    Exhausted,
}

/// Observed receipt from executing a reduced schedule candidate.
#[derive(Debug, Clone)]
pub struct ForcedScheduleCandidateReport {
    /// Why candidate execution stopped.
    pub termination: ForcedScheduleCandidateTermination,
    /// Exact source indices consumed, in execution order.
    pub consumed_source_indices: Vec<usize>,
    /// Bounded scheduler-step/time-pump work consumed by the runner.
    pub work_units: u64,
    /// Canonical runtime/oracle report at the candidate boundary.
    pub lab: LabRunReport,
}

impl ForcedSchedule {
    /// Encodes this complete lab receipt into its strict canonical artifact.
    ///
    /// The format is fixed-width and little-endian. A domain-separated SHA-256
    /// checksum covers the header, every dispatch field, and the complete
    /// terminal receipt. This is an integrity binding for immutable lab
    /// evidence, not an authentication or production scheduler-control format.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleArtifactError`] when the receipt is partial,
    /// malformed, too large for the artifact format, or cannot allocate its
    /// exact output.
    pub fn to_canonical_bytes(&self) -> Result<Vec<u8>, ForcedScheduleArtifactError> {
        validate_complete_forced_schedule_shape(self)?;
        let expected_len = forced_schedule_artifact_len(self.dispatches.len())?;
        let mut bytes = Vec::new();
        bytes.try_reserve_exact(expected_len).map_err(|_| {
            ForcedScheduleArtifactError::AllocationFailed {
                requested: expected_len,
            }
        })?;

        bytes.extend_from_slice(&FORCED_SCHEDULE_ARTIFACT_MAGIC);
        bytes.extend_from_slice(&FORCED_SCHEDULE_ARTIFACT_VERSION.to_le_bytes());
        bytes.extend_from_slice(&self.version.to_le_bytes());
        bytes.extend_from_slice(&self.seed.to_le_bytes());
        bytes.extend_from_slice(&self.config_hash.to_le_bytes());
        let dispatch_count = u64::try_from(self.dispatches.len()).map_err(|_| {
            ForcedScheduleArtifactError::LengthOverflow {
                dispatch_count: u64::MAX,
            }
        })?;
        bytes.extend_from_slice(&dispatch_count.to_le_bytes());
        for dispatch in &self.dispatches {
            bytes.extend_from_slice(&dispatch.task.0.to_le_bytes());
            bytes.extend_from_slice(&dispatch.worker.to_le_bytes());
            bytes.push(forced_schedule_lane_tag(dispatch.lane));
            bytes.extend_from_slice(&dispatch.at_step.to_le_bytes());
            bytes.extend_from_slice(&dispatch.at_nanos.to_le_bytes());
        }
        bytes.extend_from_slice(&self.terminal_steps.to_le_bytes());
        bytes.extend_from_slice(&self.terminal_nanos.to_le_bytes());
        bytes.extend_from_slice(&self.terminal_schedule_hash.to_le_bytes());
        bytes.push(u8::from(self.terminal_quiescent));
        bytes.push(u8::from(self.truncated));
        let checksum = forced_schedule_artifact_checksum(&bytes);
        bytes.extend_from_slice(&checksum);
        debug_assert_eq!(bytes.len(), expected_len);
        Ok(bytes)
    }

    /// Decodes and validates one strict canonical forced-schedule artifact.
    ///
    /// Byte, count, decoded-storage, and arithmetic admission all happen before
    /// the dispatch vector is allocated. The reconstructed private authority is
    /// complete and canonical, but [`LabRuntime::run_forced_schedule`] still
    /// revalidates the source seed/config and every task generation, worker,
    /// lane, step, time, and terminal certificate before accepting replay.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleArtifactError`] for an unsupported or
    /// noncanonical artifact, an incomplete source receipt, checksum mismatch,
    /// exceeded caller limit, checked-arithmetic failure, or allocation
    /// refusal.
    pub fn try_from_canonical_bytes(
        bytes: &[u8],
        limits: ForcedScheduleDecodeLimits,
    ) -> Result<Self, ForcedScheduleArtifactError> {
        if bytes.len() > limits.max_encoded_bytes {
            return Err(ForcedScheduleArtifactError::ByteLimitExceeded {
                found: bytes.len(),
                limit: limits.max_encoded_bytes,
            });
        }
        if bytes.len() < FORCED_SCHEDULE_ARTIFACT_HEADER_LEN {
            return Err(ForcedScheduleArtifactError::Truncated {
                expected: FORCED_SCHEDULE_ARTIFACT_HEADER_LEN,
                found: bytes.len(),
            });
        }
        if bytes[..FORCED_SCHEDULE_ARTIFACT_MAGIC.len()] != FORCED_SCHEDULE_ARTIFACT_MAGIC {
            return Err(ForcedScheduleArtifactError::MagicMismatch);
        }
        let artifact_version = forced_schedule_artifact_u32(bytes, 8)?;
        if artifact_version != FORCED_SCHEDULE_ARTIFACT_VERSION {
            return Err(ForcedScheduleArtifactError::VersionMismatch {
                expected: FORCED_SCHEDULE_ARTIFACT_VERSION,
                found: artifact_version,
            });
        }
        let version = forced_schedule_artifact_u32(bytes, 12)?;
        if version != FORCED_SCHEDULE_SCHEMA_VERSION {
            return Err(ForcedScheduleArtifactError::SchemaMismatch {
                expected: FORCED_SCHEDULE_SCHEMA_VERSION,
                found: version,
            });
        }
        let seed = forced_schedule_artifact_u64(bytes, 16)?;
        let config_hash = forced_schedule_artifact_u64(bytes, 24)?;
        let dispatch_count_u64 =
            forced_schedule_artifact_u64(bytes, FORCED_SCHEDULE_ARTIFACT_COUNT_OFFSET)?;
        let dispatch_count = usize::try_from(dispatch_count_u64).map_err(|_| {
            ForcedScheduleArtifactError::LengthOverflow {
                dispatch_count: dispatch_count_u64,
            }
        })?;
        if dispatch_count > limits.max_dispatches {
            return Err(ForcedScheduleArtifactError::DispatchLimitExceeded {
                found: dispatch_count,
                limit: limits.max_dispatches,
            });
        }
        let decoded_dispatch_bytes = dispatch_count
            .checked_mul(std::mem::size_of::<ForcedDispatch>())
            .ok_or(ForcedScheduleArtifactError::LengthOverflow {
                dispatch_count: dispatch_count_u64,
            })?;
        if decoded_dispatch_bytes > limits.max_decoded_dispatch_bytes {
            return Err(
                ForcedScheduleArtifactError::DecodedAllocationLimitExceeded {
                    requested: decoded_dispatch_bytes,
                    limit: limits.max_decoded_dispatch_bytes,
                },
            );
        }

        let expected_len = forced_schedule_artifact_len(dispatch_count)?;
        if bytes.len() < expected_len {
            return Err(ForcedScheduleArtifactError::Truncated {
                expected: expected_len,
                found: bytes.len(),
            });
        }
        if bytes.len() > expected_len {
            return Err(ForcedScheduleArtifactError::TrailingBytes {
                expected: expected_len,
                found: bytes.len(),
            });
        }
        let checksum_offset = expected_len - FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN;
        let actual_checksum = forced_schedule_artifact_checksum(&bytes[..checksum_offset]);
        if bytes[checksum_offset..] != actual_checksum {
            return Err(ForcedScheduleArtifactError::ChecksumMismatch);
        }

        let mut dispatches = Vec::new();
        dispatches.try_reserve_exact(dispatch_count).map_err(|_| {
            ForcedScheduleArtifactError::AllocationFailed {
                requested: decoded_dispatch_bytes,
            }
        })?;
        for index in 0..dispatch_count {
            let offset =
                FORCED_SCHEDULE_ARTIFACT_HEADER_LEN + index * FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN;
            let task = CompactTaskId(forced_schedule_artifact_u64(bytes, offset)?);
            let worker = forced_schedule_artifact_u32(bytes, offset + 8)?;
            let lane_tag = bytes[offset + 12];
            let lane = forced_schedule_lane_from_tag(index, lane_tag)?;
            let at_step = forced_schedule_artifact_u64(bytes, offset + 13)?;
            let at_nanos = forced_schedule_artifact_u64(bytes, offset + 21)?;
            dispatches.push(ForcedDispatch {
                task,
                worker,
                lane,
                at_step,
                at_nanos,
            });
        }
        let terminal_offset = FORCED_SCHEDULE_ARTIFACT_HEADER_LEN
            + dispatch_count * FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN;
        let terminal_steps = forced_schedule_artifact_u64(bytes, terminal_offset)?;
        let terminal_nanos = forced_schedule_artifact_u64(bytes, terminal_offset + 8)?;
        let terminal_schedule_hash = forced_schedule_artifact_u64(bytes, terminal_offset + 16)?;
        let terminal_quiescent =
            forced_schedule_bool(bytes[terminal_offset + 24], "terminal_quiescent")?;
        let truncated = forced_schedule_bool(bytes[terminal_offset + 25], "truncated")?;
        let schedule = Self {
            version,
            seed,
            config_hash,
            dispatches,
            terminal_steps,
            terminal_nanos,
            terminal_schedule_hash,
            terminal_quiescent,
            truncated,
        };
        validate_complete_forced_schedule_shape(&schedule)?;
        if schedule.to_canonical_bytes()?.as_slice() != bytes {
            return Err(ForcedScheduleArtifactError::NonCanonical);
        }
        Ok(schedule)
    }

    /// Projection schema version.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Source lab seed.
    #[must_use]
    pub const fn seed(&self) -> u64 {
        self.seed
    }

    /// Stable source execution-configuration hash.
    #[must_use]
    pub const fn config_hash(&self) -> u64 {
        self.config_hash
    }

    /// Ordered exact dispatches.
    #[must_use]
    pub fn dispatches(&self) -> &[ForcedDispatch] {
        &self.dispatches
    }

    /// Source run terminal step.
    #[must_use]
    pub const fn terminal_steps(&self) -> u64 {
        self.terminal_steps
    }

    /// Source run terminal virtual time.
    #[must_use]
    pub const fn terminal_nanos(&self) -> u64 {
        self.terminal_nanos
    }

    /// Source run terminal schedule-certificate hash.
    #[must_use]
    pub const fn terminal_schedule_hash(&self) -> u64 {
        self.terminal_schedule_hash
    }

    /// Whether the source terminated in structured quiescence.
    #[must_use]
    pub const fn terminal_quiescent(&self) -> bool {
        self.terminal_quiescent
    }

    /// Whether bounded source capture truncated dispatch evidence.
    #[must_use]
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Derives a deletion-only candidate from ordered source indices.
    ///
    /// Every retained dispatch is copied from this complete source receipt.
    /// Callers can therefore remove choices but cannot synthesize task IDs or
    /// scheduler metadata. The source itself is bounded and shape-validated
    /// before any candidate allocation.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleError`] when the source is partial or malformed,
    /// a caller limit is zero/exhausted, indices are duplicated/reordered/out of
    /// range, or bounded candidate allocation fails.
    pub fn derive_candidate(
        &self,
        retained_source_indices: &[usize],
        limits: ForcedScheduleCandidateLimits,
    ) -> Result<ForcedScheduleCandidate, ForcedScheduleError> {
        validate_candidate_limits(limits)?;
        if self.version != FORCED_SCHEDULE_SCHEMA_VERSION {
            return Err(ForcedScheduleError::SchemaMismatch {
                expected: FORCED_SCHEDULE_SCHEMA_VERSION,
                found: self.version,
            });
        }
        if self.truncated || !self.terminal_quiescent {
            return Err(ForcedScheduleError::PartialSource);
        }
        if self.dispatches.len() > limits.max_source_dispatches {
            return Err(ForcedScheduleError::CandidateSourceLimitExceeded {
                found: self.dispatches.len(),
                limit: limits.max_source_dispatches,
            });
        }
        if retained_source_indices.len() > limits.max_candidate_dispatches {
            return Err(ForcedScheduleError::DispatchLimitExceeded {
                found: retained_source_indices.len(),
                limit: limits.max_candidate_dispatches,
            });
        }

        validate_dispatch_order(&self.dispatches)?;
        if self.dispatches.last().is_some_and(|dispatch| {
            dispatch.at_step > self.terminal_steps || dispatch.at_nanos > self.terminal_nanos
        }) {
            return Err(ForcedScheduleError::PartialSource);
        }

        let mut dispatches = Vec::new();
        dispatches
            .try_reserve_exact(retained_source_indices.len())
            .map_err(|_| ForcedScheduleError::CandidateAllocationFailed {
                requested: retained_source_indices.len(),
            })?;
        let mut previous = None;
        for (candidate_index, &source_index) in retained_source_indices.iter().enumerate() {
            if let Some(previous) = previous
                && source_index <= previous
            {
                return Err(ForcedScheduleError::CandidateIndexOrder {
                    candidate_index,
                    previous,
                    next: source_index,
                });
            }
            let Some(&dispatch) = self.dispatches.get(source_index) else {
                return Err(ForcedScheduleError::CandidateIndexOutOfRange {
                    candidate_index,
                    source_index,
                    source_len: self.dispatches.len(),
                });
            };
            dispatches.push(ForcedScheduleCandidateDispatch {
                source_index,
                dispatch,
            });
            previous = Some(source_index);
        }

        Ok(ForcedScheduleCandidate {
            version: FORCED_SCHEDULE_CANDIDATE_SCHEMA_VERSION,
            source_version: self.version,
            seed: self.seed,
            config_hash: self.config_hash,
            source_dispatch_count: self.dispatches.len(),
            source_terminal_schedule_hash: self.terminal_schedule_hash,
            dispatches,
        })
    }
}

/// Caller-owned admission limits for forced lab execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedScheduleLimits {
    /// Maximum number of dispatch records the caller will admit.
    pub max_dispatches: usize,
    /// Maximum lab steps the forced runner may execute.
    pub max_steps: u64,
}

impl ForcedScheduleLimits {
    /// Creates explicit forced-execution limits.
    #[must_use]
    pub const fn new(max_dispatches: usize, max_steps: u64) -> Self {
        Self {
            max_dispatches,
            max_steps,
        }
    }
}

/// Successful exact forced-schedule execution receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForcedScheduleReport {
    /// Number of exact dispatch records consumed.
    pub dispatches: usize,
    /// Number of lab steps executed by this call.
    pub steps: u64,
    /// Terminal virtual time.
    pub terminal_nanos: u64,
    /// Terminal schedule-certificate hash.
    pub schedule_hash: u64,
    /// Whether the runtime reached structured quiescence.
    pub quiescent: bool,
}

/// Fail-closed forced-schedule admission or execution error.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ForcedScheduleError {
    /// Recording was requested with a zero event limit.
    #[error("forced schedule recording requires a nonzero dispatch limit")]
    ZeroRecordingLimit,
    /// A recorder is already active on this runtime.
    #[error("forced schedule recording is already active")]
    RecordingAlreadyActive,
    /// No recorder is active on this runtime.
    #[error("forced schedule recording is not active")]
    RecordingNotActive,
    /// The source execution exceeded its recording limit.
    #[error("forced schedule recording exceeded its limit of {max_dispatches} dispatches")]
    RecordingLimitExceeded {
        /// Configured source recording limit.
        max_dispatches: usize,
    },
    /// A candidate limit was configured as zero.
    #[error("forced schedule candidate limit {limit_name} must be nonzero")]
    ZeroCandidateLimit {
        /// Stable name of the invalid limit.
        limit_name: &'static str,
    },
    /// The complete source schedule exceeds caller admission.
    #[error("forced schedule candidate source has {found} dispatches, limit is {limit}")]
    CandidateSourceLimitExceeded {
        /// Complete source dispatch count.
        found: usize,
        /// Caller-owned source admission bound.
        limit: usize,
    },
    /// Retained source indices are not strictly increasing.
    #[error(
        "forced schedule candidate index order is invalid at {candidate_index}: previous {previous}, next {next}"
    )]
    CandidateIndexOrder {
        /// Candidate position containing the invalid source index.
        candidate_index: usize,
        /// Previous retained source index.
        previous: usize,
        /// Reordered or duplicate source index.
        next: usize,
    },
    /// A retained index does not exist in the complete source schedule.
    #[error(
        "forced schedule candidate index {candidate_index} references source {source_index}, source length is {source_len}"
    )]
    CandidateIndexOutOfRange {
        /// Candidate position containing the invalid source index.
        candidate_index: usize,
        /// Invalid source index.
        source_index: usize,
        /// Complete source schedule length.
        source_len: usize,
    },
    /// Candidate allocation failed before execution.
    #[error("forced schedule candidate could not allocate {requested} dispatches")]
    CandidateAllocationFailed {
        /// Requested retained dispatch capacity.
        requested: usize,
    },
    /// The reduced candidate uses an unsupported schema.
    #[error("forced schedule candidate schema mismatch: expected {expected}, found {found}")]
    CandidateSchemaMismatch {
        /// Supported candidate schema.
        expected: u32,
        /// Supplied candidate schema.
        found: u32,
    },
    /// Caller-owned candidate execution work was exhausted.
    #[error("forced schedule candidate work limit exhausted at {work_units} units (limit {limit})")]
    CandidateWorkLimitExceeded {
        /// Bounded execution work already consumed.
        work_units: u64,
        /// Caller-owned execution work bound.
        limit: u64,
    },
    /// The projection schema is unsupported.
    #[error("forced schedule schema mismatch: expected {expected}, found {found}")]
    SchemaMismatch {
        /// Supported schema.
        expected: u32,
        /// Supplied schema.
        found: u32,
    },
    /// The projection is from a different deterministic seed.
    #[error("forced schedule seed mismatch: expected {expected}, found {found}")]
    SeedMismatch {
        /// Runtime seed.
        expected: u64,
        /// Projection seed.
        found: u64,
    },
    /// The projection is from a different lab configuration.
    #[error("forced schedule config mismatch: expected {expected:#x}, found {found:#x}")]
    ConfigMismatch {
        /// Runtime configuration hash.
        expected: u64,
        /// Projection configuration hash.
        found: u64,
    },
    /// Forced execution only starts from a pristine runtime clock/certificate.
    #[error("forced schedule requires a pristine runtime (steps={steps}, decisions={decisions})")]
    RuntimeAlreadyStarted {
        /// Runtime steps already executed.
        steps: u64,
        /// Schedule decisions already recorded.
        decisions: u64,
    },
    /// The source projection was incomplete or did not reach quiescence.
    #[error("forced schedule source projection is partial")]
    PartialSource,
    /// Caller-owned dispatch admission was exceeded.
    #[error("forced schedule has {found} dispatches, limit is {limit}")]
    DispatchLimitExceeded {
        /// Supplied number of dispatches.
        found: usize,
        /// Caller-owned limit.
        limit: usize,
    },
    /// Caller-owned step budget was exhausted.
    #[error("forced schedule work limit exhausted at {steps} steps (limit {limit})")]
    WorkLimitExceeded {
        /// Steps consumed by this invocation.
        steps: u64,
        /// Caller-owned limit.
        limit: u64,
    },
    /// Dispatch steps are not strictly increasing.
    #[error(
        "forced schedule step order is invalid at dispatch {index}: previous {previous}, next {next}"
    )]
    StepOrder {
        /// Offending dispatch index.
        index: usize,
        /// Previous step.
        previous: u64,
        /// Next step.
        next: u64,
    },
    /// Dispatch virtual time moved backwards.
    #[error(
        "forced schedule virtual time moved backwards at dispatch {index}: previous {previous}, next {next}"
    )]
    TimeOrder {
        /// Offending dispatch index.
        index: usize,
        /// Previous virtual time.
        previous: u64,
        /// Next virtual time.
        next: u64,
    },
    /// Runnable work appeared before the next recorded dispatch step.
    #[error("runnable work appeared at step {actual} before recorded step {expected}")]
    EarlyRunnable {
        /// Recorded next dispatch step.
        expected: u64,
        /// Current step.
        actual: u64,
    },
    /// The runner passed the next recorded dispatch step.
    #[error("forced schedule missed dispatch {index}: expected step {expected}, reached {actual}")]
    StepMismatch {
        /// Dispatch index.
        index: usize,
        /// Recorded step.
        expected: u64,
        /// Current step.
        actual: u64,
    },
    /// The virtual clock did not match the recorded dispatch.
    #[error(
        "forced schedule time mismatch at dispatch {index}: expected {expected}, found {actual}"
    )]
    TimeMismatch {
        /// Dispatch index.
        index: usize,
        /// Recorded virtual time.
        expected: u64,
        /// Runtime virtual time.
        actual: u64,
    },
    /// The recorded worker is not part of this runtime.
    #[error("forced schedule worker {worker} is unavailable (worker count {worker_count})")]
    WorkerUnavailable {
        /// Recorded worker.
        worker: u32,
        /// Runtime worker count.
        worker_count: usize,
    },
    /// The exact task generation is absent or already completed.
    #[error("forced schedule task {task:?} is unavailable at dispatch {index}")]
    TaskUnavailable {
        /// Dispatch index.
        index: usize,
        /// Full compact task identity.
        task: CompactTaskId,
    },
    /// The task's authoritative worker differs from the recorded worker.
    #[error(
        "forced schedule worker mismatch at dispatch {index}: expected {expected}, found {actual}"
    )]
    WorkerMismatch {
        /// Dispatch index.
        index: usize,
        /// Recorded worker.
        expected: u32,
        /// Actual assigned worker.
        actual: u32,
    },
    /// The task's authoritative lane differs from the recorded lane.
    #[error(
        "forced schedule lane mismatch at dispatch {index}: expected {expected:?}, found {actual:?}"
    )]
    LaneMismatch {
        /// Dispatch index.
        index: usize,
        /// Recorded lane.
        expected: DispatchLane,
        /// Actual lane.
        actual: DispatchLane,
    },
    /// A timed task was selected before its deadline.
    #[error(
        "forced schedule timed task is not due at dispatch {index}: deadline {deadline}, now {now}"
    )]
    TimedNotDue {
        /// Dispatch index.
        index: usize,
        /// Recorded task deadline.
        deadline: u64,
        /// Current virtual time.
        now: u64,
    },
    /// Scheduler membership and lane queues disagree.
    #[error("forced schedule queue invariant failed at dispatch {index}")]
    QueueInvariant {
        /// Dispatch index.
        index: usize,
    },
    /// The projection ended while runnable or live work remained.
    #[error("forced schedule exhausted after {consumed} dispatches before terminal quiescence")]
    ScheduleExhausted {
        /// Dispatches consumed.
        consumed: usize,
    },
    /// Terminal schedule hash differed from the source receipt.
    #[error("forced schedule certificate mismatch: expected {expected:#x}, found {actual:#x}")]
    CertificateMismatch {
        /// Source schedule hash.
        expected: u64,
        /// Replayed schedule hash.
        actual: u64,
    },
    /// Terminal step or virtual time differed from the source receipt.
    #[error(
        "forced schedule terminal mismatch: expected step/time {expected_steps}/{expected_nanos}, found {actual_steps}/{actual_nanos}"
    )]
    TerminalMismatch {
        /// Source terminal step.
        expected_steps: u64,
        /// Source terminal virtual time.
        expected_nanos: u64,
        /// Replay terminal step.
        actual_steps: u64,
        /// Replay terminal virtual time.
        actual_nanos: u64,
    },
}

/// Fail-closed error for the canonical [`ForcedSchedule`] artifact codec.
///
/// This error is separate from [`ForcedScheduleError`] so adding the codec in
/// a `0.4.x` release does not add variants to that existing exhaustively
/// matchable public enum.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ForcedScheduleArtifactError {
    /// The complete schedule is not valid replay authority.
    #[error(transparent)]
    Schedule(#[from] ForcedScheduleError),
    /// The artifact exceeds the caller's encoded-byte admission limit.
    #[error("forced schedule artifact has {found} bytes, limit is {limit}")]
    ByteLimitExceeded {
        /// Supplied encoded byte length.
        found: usize,
        /// Caller-owned encoded byte limit.
        limit: usize,
    },
    /// The artifact magic prefix is not recognized.
    #[error("forced schedule artifact magic mismatch")]
    MagicMismatch,
    /// The artifact codec version is unsupported.
    #[error("forced schedule artifact version mismatch: expected {expected}, found {found}")]
    VersionMismatch {
        /// Supported artifact version.
        expected: u32,
        /// Supplied artifact version.
        found: u32,
    },
    /// The encoded schedule schema is unsupported.
    #[error("forced schedule schema mismatch: expected {expected}, found {found}")]
    SchemaMismatch {
        /// Supported schedule schema.
        expected: u32,
        /// Supplied schedule schema.
        found: u32,
    },
    /// Artifact size arithmetic overflowed before allocation.
    #[error("forced schedule artifact length overflow for {dispatch_count} dispatches")]
    LengthOverflow {
        /// Untrusted dispatch count that overflowed admission arithmetic.
        dispatch_count: u64,
    },
    /// The artifact ended before its declared canonical length.
    #[error("forced schedule artifact is truncated: expected {expected} bytes, found {found}")]
    Truncated {
        /// Minimum or exact required byte length.
        expected: usize,
        /// Supplied byte length.
        found: usize,
    },
    /// Bytes remain after the canonical artifact boundary.
    #[error("forced schedule artifact has trailing bytes: expected {expected}, found {found}")]
    TrailingBytes {
        /// Exact canonical byte length.
        expected: usize,
        /// Supplied byte length.
        found: usize,
    },
    /// The SHA-256 integrity binding does not match the artifact body.
    #[error("forced schedule artifact checksum mismatch")]
    ChecksumMismatch,
    /// The decoded dispatch count exceeds the caller's admission limit.
    #[error("forced schedule artifact has {found} dispatches, limit is {limit}")]
    DispatchLimitExceeded {
        /// Supplied number of dispatches.
        found: usize,
        /// Caller-owned dispatch limit.
        limit: usize,
    },
    /// Decoded dispatch storage exceeds the caller's allocation admission.
    #[error("forced schedule artifact needs {requested} decoded dispatch bytes, limit is {limit}")]
    DecodedAllocationLimitExceeded {
        /// Required decoded dispatch-vector bytes.
        requested: usize,
        /// Caller-owned decoded allocation limit.
        limit: usize,
    },
    /// Exact artifact or dispatch-vector allocation failed.
    #[error("forced schedule artifact could not allocate {requested} bytes")]
    AllocationFailed {
        /// Exact requested allocation size.
        requested: usize,
    },
    /// A dispatch encoded an unsupported scheduler-lane tag.
    #[error("forced schedule artifact lane tag {tag} is invalid at dispatch {index}")]
    LaneTag {
        /// Dispatch containing the invalid tag.
        index: usize,
        /// Unsupported lane tag.
        tag: u8,
    },
    /// A boolean field used a noncanonical tag.
    #[error("forced schedule artifact boolean {field} has invalid tag {tag}")]
    BooleanTag {
        /// Stable field name.
        field: &'static str,
        /// Unsupported boolean tag.
        tag: u8,
    },
    /// Parsed fields did not reproduce the exact input bytes.
    #[error("forced schedule artifact is not canonically encoded")]
    NonCanonical,
}

#[derive(Debug)]
struct ForcedScheduleRecorder {
    max_dispatches: usize,
    dispatches: Vec<ForcedDispatch>,
    truncated: bool,
}

enum LabDispatchMode<'a> {
    Normal,
    Forced {
        expected: Option<(usize, &'a ForcedDispatch)>,
    },
    Candidate {
        expected: Option<(usize, &'a ForcedDispatch)>,
    },
}

fn compact_task_id(compact: CompactTaskId) -> TaskId {
    let (index, generation) = compact.unpack();
    TaskId::from_arena(ArenaIndex::new(index, generation))
}

fn forced_schedule_config_hash(config: &LabConfig) -> u64 {
    use std::hash::{Hash, Hasher};

    let mut hasher = crate::util::DetHasher::for_lab();
    "asupersync.lab.forced-schedule.config.v1".hash(&mut hasher);
    LabConfigSummary::from_config(config)
        .config_hash()
        .hash(&mut hasher);
    config.auto_advance_time.hash(&mut hasher);
    config.enable_cancellation_oracle.hash(&mut hasher);
    config.panic_on_cancellation_violation.hash(&mut hasher);
    config.oracle_selection.hash(&mut hasher);
    hasher.finish()
}

fn validate_candidate_limits(
    limits: ForcedScheduleCandidateLimits,
) -> Result<(), ForcedScheduleError> {
    if limits.max_source_dispatches == 0 {
        return Err(ForcedScheduleError::ZeroCandidateLimit {
            limit_name: "max_source_dispatches",
        });
    }
    if limits.max_candidate_dispatches == 0 {
        return Err(ForcedScheduleError::ZeroCandidateLimit {
            limit_name: "max_candidate_dispatches",
        });
    }
    if limits.max_work_units == 0 {
        return Err(ForcedScheduleError::ZeroCandidateLimit {
            limit_name: "max_work_units",
        });
    }
    Ok(())
}

fn take_candidate_work(work_units: &mut u64, limit: u64) -> Result<(), ForcedScheduleError> {
    if *work_units >= limit {
        return Err(ForcedScheduleError::CandidateWorkLimitExceeded {
            work_units: *work_units,
            limit,
        });
    }
    *work_units += 1;
    Ok(())
}

fn validate_dispatch_order(dispatches: &[ForcedDispatch]) -> Result<(), ForcedScheduleError> {
    let mut previous_step = 0u64;
    let mut previous_nanos = 0u64;
    for (index, dispatch) in dispatches.iter().enumerate() {
        if dispatch.at_step <= previous_step {
            return Err(ForcedScheduleError::StepOrder {
                index,
                previous: previous_step,
                next: dispatch.at_step,
            });
        }
        if dispatch.at_nanos < previous_nanos {
            return Err(ForcedScheduleError::TimeOrder {
                index,
                previous: previous_nanos,
                next: dispatch.at_nanos,
            });
        }
        previous_step = dispatch.at_step;
        previous_nanos = dispatch.at_nanos;
    }
    Ok(())
}

fn forced_schedule_artifact_len(
    dispatch_count: usize,
) -> Result<usize, ForcedScheduleArtifactError> {
    let dispatch_count_u64 = u64::try_from(dispatch_count).unwrap_or(u64::MAX);
    let dispatch_bytes = dispatch_count
        .checked_mul(FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN)
        .ok_or(ForcedScheduleArtifactError::LengthOverflow {
            dispatch_count: dispatch_count_u64,
        })?;
    FORCED_SCHEDULE_ARTIFACT_HEADER_LEN
        .checked_add(dispatch_bytes)
        .and_then(|len| len.checked_add(FORCED_SCHEDULE_ARTIFACT_TERMINAL_LEN))
        .and_then(|len| len.checked_add(FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN))
        .ok_or(ForcedScheduleArtifactError::LengthOverflow {
            dispatch_count: dispatch_count_u64,
        })
}

fn forced_schedule_artifact_checksum(bytes: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(b"asupersync.lab.forced-schedule.artifact.v1\0");
    hasher.update(bytes);
    hasher.finalize().into()
}

fn forced_schedule_artifact_u32(
    bytes: &[u8],
    offset: usize,
) -> Result<u32, ForcedScheduleArtifactError> {
    let end = offset
        .checked_add(4)
        .ok_or(ForcedScheduleArtifactError::LengthOverflow {
            dispatch_count: u64::MAX,
        })?;
    let Some(raw) = bytes.get(offset..end) else {
        return Err(ForcedScheduleArtifactError::Truncated {
            expected: end,
            found: bytes.len(),
        });
    };
    let mut value = [0u8; 4];
    value.copy_from_slice(raw);
    Ok(u32::from_le_bytes(value))
}

fn forced_schedule_artifact_u64(
    bytes: &[u8],
    offset: usize,
) -> Result<u64, ForcedScheduleArtifactError> {
    let end = offset
        .checked_add(8)
        .ok_or(ForcedScheduleArtifactError::LengthOverflow {
            dispatch_count: u64::MAX,
        })?;
    let Some(raw) = bytes.get(offset..end) else {
        return Err(ForcedScheduleArtifactError::Truncated {
            expected: end,
            found: bytes.len(),
        });
    };
    let mut value = [0u8; 8];
    value.copy_from_slice(raw);
    Ok(u64::from_le_bytes(value))
}

const fn forced_schedule_lane_tag(lane: DispatchLane) -> u8 {
    match lane {
        DispatchLane::Cancel => 0,
        DispatchLane::Timed => 1,
        DispatchLane::Ready => 2,
        DispatchLane::Stolen => 3,
    }
}

fn forced_schedule_lane_from_tag(
    index: usize,
    tag: u8,
) -> Result<DispatchLane, ForcedScheduleArtifactError> {
    match tag {
        0 => Ok(DispatchLane::Cancel),
        1 => Ok(DispatchLane::Timed),
        2 => Ok(DispatchLane::Ready),
        3 => Ok(DispatchLane::Stolen),
        _ => Err(ForcedScheduleArtifactError::LaneTag { index, tag }),
    }
}

fn forced_schedule_bool(tag: u8, field: &'static str) -> Result<bool, ForcedScheduleArtifactError> {
    match tag {
        0 => Ok(false),
        1 => Ok(true),
        _ => Err(ForcedScheduleArtifactError::BooleanTag { field, tag }),
    }
}

fn validate_complete_forced_schedule_shape(
    schedule: &ForcedSchedule,
) -> Result<(), ForcedScheduleError> {
    if schedule.version != FORCED_SCHEDULE_SCHEMA_VERSION {
        return Err(ForcedScheduleError::SchemaMismatch {
            expected: FORCED_SCHEDULE_SCHEMA_VERSION,
            found: schedule.version,
        });
    }
    if schedule.truncated || !schedule.terminal_quiescent {
        return Err(ForcedScheduleError::PartialSource);
    }
    validate_dispatch_order(&schedule.dispatches)?;
    if schedule.dispatches.last().is_some_and(|dispatch| {
        dispatch.at_step > schedule.terminal_steps || dispatch.at_nanos > schedule.terminal_nanos
    }) {
        return Err(ForcedScheduleError::PartialSource);
    }
    Ok(())
}

/// Why a [`LabRuntime::run_with_auto_advance`] loop terminated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AutoAdvanceTermination {
    /// The runtime reached quiescence: no runnable tasks, no pending timers,
    /// and all regions are closed.
    Quiescent,
    /// The configured `max_steps` limit was reached before quiescence.
    StepLimitReached,
    /// The runtime was stuck (scheduler empty, no pending deadlines, not
    /// quiescent) for 1 000 consecutive iterations and bailed out.
    StuckBailout,
}

impl fmt::Display for AutoAdvanceTermination {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Quiescent => f.write_str("quiescent"),
            Self::StepLimitReached => f.write_str("step-limit-reached"),
            Self::StuckBailout => f.write_str("stuck-bailout"),
        }
    }
}

/// Report from a [`LabRuntime::run_with_auto_advance`] execution.
///
/// Captures statistics about automatic time advancement during the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VirtualTimeReport {
    /// Total scheduler steps executed.
    pub steps: u64,
    /// Number of times virtual time was auto-advanced to the next pending
    /// timer or lab-reactor deadline.
    pub auto_advances: u64,
    /// Total timer wakeups triggered by auto-advances.
    pub total_wakeups: u64,
    /// Virtual time at the start of the run.
    pub time_start: Time,
    /// Virtual time at the end of the run.
    pub time_end: Time,
    /// Total virtual nanoseconds elapsed during the run.
    pub virtual_elapsed_nanos: u64,
    /// Why the auto-advance loop terminated.
    pub termination: AutoAdvanceTermination,
}

impl VirtualTimeReport {
    /// Returns the virtual elapsed time in milliseconds.
    #[must_use]
    pub const fn virtual_elapsed_ms(&self) -> u64 {
        self.virtual_elapsed_nanos / 1_000_000
    }

    /// Returns the virtual elapsed time in seconds.
    #[must_use]
    pub const fn virtual_elapsed_secs(&self) -> u64 {
        self.virtual_elapsed_nanos / 1_000_000_000
    }
}

/// Structured report for a single lab runtime run.
///
/// This is intended as a low-level building block for Spork app harnesses.
/// It contains canonical trace fingerprints and oracle outcomes, but it does
/// not write to stdout/stderr or persist artifacts.
#[derive(Debug, Clone)]
pub struct LabRunReport {
    /// Lab seed driving scheduling determinism.
    pub seed: u64,
    /// Steps executed during the `run_until_quiescent()` call that produced this report.
    pub steps_delta: u64,
    /// Total steps executed by the runtime so far.
    pub steps_total: u64,
    /// Whether the runtime is quiescent at report time.
    pub quiescent: bool,
    /// Virtual time (nanoseconds since epoch) at report time.
    pub now_nanos: u64,
    /// Number of events in the current trace buffer snapshot.
    pub trace_len: usize,
    /// Canonical fingerprint of the trace equivalence class (Foata / Mazurkiewicz).
    pub trace_fingerprint: u64,
    /// Trace certificate summary (event hash/count + schedule hash).
    pub trace_certificate: LabTraceCertificateSummary,
    /// Unified oracle report (stable ordering, serializable).
    pub oracle_report: crate::lab::oracle::OracleReport,
    /// Runtime invariant violations detected by `LabRuntime::check_invariants()`
    /// plus stable `oracle:<name>` mirrors for every failed oracle-suite row.
    ///
    /// Runtime checks remain distinct from the oracle suite; the `oracle:` rows
    /// are stable references to failed suite entries for consumers of this
    /// aggregate channel.
    pub invariant_violations: Vec<String>,
    /// Temporal-oracle invariants that failed in this report.
    pub temporal_invariant_failures: Vec<String>,
    /// Minimized divergent-prefix length for temporal failures, when available.
    pub temporal_counterexample_prefix_len: Option<usize>,
    /// First failed refinement-firewall rule id, when present.
    pub refinement_firewall_rule_id: Option<String>,
    /// Event index where refinement-firewall first failed.
    pub refinement_firewall_event_index: Option<usize>,
    /// Event sequence where refinement-firewall first failed.
    pub refinement_firewall_event_seq: Option<u64>,
    /// Deterministic minimal counterexample prefix length for refinement failures.
    pub refinement_counterexample_prefix_len: Option<usize>,
    /// Whether refinement checks were skipped due to trace-buffer truncation.
    pub refinement_firewall_skipped_due_to_trace_truncation: bool,
}

impl LabRunReport {
    /// Returns true when the report satisfies the `#[lab_test]` success contract.
    #[must_use]
    pub fn lab_test_passed(&self) -> bool {
        self.quiescent && self.oracle_report.all_passed() && self.invariant_violations.is_empty()
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        json!({
            "seed": self.seed,
            "steps_delta": self.steps_delta,
            "steps_total": self.steps_total,
            "quiescent": self.quiescent,
            "now_nanos": self.now_nanos,
            "trace": {
                "len": self.trace_len,
                "fingerprint": self.trace_fingerprint,
                "certificate": {
                    "event_hash": self.trace_certificate.event_hash,
                    "event_count": self.trace_certificate.event_count,
                    "schedule_hash": self.trace_certificate.schedule_hash,
                }
            },
            "oracles": self.oracle_report.to_json(),
            "invariants": self.invariant_violations,
            "temporal": {
                "failed_invariants": self.temporal_invariant_failures,
                "counterexample_prefix_len": self.temporal_counterexample_prefix_len,
            },
            "refinement_firewall": {
                "rule_id": self.refinement_firewall_rule_id,
                "event_index": self.refinement_firewall_event_index,
                "event_seq": self.refinement_firewall_event_seq,
                "counterexample_prefix_len": self.refinement_counterexample_prefix_len,
                "skipped_due_to_trace_truncation": self.refinement_firewall_skipped_due_to_trace_truncation,
            },
        })
    }

    /// Export this run's trace events to a TLA+ module for model checking.
    ///
    /// Converts the captured trace into a TLA+ behavior (concrete state
    /// sequence) with property templates for the 6 core invariants. The
    /// resulting module can be fed to TLC for bounded model checking.
    ///
    /// Returns `None` if no trace events were captured.
    #[must_use]
    pub fn export_tla(
        &self,
        trace_events: &[crate::trace::TraceEvent],
        module_name: &str,
    ) -> Option<crate::trace::tla_export::TlaModule> {
        if trace_events.is_empty() {
            return None;
        }
        let exporter = crate::trace::tla_export::TlaExporter::from_trace(trace_events);
        if exporter.snapshot_count() == 0 {
            return None;
        }
        Some(exporter.export_behavior(module_name))
    }
}

/// Crashpack artifact written by the lab auto-forensics path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LabAutoCrashpack {
    /// Filesystem path of the written crashpack.
    pub path: String,
    /// One-command replay recipe embedded in the crashpack.
    pub replay: ReplayCommand,
}

/// Error returned when lab auto-forensics cannot write a crashpack.
#[derive(Debug)]
pub enum LabAutoCrashpackError {
    /// Creating the deterministic artifact directory failed.
    CreateDir {
        /// Directory that could not be created.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Serializing or writing the crashpack failed.
    Write(CrashPackWriteError),
}

impl fmt::Display for LabAutoCrashpackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CreateDir { path, source } => {
                write!(
                    f,
                    "failed to create lab crashpack directory {}: {source}",
                    path.display()
                )
            }
            Self::Write(source) => write!(f, "{source}"),
        }
    }
}

impl std::error::Error for LabAutoCrashpackError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CreateDir { source, .. } => Some(source),
            Self::Write(source) => Some(source),
        }
    }
}

impl From<CrashPackWriteError> for LabAutoCrashpackError {
    fn from(source: CrashPackWriteError) -> Self {
        Self::Write(source)
    }
}

const TEMPORAL_ORACLE_INVARIANTS: &[&str] = &[
    "task_leak",
    "obligation_leak",
    "quiescence",
    "cancellation_protocol",
    "loser_drain",
    "region_tree",
    "deadline_monotone",
    #[cfg(feature = "messaging-fabric")]
    "fabric_publish",
    #[cfg(feature = "messaging-fabric")]
    "fabric_reply",
    #[cfg(feature = "messaging-fabric")]
    "fabric_quiescence",
    #[cfg(feature = "messaging-fabric")]
    "fabric_redelivery",
];

// ---------------------------------------------------------------------------
// Spork app harness report schema (bd-11dm5)
// ---------------------------------------------------------------------------

/// Snapshot of a [`LabConfig`] captured into a stable, JSON-friendly schema.
///
/// This is intentionally a *summary* (not the raw config), so downstream tools
/// can depend on a stable field set without pulling in internal config types.
#[derive(Debug, Clone, PartialEq)]
pub struct LabConfigSummary {
    /// Random seed for deterministic scheduling.
    pub seed: u64,
    /// Seed for capability entropy sources (may be decoupled from `seed`).
    pub entropy_seed: u64,
    /// Number of modeled workers in the deterministic multi-worker simulation.
    pub worker_count: usize,
    /// Whether the runtime panics on obligation leaks in lab mode.
    pub panic_on_obligation_leak: bool,
    /// Capacity of the trace buffer.
    pub trace_capacity: usize,
    /// Maximum steps a task may remain unpolled while holding obligations before futurelock triggers.
    pub futurelock_max_idle_steps: u64,
    /// Whether the runtime panics when a futurelock is detected.
    pub panic_on_futurelock: bool,
    /// Optional maximum step limit for a run.
    pub max_steps: Option<u64>,
    /// Chaos configuration summary, when enabled.
    pub chaos: Option<ChaosConfigSummary>,
    /// Whether replay recording is enabled.
    pub replay_recording_enabled: bool,
}

impl LabConfigSummary {
    /// Build a config summary from the full [`LabConfig`].
    #[must_use]
    pub fn from_config(config: &LabConfig) -> Self {
        Self {
            seed: config.seed,
            entropy_seed: config.entropy_seed,
            worker_count: config.worker_count,
            panic_on_obligation_leak: config.panic_on_obligation_leak,
            trace_capacity: config.trace_capacity,
            futurelock_max_idle_steps: config.futurelock_max_idle_steps,
            panic_on_futurelock: config.panic_on_futurelock,
            max_steps: config.max_steps,
            chaos: config.chaos.as_ref().map(ChaosConfigSummary::from_config),
            replay_recording_enabled: config.replay_recording.is_some(),
        }
    }

    /// Compute a stable hash of the configuration for quick equivalence checking.
    ///
    /// Two configs with the same hash produced identical lab setups. Agents can
    /// compare config hashes across runs to confirm they used the same settings.
    #[must_use]
    pub fn config_hash(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        // DefaultHasher is NOT stable across Rust versions; DetHasher uses a
        // fixed algorithm and seed for cross-version deterministic hashing.
        let mut h = crate::util::DetHasher::for_lab();
        self.seed.hash(&mut h);
        self.entropy_seed.hash(&mut h);
        self.worker_count.hash(&mut h);
        self.panic_on_obligation_leak.hash(&mut h);
        self.trace_capacity.hash(&mut h);
        self.futurelock_max_idle_steps.hash(&mut h);
        self.panic_on_futurelock.hash(&mut h);
        self.max_steps.hash(&mut h);
        self.replay_recording_enabled.hash(&mut h);
        if let Some(ref c) = self.chaos {
            1u8.hash(&mut h);
            c.seed.hash(&mut h);
            c.cancel_probability.to_bits().hash(&mut h);
            c.delay_probability.to_bits().hash(&mut h);
            c.io_error_probability.to_bits().hash(&mut h);
            c.wakeup_storm_probability.to_bits().hash(&mut h);
            c.budget_exhaust_probability.to_bits().hash(&mut h);
        } else {
            0u8.hash(&mut h);
        }
        h.finish()
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        json!({
            "seed": self.seed,
            "entropy_seed": self.entropy_seed,
            "worker_count": self.worker_count,
            "panic_on_obligation_leak": self.panic_on_obligation_leak,
            "trace_capacity": self.trace_capacity,
            "futurelock_max_idle_steps": self.futurelock_max_idle_steps,
            "panic_on_futurelock": self.panic_on_futurelock,
            "max_steps": self.max_steps,
            "chaos": self.chaos.as_ref().map(ChaosConfigSummary::to_json),
            "replay_recording_enabled": self.replay_recording_enabled,
        })
    }
}

/// JSON-friendly summary of chaos settings.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChaosConfigSummary {
    /// Seed for deterministic chaos injection.
    pub seed: u64,
    /// Probability of injecting cancellation at each poll point.
    pub cancel_probability: f64,
    /// Probability of injecting delay at each poll point.
    pub delay_probability: f64,
    /// Probability of injecting an I/O error.
    pub io_error_probability: f64,
    /// Probability of triggering a spurious wakeup storm.
    pub wakeup_storm_probability: f64,
    /// Probability of injecting budget exhaustion.
    pub budget_exhaust_probability: f64,
}

impl ChaosConfigSummary {
    /// Build a chaos summary from the full chaos configuration.
    #[must_use]
    pub fn from_config(config: &crate::lab::chaos::ChaosConfig) -> Self {
        Self {
            seed: config.seed,
            cancel_probability: config.cancel_probability,
            delay_probability: config.delay_probability,
            io_error_probability: config.io_error_probability,
            wakeup_storm_probability: config.wakeup_storm_probability,
            budget_exhaust_probability: config.budget_exhaust_probability,
        }
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        json!({
            "seed": self.seed,
            "cancel_probability": self.cancel_probability,
            "delay_probability": self.delay_probability,
            "io_error_probability": self.io_error_probability,
            "wakeup_storm_probability": self.wakeup_storm_probability,
            "budget_exhaust_probability": self.budget_exhaust_probability,
        })
    }
}

/// Attachment kind for Spork harness reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum HarnessAttachmentKind {
    /// Crash pack artifact (minimal repro pack).
    CrashPack,
    /// Replay trace artifact (recorded non-determinism for replay).
    ReplayTrace,
    /// Generic trace artifact (e.g., NDJSON/JSON trace snapshot).
    Trace,
    /// Other harness-defined artifact.
    Other,
}

impl fmt::Display for HarnessAttachmentKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CrashPack => write!(f, "crashpack"),
            Self::ReplayTrace => write!(f, "replay_trace"),
            Self::Trace => write!(f, "trace"),
            Self::Other => write!(f, "other"),
        }
    }
}

/// Report attachment reference (path-only).
///
/// The lab runtime does not write artifacts; this is a schema hook that a harness
/// can fill in when it persists crash packs, replay traces, etc.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HarnessAttachmentRef {
    /// Attachment kind (used for deterministic ordering and downstream routing).
    pub kind: HarnessAttachmentKind,
    /// Artifact path (relative or absolute; interpreted by the harness).
    pub path: String,
}

impl HarnessAttachmentRef {
    /// Convenience constructor for crash pack attachments.
    #[must_use]
    pub fn crashpack(path: impl Into<String>) -> Self {
        Self {
            kind: HarnessAttachmentKind::CrashPack,
            path: path.into(),
        }
    }

    /// Convenience constructor for replay trace attachments.
    #[must_use]
    pub fn replay_trace(path: impl Into<String>) -> Self {
        Self {
            kind: HarnessAttachmentKind::ReplayTrace,
            path: path.into(),
        }
    }

    /// Convenience constructor for generic trace attachments.
    #[must_use]
    pub fn trace(path: impl Into<String>) -> Self {
        Self {
            kind: HarnessAttachmentKind::Trace,
            path: path.into(),
        }
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        json!({
            "kind": self.kind.to_string(),
            "path": self.path,
        })
    }
}

/// Deterministic crashpack linkage metadata exposed in harness reports.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrashpackLink {
    /// Artifact path for the crashpack attachment.
    pub path: String,
    /// Stable crashpack identifier (seed + fingerprint tuple).
    pub id: String,
    /// Canonical trace fingerprint associated with this crashpack.
    pub fingerprint: u64,
    /// Reproduction command generated from the run config and crashpack path.
    pub replay: ReplayCommand,
}

impl CrashpackLink {
    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        json!({
            "path": self.path,
            "id": self.id,
            "fingerprint": self.fingerprint,
            "replay": self.replay,
        })
    }
}

/// Stable, JSON-first report schema for Spork app harness runs.
///
/// This wraps [`LabRunReport`] and adds:
/// - config snapshot (lab-side)
/// - stable fingerprint extraction points
/// - optional artifact attachment references (crash packs, replay traces, ...)
#[derive(Debug, Clone)]
pub struct SporkHarnessReport {
    /// Schema version for stable downstream parsing.
    pub schema_version: u32,
    /// Application identifier/name for the harness run.
    pub app: String,
    /// Lab configuration snapshot used for the run.
    pub config: LabConfigSummary,
    /// Low-level lab run report (trace fingerprints + oracles + invariants).
    pub run: LabRunReport,
    /// Optional attachment references (crash packs, replay traces, etc.).
    pub attachments: Vec<HarnessAttachmentRef>,
}

impl SporkHarnessReport {
    /// Current stable schema version.
    ///
    /// Increment when the JSON contract changes in a backward-incompatible way.
    /// Backward-compatible additions (new optional fields) do NOT require a bump.
    /// Breaking changes (field renames, type changes, removals) MUST bump this
    /// and document the migration in a comment here.
    ///
    /// # Version history
    ///
    /// - **v1**: Initial schema (bd-11dm5). Top-level keys: `schema_version`,
    ///   `app`, `lab`, `fingerprints`, `run`, `attachments`.
    /// - **v2**: Agent report contract (bd-f262i). Added `lab.config_hash` for
    ///   quick equivalence checking. Added `verdict` top-level key. No
    ///   breaking changes to existing fields.
    /// - **v3**: Crashpack linking contract (bd-1wen4). Added top-level
    ///   `crashpack` object with deterministic path/id/fingerprint/replay.
    pub const SCHEMA_VERSION: u32 = 3;

    /// Create a new harness report from a low-level lab run report.
    #[must_use]
    pub fn new(
        app: impl Into<String>,
        config: &LabConfig,
        run: LabRunReport,
        attachments: Vec<HarnessAttachmentRef>,
    ) -> Self {
        Self {
            schema_version: Self::SCHEMA_VERSION,
            app: app.into(),
            config: LabConfigSummary::from_config(config),
            run,
            attachments,
        }
    }

    // -------------------------------------------------------------------------
    // Agent UX convenience methods (bd-f262i)
    // -------------------------------------------------------------------------

    /// Quick pass/fail verdict: quiescent, with all oracles passed and no
    /// invariant violations.
    #[must_use]
    pub fn passed(&self) -> bool {
        self.run.lab_test_passed()
    }

    /// The canonical trace fingerprint for this run.
    #[must_use]
    pub fn trace_fingerprint(&self) -> u64 {
        self.run.trace_fingerprint
    }

    /// The lab seed that drove this run.
    #[must_use]
    pub fn seed(&self) -> u64 {
        self.run.seed
    }

    /// Config hash for quick equivalence checking across runs.
    #[must_use]
    pub fn config_hash(&self) -> u64 {
        self.config.config_hash()
    }

    /// Returns the path to the first crashpack attachment, if any.
    #[must_use]
    pub fn crashpack_path(&self) -> Option<&str> {
        self.attachments
            .iter()
            .find(|a| a.kind == HarnessAttachmentKind::CrashPack)
            .map(|a| a.path.as_str())
    }

    /// Deterministic crashpack linkage metadata when a crashpack is attached.
    #[must_use]
    pub fn crashpack_link(&self) -> Option<CrashpackLink> {
        let path = self.crashpack_path()?.to_string();
        let crash_config = CrashPackConfig {
            seed: self.seed(),
            config_hash: self.config_hash(),
            worker_count: self.config.worker_count,
            max_steps: self.config.max_steps,
            test_name: None,
            commit_hash: compiled_commit_hash(),
        };
        let replay = ReplayCommand::from_config_cli(&crash_config, &path);
        Some(CrashpackLink {
            id: format!(
                "crashpack-{seed:016x}-{fingerprint:016x}",
                seed = self.seed(),
                fingerprint = self.trace_fingerprint()
            ),
            fingerprint: self.trace_fingerprint(),
            path,
            replay,
        })
    }

    /// Returns oracle failure descriptions, if any.
    #[must_use]
    pub fn oracle_failures(&self) -> Vec<String> {
        self.run
            .oracle_report
            .failures()
            .iter()
            .map(|e| {
                let desc = e
                    .violation
                    .as_ref()
                    .map_or_else(String::new, |v| format!(": {v}"));
                format!("{}{desc}", e.invariant)
            })
            .collect()
    }

    /// One-line human-readable summary suitable for agent log output.
    ///
    /// Format: `[PASS|FAIL] app="name" seed=N fingerprint=N oracles=P/T`
    #[must_use]
    pub fn summary_line(&self) -> String {
        let verdict = if self.passed() { "PASS" } else { "FAIL" };
        let oracle = &self.run.oracle_report;
        format!(
            "[{verdict}] app=\"{}\" seed={} fingerprint={} oracles={}/{} invariant_violations={}",
            self.app,
            self.run.seed,
            self.run.trace_fingerprint,
            oracle.passed,
            oracle.total,
            self.run.invariant_violations.len(),
        )
    }

    /// Convert to JSON for artifact storage.
    ///
    /// # Agent Report Contract (bd-f262i)
    ///
    /// This is the **single stable JSON schema** that agents rely on across:
    /// - Lab runs (`SporkAppHarness::run_to_report`)
    /// - DPOR exploration (`ExplorationReport` wraps these)
    /// - Conformance suites (test assertions against these fields)
    ///
    /// ## Top-level fields (v2)
    ///
    /// | Key              | Type    | Stable? | Description                              |
    /// |------------------|---------|---------|------------------------------------------|
    /// | `schema_version` | u32     | yes     | Schema version (bump on breaking change) |
    /// | `verdict`        | string  | yes     | `"pass"` or `"fail"`                     |
    /// | `app.name`       | string  | yes     | Application name from `AppSpec`           |
    /// | `lab.config`     | object  | yes     | Full config snapshot                      |
    /// | `lab.config_hash`| u64     | yes     | Quick config equivalence hash             |
    /// | `fingerprints.*` | u64     | yes     | Trace/schedule fingerprints               |
    /// | `run.*`          | object  | yes     | Full `LabRunReport` (oracles, invariants) |
    /// | `crashpack`      | object? | yes     | Deterministic crashpack linkage metadata  |
    /// | `attachments`    | array   | yes     | Sorted by (kind, path)                    |
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;

        // Ensure stable ordering regardless of insertion order.
        let mut attachments = self.attachments.clone();
        attachments.sort_by(|a, b| (a.kind, &a.path).cmp(&(b.kind, &b.path)));

        json!({
            "schema_version": self.schema_version,
            "verdict": if self.passed() { "pass" } else { "fail" },
            "app": { "name": self.app },
            "lab": {
                "config": self.config.to_json(),
                "config_hash": self.config.config_hash(),
            },
            "fingerprints": {
                "trace": self.run.trace_fingerprint,
                "event_hash": self.run.trace_certificate.event_hash,
                "event_count": self.run.trace_certificate.event_count,
                "schedule_hash": self.run.trace_certificate.schedule_hash,
            },
            "run": self.run.to_json(),
            "crashpack": self.crashpack_link().map(|link| link.to_json()),
            "attachments": attachments.iter().map(HarnessAttachmentRef::to_json).collect::<Vec<_>>(),
        })
    }
}

/// The deterministic lab runtime.
///
/// This runtime is designed for testing and provides:
/// - Virtual time instead of wall-clock time
/// - Deterministic scheduling based on a seed
/// - Trace capture for debugging and replay
/// - Chaos injection for stress testing
#[derive(Debug)]
pub struct LabRuntime {
    /// Runtime state (public for tests and oracle access).
    pub state: RuntimeState,
    /// Lab reactor for deterministic I/O simulation.
    lab_reactor: Arc<LabReactor>,
    /// Deterministic spawn intake (br-asupersync-4h8lye / A2.1): requests
    /// enqueued here are admitted in FIFO order at the top of each step.
    spawn_mailbox: Arc<crate::runtime::spawn_mailbox::SpawnMailbox>,
    /// Keeps the lab spawn gateway live while the lab runtime is alive.
    _spawn_liveness: Arc<()>,
    /// Tokens seen for I/O submissions (for trace emission).
    seen_io_tokens: DetHashSet<usize>,
    /// Scheduler.
    pub scheduler: Arc<Mutex<LabScheduler>>,
    /// Configuration.
    config: LabConfig,
    /// Deterministic RNG.
    rng: DetRng,
    /// Current virtual time.
    virtual_time: Time,
    /// Virtual clock backing the timer driver.
    virtual_clock: Arc<VirtualClock>,
    /// Number of steps executed.
    steps: u64,
    /// Number of steps that actually dispatched a task.
    ///
    /// GH#55: `steps` counts loop turns, including turns where the scheduler
    /// reported pending work but nothing was dispatchable. Progress-based
    /// bailouts must key off this counter, not `steps`, or a task stranded in
    /// `LabScheduler::scheduled` spins forever while looking busy.
    dispatches: u64,
    /// Chaos RNG for deterministic fault injection.
    chaos_rng: Option<ChaosRng>,
    /// Statistics about chaos injections.
    chaos_stats: ChaosStats,
    /// Reactor chaos statistics already folded into `chaos_stats`.
    seen_reactor_chaos_stats: ChaosStats,
    /// Replay recorder for deterministic trace capture.
    replay_recorder: TraceRecorder,
    /// Optional bounded recorder for exact lab dispatch choices.
    forced_schedule_recorder: Option<ForcedScheduleRecorder>,
    /// Optional deadline monitor for warning callbacks.
    deadline_monitor: Option<DeadlineMonitor>,
    /// Oracle suite for invariant verification.
    pub oracles: OracleSuite,
    /// Schedule certificate for determinism verification.
    certificate: ScheduleCertificate,
}

impl LabRuntime {
    /// Creates a new lab runtime with the given configuration.
    #[must_use]
    pub fn new(config: LabConfig) -> Self {
        let rng = config.rng();
        let chaos_rng = config.chaos.as_ref().map(ChaosRng::from_config);
        let lab_reactor = config.chaos.as_ref().map_or_else(
            || Arc::new(LabReactor::new()),
            |chaos| Arc::new(LabReactor::with_chaos(chaos.clone())),
        );
        let mut state = RuntimeState::with_reactor(lab_reactor.clone());
        state.trace = TraceBufferHandle::new(config.trace_capacity);
        state.set_logical_clock_mode(crate::trace::distributed::LogicalClockMode::Lamport);
        state.set_obligation_leak_response(if config.panic_on_obligation_leak {
            ObligationLeakResponse::Panic
        } else {
            ObligationLeakResponse::Log
        });
        let virtual_clock = Arc::new(VirtualClock::starting_at(Time::ZERO));
        state.set_timer_driver(crate::time::TimerDriverHandle::with_virtual_clock(
            virtual_clock.clone(),
        ));
        // Producer-side spawn gateway (br-asupersync-hwjqyo / A2.2): the
        // lab drains this mailbox synchronously at the top of each step, so
        // the notifier is a no-op.
        let spawn_mailbox = Arc::new(crate::runtime::spawn_mailbox::SpawnMailbox::with_trace(
            state.trace_handle(),
        ));
        let spawn_liveness = Arc::new(());
        state.set_spawn_gateway(Arc::new(crate::runtime::spawn_mailbox::SpawnGateway::new(
            Arc::clone(&spawn_mailbox),
            Arc::new(|| {}),
            state.timer_driver_handle(),
            Arc::downgrade(&spawn_liveness),
        )));
        state.set_entropy_source(Arc::new(DetEntropy::new(config.entropy_seed)));

        // Initialize replay recorder if configured
        let mut replay_recorder = if let Some(ref rec_config) = config.replay_recording {
            TraceRecorder::with_config(TraceMetadata::new(config.seed), rec_config.clone())
        } else {
            TraceRecorder::disabled()
        };

        // Record initial RNG seed
        replay_recorder.record_rng_seed(config.seed);

        crate::tracing_compat::info!("virtual clock initialized: start_time_ms=0");

        Self {
            state,
            lab_reactor,
            spawn_mailbox,
            _spawn_liveness: spawn_liveness,
            // GH#55: derive lab hashing from the lab seed rather than
            // `Default::default()`, which is randomly seeded in builds
            // without `test-internals` and breaks lab determinism.
            seen_io_tokens: DetHashSet::with_hasher(
                crate::util::det_hash::DetBuildHasher::with_seed(config.seed),
            ),
            scheduler: Arc::new(Mutex::new(LabScheduler::new(
                config.worker_count,
                config.seed,
            ))),
            config,
            rng,
            virtual_time: Time::ZERO,
            virtual_clock,
            steps: 0,
            dispatches: 0,
            chaos_rng,
            chaos_stats: ChaosStats::new(),
            seen_reactor_chaos_stats: ChaosStats::new(),
            replay_recorder,
            forced_schedule_recorder: None,
            deadline_monitor: None,
            oracles: OracleSuite::new(),
            certificate: ScheduleCertificate::new(),
        }
    }

    /// Creates a lab runtime with the default configuration.
    #[must_use]
    pub fn with_seed(seed: u64) -> Self {
        Self::new(LabConfig::new(seed))
    }

    /// Returns the current virtual time.
    #[must_use]
    pub const fn now(&self) -> Time {
        self.virtual_time
    }

    /// Returns the number of steps executed.
    #[must_use]
    pub const fn steps(&self) -> u64 {
        self.steps
    }

    /// Returns a reference to the configuration.
    #[must_use]
    pub const fn config(&self) -> &LabConfig {
        &self.config
    }

    /// Returns a handle to the lab reactor for deterministic I/O injection.
    #[must_use]
    pub fn lab_reactor(&self) -> &Arc<LabReactor> {
        &self.lab_reactor
    }

    /// Returns a reference to the trace buffer handle.
    #[must_use]
    pub fn trace(&self) -> &TraceBufferHandle {
        &self.state.trace
    }

    /// Returns a race report derived from the current trace buffer.
    #[must_use]
    pub fn detected_races(&self) -> crate::trace::dpor::RaceReport {
        crate::trace::dpor::detect_hb_races(&self.state.trace.snapshot())
    }

    /// Returns aggregated chaos statistics for both task-side and reactor-side injection.
    #[must_use]
    pub fn chaos_stats(&self) -> &ChaosStats {
        &self.chaos_stats
    }

    /// Returns the schedule certificate for determinism verification.
    #[must_use]
    pub fn certificate(&self) -> &ScheduleCertificate {
        &self.certificate
    }

    /// Returns true if replay recording is enabled.
    #[must_use]
    pub fn has_replay_recording(&self) -> bool {
        self.replay_recorder.is_enabled()
    }

    /// Returns a reference to the replay recorder.
    #[must_use]
    pub fn replay_recorder(&self) -> &TraceRecorder {
        &self.replay_recorder
    }

    /// Takes the replay trace, leaving an empty trace in place.
    ///
    /// Returns `None` if recording is disabled.
    pub fn take_replay_trace(&mut self) -> Option<ReplayTrace> {
        self.replay_recorder.take()
    }

    /// Finishes recording and returns the replay trace.
    ///
    /// This consumes the replay recorder. Returns `None` if recording is disabled.
    pub fn finish_replay_trace(&mut self) -> Option<ReplayTrace> {
        // Take ownership by replacing with a disabled recorder
        let recorder = std::mem::replace(&mut self.replay_recorder, TraceRecorder::disabled());
        recorder.finish()
    }

    /// Starts bounded capture of exact task/worker/lane/step/time dispatches.
    ///
    /// Capture is opt-in and lab-only. Reaching the bound does not perturb the
    /// source execution, but finishing the recorder then fails closed instead
    /// of returning a partial schedule.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleError::ZeroRecordingLimit`] for a zero bound or
    /// [`ForcedScheduleError::RecordingAlreadyActive`] when capture is active.
    pub fn start_forced_schedule_recording(
        &mut self,
        max_dispatches: usize,
    ) -> Result<(), ForcedScheduleError> {
        if max_dispatches == 0 {
            return Err(ForcedScheduleError::ZeroRecordingLimit);
        }
        if self.forced_schedule_recorder.is_some() {
            return Err(ForcedScheduleError::RecordingAlreadyActive);
        }
        if self.steps != 0 || self.certificate.decisions() != 0 {
            return Err(ForcedScheduleError::RuntimeAlreadyStarted {
                steps: self.steps,
                decisions: self.certificate.decisions(),
            });
        }
        self.forced_schedule_recorder = Some(ForcedScheduleRecorder {
            max_dispatches,
            dispatches: Vec::new(),
            truncated: false,
        });
        Ok(())
    }

    /// Finishes exact dispatch capture and binds it to terminal runtime state.
    ///
    /// # Errors
    ///
    /// Returns a typed error when capture was not active or its event bound was
    /// exceeded. A non-quiescent source is represented in the returned receipt
    /// and is rejected by [`Self::run_forced_schedule`].
    pub fn finish_forced_schedule_recording(
        &mut self,
    ) -> Result<ForcedSchedule, ForcedScheduleError> {
        let recorder = self
            .forced_schedule_recorder
            .take()
            .ok_or(ForcedScheduleError::RecordingNotActive)?;
        if recorder.truncated {
            return Err(ForcedScheduleError::RecordingLimitExceeded {
                max_dispatches: recorder.max_dispatches,
            });
        }
        Ok(ForcedSchedule {
            version: FORCED_SCHEDULE_SCHEMA_VERSION,
            seed: self.config.seed,
            config_hash: forced_schedule_config_hash(&self.config),
            dispatches: recorder.dispatches,
            terminal_steps: self.steps,
            terminal_nanos: self.now().as_nanos(),
            terminal_schedule_hash: self.certificate.hash(),
            terminal_quiescent: self.is_quiescent(),
            truncated: false,
        })
    }

    /// Executes an exact recorded dispatch projection on this fresh lab runtime.
    ///
    /// The next recorded task is removed from its exact authoritative queue
    /// before it is polled. There is no RNG-scheduler fallback: missing, early,
    /// stale, wrong-worker, wrong-lane, wrong-time, or extra work returns a typed
    /// error while leaving the mismatched task unpolled.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleError`] for incompatible or partial receipts,
    /// exhausted caller limits, or the first execution divergence.
    pub fn run_forced_schedule(
        &mut self,
        schedule: &ForcedSchedule,
        limits: ForcedScheduleLimits,
    ) -> Result<ForcedScheduleReport, ForcedScheduleError> {
        self.validate_forced_schedule(schedule, limits)?;

        let start_steps = self.steps;
        let mut consumed = 0usize;
        while self.steps < schedule.terminal_steps {
            let used = self.steps.saturating_sub(start_steps);
            if used >= limits.max_steps {
                return Err(ForcedScheduleError::WorkLimitExceeded {
                    steps: used,
                    limit: limits.max_steps,
                });
            }

            let next = schedule.dispatches.get(consumed);
            if let Some(dispatch) = next {
                let target = Time::from_nanos(dispatch.at_nanos);
                let can_auto_advance = self.scheduler.lock().is_empty()
                    && self.spawn_mailbox.is_empty()
                    && !self.state.has_deferred_cancel_dispatches()
                    && self.now() < target
                    && self.next_auto_advance_deadline() == Some(target);
                if can_auto_advance {
                    self.advance_time_to(target);
                    let _ = self.pump_due_system_events();
                }
            }

            if self.step_with_forced_dispatch(next.map(|dispatch| (consumed, dispatch)))? {
                consumed = consumed.saturating_add(1);
            }
        }

        // A source using auto-advance can reach its final virtual timestamp
        // after the last task dispatch (for example, while draining a reactor
        // event that does not wake another task). Reproduce that one bounded
        // terminal jump only when the runtime independently exposes the exact
        // recorded timer/reactor deadline. A caller-mutated timestamp or an
        // unrecorded manual clock jump is not self-authenticating. If the real
        // deadline makes work runnable, the missing dispatch below is still
        // rejected rather than selected by the normal scheduler.
        let terminal_target = Time::from_nanos(schedule.terminal_nanos);
        if consumed == schedule.dispatches.len()
            && self.scheduler.lock().is_empty()
            && self.spawn_mailbox.is_empty()
            && !self.state.has_deferred_cancel_dispatches()
            && self.now() < terminal_target
            && self.next_auto_advance_deadline() == Some(terminal_target)
        {
            self.advance_time_to(terminal_target);
            let _ = self.pump_due_system_events();
        }

        if consumed != schedule.dispatches.len() || !self.is_quiescent() {
            return Err(ForcedScheduleError::ScheduleExhausted { consumed });
        }
        let actual_nanos = self.now().as_nanos();
        if self.steps != schedule.terminal_steps || actual_nanos != schedule.terminal_nanos {
            return Err(ForcedScheduleError::TerminalMismatch {
                expected_steps: schedule.terminal_steps,
                expected_nanos: schedule.terminal_nanos,
                actual_steps: self.steps,
                actual_nanos,
            });
        }
        let actual_hash = self.certificate.hash();
        if actual_hash != schedule.terminal_schedule_hash {
            return Err(ForcedScheduleError::CertificateMismatch {
                expected: schedule.terminal_schedule_hash,
                actual: actual_hash,
            });
        }

        Ok(ForcedScheduleReport {
            dispatches: consumed,
            steps: self.steps.saturating_sub(start_steps),
            terminal_nanos: actual_nanos,
            schedule_hash: actual_hash,
            quiescent: true,
        })
    }

    /// Executes a deletion-only schedule candidate on this fresh runtime.
    ///
    /// Each retained task/worker/lane tuple is removed from its authoritative
    /// scheduler queue before polling. Scheduler RNG is still advanced as part
    /// of deterministic lab state, but it is never consulted to select a task.
    /// Once the retained choices are exhausted, the runner may pump only
    /// deterministic system work; it never polls an unrecorded task.
    ///
    /// # Errors
    ///
    /// Returns [`ForcedScheduleError`] for invalid provenance, incompatible
    /// runtime configuration, impossible retained choices, allocation failure,
    /// or exhausted caller-owned work.
    pub fn run_forced_schedule_candidate(
        &mut self,
        candidate: &ForcedScheduleCandidate,
        limits: ForcedScheduleCandidateLimits,
    ) -> Result<ForcedScheduleCandidateReport, ForcedScheduleError> {
        self.validate_forced_schedule_candidate(candidate, limits)?;

        let start_steps = self.steps;
        let mut work_units = 0u64;
        let mut consumed_source_indices = Vec::new();
        consumed_source_indices
            .try_reserve_exact(candidate.dispatches.len())
            .map_err(|_| ForcedScheduleError::CandidateAllocationFailed {
                requested: candidate.dispatches.len(),
            })?;

        for (candidate_index, retained) in candidate.dispatches.iter().enumerate() {
            loop {
                if self.has_pending_dispatch_commands() {
                    take_candidate_work(&mut work_units, limits.max_work_units)?;
                    let dispatched = self.step_with_candidate_dispatch(None)?;
                    debug_assert!(
                        !dispatched,
                        "candidate command pump must not poll a retained task"
                    );
                    continue;
                }
                if !self.candidate_has_runnable_work()
                    && let Some(deadline) = self.next_auto_advance_deadline()
                {
                    take_candidate_work(&mut work_units, limits.max_work_units)?;
                    if deadline > self.now() {
                        self.advance_time_to(deadline);
                    }
                    let _ = self.pump_due_system_events();
                    continue;
                }

                take_candidate_work(&mut work_units, limits.max_work_units)?;
                if self.step_with_candidate_dispatch(Some((candidate_index, &retained.dispatch)))? {
                    consumed_source_indices.push(retained.source_index);
                    break;
                }
            }
        }

        let termination = loop {
            if self.is_quiescent() {
                break ForcedScheduleCandidateTermination::Quiescent;
            }
            if self.candidate_has_runnable_work() {
                break ForcedScheduleCandidateTermination::Exhausted;
            }
            if self.has_pending_dispatch_commands() {
                take_candidate_work(&mut work_units, limits.max_work_units)?;
                let dispatched = self.step_with_candidate_dispatch(None)?;
                debug_assert!(
                    !dispatched,
                    "candidate system-work pump must not poll an unrecorded task"
                );
                continue;
            }
            if let Some(deadline) = self.next_auto_advance_deadline() {
                take_candidate_work(&mut work_units, limits.max_work_units)?;
                if deadline > self.now() {
                    self.advance_time_to(deadline);
                }
                let _ = self.pump_due_system_events();
                continue;
            }
            break ForcedScheduleCandidateTermination::Exhausted;
        };

        let steps_delta = self.steps.saturating_sub(start_steps);
        let lab = self.report_with_steps_delta(steps_delta);
        Ok(ForcedScheduleCandidateReport {
            termination,
            consumed_source_indices,
            work_units,
            lab,
        })
    }

    fn candidate_has_runnable_work(&self) -> bool {
        let now = self.now();
        self.scheduler.lock().has_runnable_work(now)
    }

    fn has_pending_dispatch_commands(&self) -> bool {
        !self.spawn_mailbox.is_empty() || self.state.has_deferred_cancel_dispatches()
    }

    fn validate_forced_schedule_candidate(
        &self,
        candidate: &ForcedScheduleCandidate,
        limits: ForcedScheduleCandidateLimits,
    ) -> Result<(), ForcedScheduleError> {
        validate_candidate_limits(limits)?;
        if candidate.version != FORCED_SCHEDULE_CANDIDATE_SCHEMA_VERSION {
            return Err(ForcedScheduleError::CandidateSchemaMismatch {
                expected: FORCED_SCHEDULE_CANDIDATE_SCHEMA_VERSION,
                found: candidate.version,
            });
        }
        if candidate.source_version != FORCED_SCHEDULE_SCHEMA_VERSION {
            return Err(ForcedScheduleError::SchemaMismatch {
                expected: FORCED_SCHEDULE_SCHEMA_VERSION,
                found: candidate.source_version,
            });
        }
        if candidate.seed != self.config.seed {
            return Err(ForcedScheduleError::SeedMismatch {
                expected: self.config.seed,
                found: candidate.seed,
            });
        }
        let config_hash = forced_schedule_config_hash(&self.config);
        if candidate.config_hash != config_hash {
            return Err(ForcedScheduleError::ConfigMismatch {
                expected: config_hash,
                found: candidate.config_hash,
            });
        }
        if self.steps != 0 || self.certificate.decisions() != 0 {
            return Err(ForcedScheduleError::RuntimeAlreadyStarted {
                steps: self.steps,
                decisions: self.certificate.decisions(),
            });
        }
        if candidate.source_dispatch_count > limits.max_source_dispatches {
            return Err(ForcedScheduleError::CandidateSourceLimitExceeded {
                found: candidate.source_dispatch_count,
                limit: limits.max_source_dispatches,
            });
        }
        if candidate.dispatches.len() > limits.max_candidate_dispatches {
            return Err(ForcedScheduleError::DispatchLimitExceeded {
                found: candidate.dispatches.len(),
                limit: limits.max_candidate_dispatches,
            });
        }
        let minimum_work = u64::try_from(candidate.dispatches.len()).unwrap_or(u64::MAX);
        if minimum_work > limits.max_work_units {
            return Err(ForcedScheduleError::CandidateWorkLimitExceeded {
                work_units: minimum_work,
                limit: limits.max_work_units,
            });
        }

        let worker_count = self.config.worker_count.max(1);
        let mut previous_source_index = None;
        let mut retained_dispatches = Vec::new();
        retained_dispatches
            .try_reserve_exact(candidate.dispatches.len())
            .map_err(|_| ForcedScheduleError::CandidateAllocationFailed {
                requested: candidate.dispatches.len(),
            })?;
        for (candidate_index, retained) in candidate.dispatches.iter().enumerate() {
            if retained.source_index >= candidate.source_dispatch_count {
                return Err(ForcedScheduleError::CandidateIndexOutOfRange {
                    candidate_index,
                    source_index: retained.source_index,
                    source_len: candidate.source_dispatch_count,
                });
            }
            if let Some(previous) = previous_source_index
                && retained.source_index <= previous
            {
                return Err(ForcedScheduleError::CandidateIndexOrder {
                    candidate_index,
                    previous,
                    next: retained.source_index,
                });
            }
            if retained.dispatch.worker as usize >= worker_count {
                return Err(ForcedScheduleError::WorkerUnavailable {
                    worker: retained.dispatch.worker,
                    worker_count,
                });
            }
            retained_dispatches.push(retained.dispatch);
            previous_source_index = Some(retained.source_index);
        }
        validate_dispatch_order(&retained_dispatches)
    }

    fn validate_forced_schedule(
        &self,
        schedule: &ForcedSchedule,
        limits: ForcedScheduleLimits,
    ) -> Result<(), ForcedScheduleError> {
        if schedule.version != FORCED_SCHEDULE_SCHEMA_VERSION {
            return Err(ForcedScheduleError::SchemaMismatch {
                expected: FORCED_SCHEDULE_SCHEMA_VERSION,
                found: schedule.version,
            });
        }
        if schedule.seed != self.config.seed {
            return Err(ForcedScheduleError::SeedMismatch {
                expected: self.config.seed,
                found: schedule.seed,
            });
        }
        let config_hash = forced_schedule_config_hash(&self.config);
        if schedule.config_hash != config_hash {
            return Err(ForcedScheduleError::ConfigMismatch {
                expected: config_hash,
                found: schedule.config_hash,
            });
        }
        if self.steps != 0 || self.certificate.decisions() != 0 {
            return Err(ForcedScheduleError::RuntimeAlreadyStarted {
                steps: self.steps,
                decisions: self.certificate.decisions(),
            });
        }
        if schedule.truncated || !schedule.terminal_quiescent {
            return Err(ForcedScheduleError::PartialSource);
        }
        if schedule.dispatches.len() > limits.max_dispatches {
            return Err(ForcedScheduleError::DispatchLimitExceeded {
                found: schedule.dispatches.len(),
                limit: limits.max_dispatches,
            });
        }
        if schedule.terminal_steps > limits.max_steps {
            return Err(ForcedScheduleError::WorkLimitExceeded {
                steps: schedule.terminal_steps,
                limit: limits.max_steps,
            });
        }

        let worker_count = self.config.worker_count.max(1);
        let mut previous_step = 0u64;
        let mut previous_nanos = 0u64;
        for (index, dispatch) in schedule.dispatches.iter().enumerate() {
            if dispatch.at_step <= previous_step {
                return Err(ForcedScheduleError::StepOrder {
                    index,
                    previous: previous_step,
                    next: dispatch.at_step,
                });
            }
            if dispatch.at_nanos < previous_nanos {
                return Err(ForcedScheduleError::TimeOrder {
                    index,
                    previous: previous_nanos,
                    next: dispatch.at_nanos,
                });
            }
            if dispatch.worker as usize >= worker_count {
                return Err(ForcedScheduleError::WorkerUnavailable {
                    worker: dispatch.worker,
                    worker_count,
                });
            }
            previous_step = dispatch.at_step;
            previous_nanos = dispatch.at_nanos;
        }
        if previous_step > schedule.terminal_steps || previous_nanos > schedule.terminal_nanos {
            return Err(ForcedScheduleError::PartialSource);
        }
        Ok(())
    }

    /// Returns true if chaos injection is enabled.
    #[must_use]
    pub fn has_chaos(&self) -> bool {
        self.chaos_rng.is_some() && self.config.has_chaos()
    }

    /// Returns true if the runtime is quiescent.
    #[must_use]
    pub fn is_quiescent(&self) -> bool {
        self.state.is_quiescent() && self.spawn_mailbox.is_empty()
    }

    /// Advances virtual time by the given number of nanoseconds.
    pub fn advance_time(&mut self, nanos: u64) {
        let from = self.virtual_time;
        self.virtual_time = self.virtual_time.saturating_add_nanos(nanos);
        self.state.now = self.virtual_time;
        self.virtual_clock.advance(nanos);
        self.lab_reactor.advance_time(Duration::from_nanos(nanos));
        // Record time advancement
        self.replay_recorder
            .record_time_advanced(from, self.virtual_time);

        crate::tracing_compat::debug!(
            "virtual clock advanced: delta_ms={}, new_time_ms={}",
            nanos / 1_000_000,
            self.virtual_time.as_nanos() / 1_000_000
        );
    }

    /// Advances time to the given absolute time.
    ///
    /// If the target time is before the current time, logs an error
    /// and does nothing (time cannot go backward).
    pub fn advance_time_to(&mut self, time: Time) {
        if time > self.virtual_time {
            let from = self.virtual_time;
            self.virtual_time = time;
            self.state.now = self.virtual_time;
            self.virtual_clock.advance_to(time);
            self.lab_reactor.advance_time_to(time);
            // Record time advancement
            self.replay_recorder
                .record_time_advanced(from, self.virtual_time);

            crate::tracing_compat::debug!(
                "virtual clock advanced: delta_ms={}, new_time_ms={}",
                (time.as_nanos() - from.as_nanos()) / 1_000_000,
                time.as_nanos() / 1_000_000
            );
        } else if time < self.virtual_time {
            crate::tracing_compat::error!(
                "virtual clock attempt to go backward: current_ms={}, requested_ms={}",
                self.virtual_time.as_nanos() / 1_000_000,
                time.as_nanos() / 1_000_000
            );
        }
    }

    // =========================================================================
    // Virtual time control (bd-1hu19.3)
    // =========================================================================

    /// Advances virtual time to the next timer deadline.
    ///
    /// If a timer is pending, advances time to its deadline, processes the
    /// expired timer(s), and returns the number of wakeups triggered.
    /// Returns 0 if no timers are pending.
    pub fn advance_to_next_timer(&mut self) -> usize {
        let next = self
            .state
            .timer_driver_handle()
            .and_then(|h| h.next_deadline());

        let Some(deadline) = next else {
            return 0;
        };

        if deadline <= self.virtual_time {
            // Timer already expired, just process it
            return self
                .state
                .timer_driver_handle()
                .map_or(0, |h| h.process_timers());
        }

        let delta_nanos = deadline.as_nanos() - self.virtual_time.as_nanos();
        self.advance_time(delta_nanos);

        let wakeups = self
            .state
            .timer_driver_handle()
            .map_or(0, |h| h.process_timers());

        crate::tracing_compat::debug!(
            "virtual clock auto-advance: reason=all_tasks_blocked, \
             next_wakeup_ms={}, delta_ms={}, wakeup_count={}",
            deadline.as_nanos() / 1_000_000,
            delta_nanos / 1_000_000,
            wakeups
        );

        wakeups
    }

    /// Returns the next timer deadline, if any timers are pending.
    #[must_use]
    pub fn next_timer_deadline(&self) -> Option<Time> {
        self.state
            .timer_driver_handle()
            .and_then(|h| h.next_deadline())
    }

    fn next_reactor_deadline(&self) -> Option<Time> {
        self.state
            .io_driver_handle()
            .and_then(|_| self.lab_reactor.next_event_time())
    }

    fn next_auto_advance_deadline(&self) -> Option<Time> {
        match (self.next_timer_deadline(), self.next_reactor_deadline()) {
            (Some(timer), Some(reactor)) => Some(timer.min(reactor)),
            (Some(timer), None) => Some(timer),
            (None, Some(reactor)) => Some(reactor),
            (None, None) => None,
        }
    }

    fn pump_due_system_events(&mut self) -> usize {
        let wakeups = self
            .state
            .timer_driver_handle()
            .map_or(0, |h| h.process_timers());
        self.poll_io();
        self.schedule_async_finalizers();
        self.check_deadline_monitor();
        wakeups
    }

    /// Returns the number of pending timers.
    #[must_use]
    pub fn pending_timer_count(&self) -> usize {
        self.state
            .timer_driver_handle()
            .map_or(0, |h| h.pending_count())
    }

    /// Runs until quiescent, automatically advancing virtual time to pending
    /// timer or lab-reactor deadlines whenever all tasks are idle.
    ///
    /// This enables "instant timeout testing": a scenario that would take
    /// 24 hours of wall-clock time completes in <1 second because every
    /// `sleep`/`timeout` deadline is jumped to instantly.
    ///
    /// The loop is:
    /// 1. Run until idle (no runnable tasks in scheduler).
    /// 2. If timers or lab-reactor events are pending, advance time to the
    ///    next deadline → go to 1.
    /// 3. If no pending virtual deadlines and quiescent → done.
    ///
    /// Returns a [`VirtualTimeReport`] with execution statistics.
    pub fn run_with_auto_advance(&mut self) -> VirtualTimeReport {
        let start_steps = self.steps;
        let mut auto_advances: u64 = 0;
        let mut total_wakeups: u64 = 0;
        let mut stuck_counter: u32 = 0;
        let start_time = self.virtual_time;

        let termination = loop {
            // Check step limit
            if let Some(max) = self.config.max_steps {
                if self.steps >= max {
                    break AutoAdvanceTermination::StepLimitReached;
                }
            }

            // Run until the scheduler is empty
            let is_empty = self.scheduler.lock().is_empty();
            if !is_empty {
                // GH#55: reset the stall counter only when the step actually
                // dispatched something. `is_empty()` reads `scheduled`, which
                // can retain a task that is no longer queued in any worker
                // lane; resetting unconditionally made `StuckBailout`
                // unreachable, turning that strand into an unbounded spin
                // bounded only by `max_steps`.
                let before = self.dispatches;
                self.step();
                if self.dispatches != before {
                    stuck_counter = 0;
                } else {
                    stuck_counter = stuck_counter.saturating_add(1);
                    if stuck_counter > 1000 {
                        break AutoAdvanceTermination::StuckBailout;
                    }
                }
                continue;
            }

            // Scheduler is empty — check if we should auto-advance
            if self.has_pending_dispatch_commands() {
                self.step();
                continue;
            }
            if let Some(deadline) = self.next_auto_advance_deadline() {
                if deadline > self.virtual_time {
                    self.advance_time_to(deadline);
                    let wakeups = self
                        .state
                        .timer_driver_handle()
                        .map_or(0, |h| h.process_timers());
                    auto_advances = auto_advances.saturating_add(1);
                    total_wakeups = total_wakeups.saturating_add(wakeups as u64);
                    continue;
                }
                // A timer or reactor event is already due at the current time.
                total_wakeups = total_wakeups.saturating_add(self.pump_due_system_events() as u64);
                continue;
            }

            // No runnable tasks and no pending virtual deadlines → quiescent
            if self.is_quiescent() {
                break AutoAdvanceTermination::Quiescent;
            }

            // Not quiescent but nothing to advance — try one more step
            // (there may be I/O or finalizers to process)
            stuck_counter = stuck_counter.saturating_add(1);
            if stuck_counter > 1000 {
                break AutoAdvanceTermination::StuckBailout;
            }
            self.step();
        };

        VirtualTimeReport {
            steps: self.steps - start_steps,
            auto_advances,
            total_wakeups,
            time_start: start_time,
            time_end: self.virtual_time,
            virtual_elapsed_nanos: self.virtual_time.as_nanos() - start_time.as_nanos(),
            termination,
        }
    }

    /// Pauses the virtual clock, freezing time at the current value.
    ///
    /// While paused, `advance_time()` and timer processing still work at the
    /// `LabRuntime` level (they update the runtime's own `virtual_time` field),
    /// but the underlying `VirtualClock` visible to tasks via `Cx::now()` is
    /// frozen. This is useful for testing timeout detection: tasks that call
    /// `Cx::now()` will see time standing still while the runtime can still
    /// orchestrate scheduling.
    pub fn pause_clock(&self) {
        self.virtual_clock.pause();
        crate::tracing_compat::info!(
            "virtual clock paused at time_ms={}",
            self.virtual_time.as_nanos() / 1_000_000
        );
    }

    /// Resumes a paused virtual clock.
    pub fn resume_clock(&self) {
        self.virtual_clock.resume();
        crate::tracing_compat::info!(
            "virtual clock resumed at time_ms={}",
            self.virtual_time.as_nanos() / 1_000_000
        );
    }

    /// Returns true if the virtual clock is currently paused.
    #[must_use]
    pub fn is_clock_paused(&self) -> bool {
        self.virtual_clock.is_paused()
    }

    /// Injects a clock skew by jumping time forward by `skew_nanos`.
    ///
    /// This simulates clock drift or NTP corrections. A warning is logged
    /// because large jumps may affect lease/timeout correctness.
    #[allow(clippy::no_effect_underscore_binding)]
    pub fn inject_clock_skew(&mut self, skew_nanos: u64) {
        // Capture old time *before* advance for accurate logging.
        let old_nanos = self.virtual_time.as_nanos();
        self.advance_time(skew_nanos);

        crate::tracing_compat::warn!(
            "virtual clock jump detected: old_time_ms={}, new_time_ms={}, jump_ms={} \
             -- may affect lease/timeout correctness",
            old_nanos / 1_000_000,
            self.virtual_time.as_nanos() / 1_000_000,
            skew_nanos / 1_000_000
        );
        #[cfg(not(feature = "tracing-integration"))]
        let _ = old_nanos;
    }

    /// Runs until quiescent or max steps reached.
    ///
    /// Returns the number of steps executed.
    pub fn run_until_quiescent(&mut self) -> u64 {
        let start_steps = self.steps;

        while !self.is_quiescent() {
            if let Some(max) = self.config.max_steps {
                if self.steps >= max {
                    break;
                }
            }
            self.step();
        }

        self.steps - start_steps
    }

    /// Runs until there are no runnable tasks in the scheduler.
    ///
    /// This is intentionally weaker than [`Self::run_until_quiescent`]:
    /// - It does **not** require all tasks to complete.
    /// - It does **not** require all obligations to be resolved.
    ///
    /// Use this when a test wants to "poll once" until the system is *idle*
    /// (e.g. a task is blocked on a channel receive) without forcing full
    /// completion and drain.
    pub fn run_until_idle(&mut self) -> u64 {
        let start_steps = self.steps;

        loop {
            if let Some(max) = self.config.max_steps {
                if self.steps >= max {
                    break;
                }
            }

            self.drain_handle_cancel_requests();
            self.drain_deferred_cancel_dispatches();
            let is_empty = self.scheduler.lock().is_empty();
            if is_empty && !self.has_pending_dispatch_commands() {
                break;
            }

            self.step();
        }

        self.steps - start_steps
    }

    /// Runs until quiescent (or `max_steps` is reached) and returns a structured report.
    #[must_use]
    pub fn run_until_quiescent_with_report(&mut self) -> LabRunReport {
        let steps_delta = self.run_until_quiescent();
        self.report_with_steps_delta(steps_delta)
    }

    /// Build a structured report for the current runtime state.
    ///
    /// This does not advance execution.
    #[must_use]
    pub fn report(&mut self) -> LabRunReport {
        self.report_with_steps_delta(0)
    }

    /// Runs until quiescent (or `max_steps` is reached) and returns a Spork harness report.
    #[must_use]
    pub fn run_until_quiescent_spork_report(
        &mut self,
        app: impl Into<String>,
        attachments: Vec<HarnessAttachmentRef>,
    ) -> SporkHarnessReport {
        let run = self.run_until_quiescent_with_report();
        self.build_spork_report(app.into(), run, attachments)
    }

    /// Build a Spork harness report for the current runtime state.
    ///
    /// This does not advance execution.
    #[must_use]
    pub fn spork_report(
        &mut self,
        app: impl Into<String>,
        attachments: Vec<HarnessAttachmentRef>,
    ) -> SporkHarnessReport {
        let run = self.report();
        self.build_spork_report(app.into(), run, attachments)
    }

    fn build_spork_report(
        &self,
        app: String,
        run: LabRunReport,
        mut attachments: Vec<HarnessAttachmentRef>,
    ) -> SporkHarnessReport {
        if let Some(auto_crashpack) = self.auto_crashpack_attachment(&run, &attachments) {
            attachments.push(auto_crashpack);
        }
        SporkHarnessReport::new(app, &self.config, run, attachments)
    }

    fn auto_crashpack_attachment(
        &self,
        run: &LabRunReport,
        attachments: &[HarnessAttachmentRef],
    ) -> Option<HarnessAttachmentRef> {
        if attachments
            .iter()
            .any(|attachment| attachment.kind == HarnessAttachmentKind::CrashPack)
        {
            return None;
        }
        let crashpack = self.build_crashpack_for_report(run)?;
        Some(HarnessAttachmentRef::crashpack(artifact_filename(
            &crashpack,
        )))
    }

    /// Build an in-memory crashpack for a failing report.
    ///
    /// Returns `None` for passing reports.
    #[must_use]
    pub fn build_crashpack_for_report(&self, run: &LabRunReport) -> Option<CrashPack> {
        self.build_crashpack_for_report_with_outcome(run, None, None, None, None)
    }

    /// Write a deterministic crashpack for a failing lab-test report.
    ///
    /// Returns `Ok(None)` when the report is passing, when auto-artifacts are
    /// disabled with `ASUPERSYNC_AUTO_ARTIFACTS=0`, or when no crashpack can be
    /// built for the report.
    pub fn write_auto_crashpack_for_report(
        &self,
        test_name: &str,
        run: &LabRunReport,
    ) -> Result<Option<LabAutoCrashpack>, LabAutoCrashpackError> {
        self.write_auto_crashpack(test_name, run, None, None, None)
    }

    /// Write a deterministic crashpack for a panic observed by a lab test body.
    ///
    /// This is used when a test panics before oracle assertions are evaluated.
    pub fn write_auto_crashpack_for_panic(
        &self,
        test_name: &str,
        run: &LabRunReport,
        panic_message: &str,
    ) -> Result<Option<LabAutoCrashpack>, LabAutoCrashpackError> {
        self.write_auto_crashpack(
            test_name,
            run,
            None,
            Some(FailureOutcome::Panicked {
                message: panic_message.to_string(),
            }),
            Some(format!("panic:{panic_message}")),
        )
    }

    fn write_auto_crashpack_for_task_failure(
        &self,
        test_name: &str,
        run: &LabRunReport,
        task: TaskId,
        region: RegionId,
        outcome: FailureOutcome,
        failure_detail: &str,
    ) -> Result<Option<LabAutoCrashpack>, LabAutoCrashpackError> {
        self.write_auto_crashpack(
            test_name,
            run,
            Some((task, region)),
            Some(outcome),
            Some(format!("task_failure:{failure_detail}")),
        )
    }

    fn write_auto_crashpack(
        &self,
        test_name: &str,
        run: &LabRunReport,
        failure_identity: Option<(TaskId, RegionId)>,
        forced_outcome: Option<FailureOutcome>,
        extra_violation: Option<String>,
    ) -> Result<Option<LabAutoCrashpack>, LabAutoCrashpackError> {
        if !auto_artifacts_enabled() {
            return Ok(None);
        }

        let Some(mut pack) = self.build_crashpack_for_report_with_outcome(
            run,
            Some(test_name),
            failure_identity,
            forced_outcome,
            extra_violation,
        ) else {
            return Ok(None);
        };

        let dir = auto_crashpack_dir(test_name, &pack);
        std::fs::create_dir_all(&dir).map_err(|source| LabAutoCrashpackError::CreateDir {
            path: dir.clone(),
            source,
        })?;

        let replay = pack.replay_command();
        pack.replay = Some(replay.clone());

        let writer = FileCrashPackWriter::new(dir);
        let artifact = writer.write(&pack)?;

        Ok(Some(LabAutoCrashpack {
            path: artifact.path().to_string(),
            replay,
        }))
    }

    fn build_crashpack_for_report_with_outcome(
        &self,
        run: &LabRunReport,
        test_name: Option<&str>,
        failure_identity: Option<(TaskId, RegionId)>,
        forced_outcome: Option<FailureOutcome>,
        extra_violation: Option<String>,
    ) -> Option<CrashPack> {
        let has_failure = !run.oracle_report.all_passed()
            || !run.invariant_violations.is_empty()
            || !run.quiescent
            || run.refinement_firewall_rule_id.is_some()
            || forced_outcome.is_some();
        if !has_failure {
            return None;
        }

        let config_summary = LabConfigSummary::from_config(&self.config);
        let crash_config = CrashPackConfig {
            seed: run.seed,
            config_hash: config_summary.config_hash(),
            worker_count: self.config.worker_count,
            max_steps: self.config.max_steps,
            test_name: test_name.map(str::to_owned),
            commit_hash: compiled_commit_hash(),
        };

        let failed_task = self.state.tasks_iter().find_map(|(_, task)| {
            let outcome = match &task.state {
                TaskState::Completed(crate::types::Outcome::Err(_)) => FailureOutcome::Err,
                TaskState::Completed(crate::types::Outcome::Cancelled(reason)) => {
                    FailureOutcome::Cancelled {
                        cancel_kind: reason.kind(),
                    }
                }
                TaskState::Completed(crate::types::Outcome::Panicked(payload)) => {
                    FailureOutcome::Panicked {
                        message: payload.message().to_owned(),
                    }
                }
                _ => return None,
            };
            Some((task.id, task.owner, outcome))
        });
        let (task, region, inferred_outcome) = failure_identity
            .map(|(task, region)| (task, region, None))
            .or_else(|| failed_task.map(|(task, region, outcome)| (task, region, Some(outcome))))
            .or_else(|| {
                self.state
                    .tasks_iter()
                    .find(|(_, task)| !task.state.is_terminal())
                    .map(|(_, task)| (task.id, task.owner, None))
            })
            .or_else(|| {
                self.state
                    .obligations_iter()
                    .find(|(_, obligation)| obligation.is_pending())
                    .map(|(_, obligation)| (obligation.holder, obligation.region, None))
            })
            .or_else(|| {
                self.state
                    .regions_iter()
                    .next()
                    .map(|(_, region)| (TaskId::testing_default(), region.id, None))
            })
            .or_else(|| {
                self.state
                    .root_region
                    .map(|root| (TaskId::testing_default(), root, None))
            })
            .unwrap_or((TaskId::testing_default(), RegionId::testing_default(), None));

        let mut oracle_violations = run.invariant_violations.clone();
        oracle_violations.extend(
            run.oracle_report
                .failures()
                .iter()
                .map(|entry| entry.invariant.clone()),
        );
        if let Some(rule_id) = &run.refinement_firewall_rule_id {
            oracle_violations.push(format!("refinement_firewall:{rule_id}"));
        }
        if let Some(prefix_len) = run.refinement_counterexample_prefix_len {
            oracle_violations.push(format!(
                "refinement_firewall:minimal_counterexample_prefix_len={prefix_len}"
            ));
        }
        if let Some(extra_violation) = extra_violation {
            oracle_violations.push(extra_violation);
        }
        oracle_violations.sort();
        oracle_violations.dedup();

        let trace_events = self.trace().snapshot();
        let mut builder = CrashPack::builder(crash_config.clone())
            .failure(FailureInfo {
                task,
                region,
                outcome: forced_outcome
                    .or(inferred_outcome)
                    .unwrap_or(FailureOutcome::Err),
                virtual_time: Time::from_nanos(run.now_nanos),
            })
            .created_at(run.now_nanos)
            .oracle_violations(oracle_violations)
            .replay(ReplayCommand::from_config(&crash_config));

        let divergent_prefix = self.auto_divergent_prefix();
        if !divergent_prefix.is_empty() {
            builder = builder.divergent_prefix(divergent_prefix);
        }

        builder = if trace_events.is_empty() {
            builder
                .fingerprint(run.trace_fingerprint)
                .event_count(run.trace_certificate.event_count)
        } else {
            builder.from_trace(&trace_events)
        };

        match builder.build() {
            Ok(pack) => Some(pack),
            Err(err) => {
                let _ = &err;
                crate::tracing_compat::error!("failed to build crash pack for lab report: {err}");
                None
            }
        }
    }

    fn auto_divergent_prefix(&self) -> Vec<ReplayEvent> {
        let Some(replay_trace) = self.replay_recorder.snapshot() else {
            return Vec::new();
        };
        if replay_trace.events.is_empty() {
            return Vec::new();
        }

        let failure_index = replay_trace
            .events
            .iter()
            .position(
                |event| matches!(event, ReplayEvent::TaskCompleted { outcome, .. } if *outcome > 0),
            )
            .unwrap_or(replay_trace.events.len().saturating_sub(1));

        crate::trace::minimal_divergent_prefix(&replay_trace, failure_index).events
    }

    fn report_with_steps_delta(&mut self, steps_delta: u64) -> LabRunReport {
        let seed = self.config.seed;
        let quiescent = self.is_quiescent();
        let now = self.now();

        let trace_events = self.trace().snapshot();
        let trace_len = trace_events.len();

        let trace_fingerprint = if trace_events.is_empty() {
            // Mirror explorer behavior: ensure the report fingerprint varies by seed
            // even if trace capture is effectively disabled / empty.
            seed_fingerprint(seed)
        } else {
            trace_fingerprint(&trace_events)
        };

        let schedule_hash = self.certificate().hash();
        let mut certificate = TraceCertificate::new();
        for e in &trace_events {
            certificate.record_event(e);
        }
        certificate.set_schedule_hash(schedule_hash);

        self.oracles.hydrate_temporal_from_state(&self.state, now);
        let oracle_report = self.oracles.report(now);
        let oracle_invariant_failures = oracle_report
            .failures()
            .into_iter()
            .map(|entry| entry.invariant.clone())
            .collect::<Vec<_>>();
        let temporal_invariant_failures = oracle_invariant_failures
            .iter()
            .filter(|invariant| TEMPORAL_ORACLE_INVARIANTS.contains(&invariant.as_str()))
            .cloned()
            .collect::<Vec<_>>();
        let temporal_counterexample_prefix_len = if temporal_invariant_failures.is_empty() {
            None
        } else {
            let prefix_len = self.auto_divergent_prefix().len();
            (prefix_len > 0).then_some(prefix_len)
        };
        // br-asupersync-9ri7x0: capture the truncation watermark BEFORE
        // deciding whether to run the firewall. Previously, when
        // total_pushed > buffer_len the refinement-firewall oracle was
        // silently disabled and the scenario could still report
        // 'passed' — adversarial event-heavy scenarios could drown out
        // detection by deliberately exceeding the buffer. The new
        // contract: a truncated trace MUST surface as an explicit
        // violation in invariant_violations so the scenario fails
        // loudly, naming the seed and the truncation watermark.
        let trace_total_pushed = self.trace().total_pushed();
        let trace_buffered_len = trace_events.len() as u64;
        let refinement_firewall_skipped_due_to_trace_truncation =
            trace_total_pushed > trace_buffered_len;
        let refinement_violation = if refinement_firewall_skipped_due_to_trace_truncation {
            None
        } else {
            check_refinement_firewall(&trace_events).first_violation
        };
        let refinement_violation = refinement_violation.as_ref();
        let refinement_firewall_rule_id = refinement_violation.map(|v| v.rule_id.to_owned());
        let refinement_firewall_event_index = refinement_violation.map(|v| v.event_index);
        let refinement_firewall_event_seq = refinement_violation.map(|v| v.event_seq);
        let refinement_counterexample_prefix_len =
            refinement_firewall_event_index.map(|idx| idx + 1);

        let mut invariant_violations = self
            .check_invariants()
            .into_iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>();
        for invariant in &oracle_invariant_failures {
            invariant_violations.push(format!("oracle:{invariant}"));
        }
        for invariant in &temporal_invariant_failures {
            invariant_violations.push(format!("temporal:{invariant}"));
        }
        if let Some(prefix_len) = temporal_counterexample_prefix_len {
            invariant_violations.push(format!(
                "temporal:minimal_divergent_prefix_len={prefix_len}"
            ));
        }
        if let Some(rule_id) = &refinement_firewall_rule_id {
            invariant_violations.push(format!("refinement_firewall:{rule_id}"));
        }
        if let Some(prefix_len) = refinement_counterexample_prefix_len {
            invariant_violations.push(format!(
                "refinement_firewall:minimal_counterexample_prefix_len={prefix_len}"
            ));
        }
        // br-asupersync-9ri7x0: when the in-memory event buffer was
        // overrun, the refinement-firewall oracle could not run on the
        // suffix that was dropped. Report it as a hard scenario
        // failure with the seed + watermark so an operator can
        // increase trace_capacity (or split the scenario) instead of
        // silently shipping a green result.
        if refinement_firewall_skipped_due_to_trace_truncation {
            invariant_violations.push(format!(
                "refinement_firewall:scenario_failed_due_to_trace_truncation:\
                 seed={seed},total_pushed={trace_total_pushed},buffered={trace_buffered_len}"
            ));
        }
        invariant_violations.sort();
        invariant_violations.dedup();

        LabRunReport {
            seed,
            steps_delta,
            steps_total: self.steps(),
            quiescent,
            now_nanos: now.as_nanos(),
            trace_len,
            trace_fingerprint,
            trace_certificate: LabTraceCertificateSummary {
                event_hash: certificate.event_hash(),
                event_count: certificate.event_count(),
                schedule_hash: certificate.schedule_hash(),
            },
            oracle_report,
            invariant_violations,
            temporal_invariant_failures,
            temporal_counterexample_prefix_len,
            refinement_firewall_rule_id,
            refinement_firewall_event_index,
            refinement_firewall_event_seq,
            refinement_counterexample_prefix_len,
            refinement_firewall_skipped_due_to_trace_truncation,
        }
    }

    /// Enable deadline monitoring with the default warning handler.
    pub fn enable_deadline_monitoring(&mut self, config: MonitorConfig) {
        self.enable_deadline_monitoring_with_handler(config, default_warning_handler);
    }

    /// Enable deadline monitoring with a custom warning handler.
    pub fn enable_deadline_monitoring_with_handler<F>(&mut self, config: MonitorConfig, f: F)
    where
        F: Fn(DeadlineWarning) + Send + Sync + 'static,
    {
        let mut monitor = DeadlineMonitor::new(config);
        monitor.on_warning(f);
        self.deadline_monitor = Some(monitor);
    }

    /// Returns a mutable reference to the deadline monitor, if enabled.
    pub fn deadline_monitor_mut(&mut self) -> Option<&mut DeadlineMonitor> {
        self.deadline_monitor.as_mut()
    }

    /// Returns the lab's deterministic spawn mailbox.
    ///
    /// Requests enqueued here (with pending-spawn credits, per the A1.2
    /// contract) are admitted in FIFO order at the start of the next step,
    /// so `run_until_quiescent` observes them as live work end to end.
    #[must_use]
    pub fn spawn_mailbox(&self) -> Arc<crate::runtime::spawn_mailbox::SpawnMailbox> {
        Arc::clone(&self.spawn_mailbox)
    }

    /// Admits every pending spawn request in FIFO order
    /// (br-asupersync-4h8lye / A2.1). Lab is single-threaded, so denial
    /// slots run inline; admitted tasks join the lab scheduler at their
    /// budget priority. Deterministic: admission order is exactly enqueue
    /// order, and the admitted arena ids depend only on prior state.
    fn drain_spawn_admissions(&mut self) {
        if self.spawn_mailbox.spawn_requests_are_empty() {
            return;
        }
        while let Some(request) = self.spawn_mailbox.dequeue() {
            match self.state.admit_spawn_request(request.into_parts()) {
                crate::runtime::state::SpawnAdmission::Admitted {
                    task_id,
                    priority,
                    cancel_publication,
                    spawn_effects,
                } => {
                    let (cancel_wakes, spawn_effects) = cancel_publication
                        .publish_with_spawn_effects(spawn_effects, |cancel_priority| {
                            let mut scheduler = self.scheduler.lock();
                            if let Some(cancel_priority) = cancel_priority {
                                scheduler.schedule_cancel(task_id, cancel_priority);
                            } else {
                                scheduler.schedule(task_id, priority);
                            }
                        });
                    // The closure-local scheduler guard is gone and the task's
                    // runnable/cancel lane is visible before observer reentry.
                    if let Some(spawn_effects) = spawn_effects {
                        spawn_effects.dispatch();
                    }
                    cancel_wakes.dispatch();
                }
                crate::runtime::state::SpawnAdmission::Denied { parts, error } => match error {
                    crate::runtime::state::SpawnError::RegionClosed(_)
                    | crate::runtime::state::SpawnError::RegionNotFound(_) => {
                        parts.resolve_cancelled(crate::types::CancelReason::new(
                            crate::types::CancelKind::ParentCancelled,
                        ));
                    }
                    other => parts.resolve_failed(other),
                },
            }
        }
    }

    /// Applies a bounded batch of callback-free TaskHandle cancellation
    /// commands. Every required cancel lane is physically published before
    /// any retained Waker is invoked.
    fn drain_handle_cancel_requests(&mut self) {
        const HANDLE_CANCEL_BATCH: usize = 16;

        if self.spawn_mailbox.handle_cancels_are_empty() {
            return;
        }
        let mut requests = Vec::with_capacity(HANDLE_CANCEL_BATCH);
        if self
            .spawn_mailbox
            .dequeue_handle_cancels_into(HANDLE_CANCEL_BATCH, &mut requests)
            == 0
        {
            return;
        }

        let requests = crate::runtime::spawn_mailbox::coalesce_handle_cancel_requests(requests);
        // Annotate explicitly: the task/priority prefix is only pinned by
        // `schedule_cancel(task_id, priority)` far below, which the current
        // nightly no longer back-infers through the `&mut tasks`/`&mut delegated`
        // shared `target` binding (E0282).
        //
        // The break is configuration-dependent, not universal: it first showed
        // up building asupersync as a *path dependency of FrankenSQLite*, whose
        // narrower downstream feature set gives inference less to work with than
        // this crate's own `cargo check`. So a green build here does NOT prove
        // the annotation is redundant — drop it and the downstream consumer is
        // what breaks, not us.
        let mut tasks: Vec<(
            TaskId,
            u8,
            Option<Arc<crate::runtime::spawn_mailbox::AdmittedTaskSlot>>,
        )> = Vec::with_capacity(requests.len());
        let mut delegated: Vec<(
            TaskId,
            u8,
            Option<Arc<crate::runtime::spawn_mailbox::AdmittedTaskSlot>>,
        )> = Vec::new();
        let mut spawn_effects_to_dispatch = Vec::with_capacity(requests.len());
        let mut wakes = crate::types::task_context::CancelWakeEffects::empty();
        for request in requests {
            let task_id = request.task_id;
            let reason = request.reason;
            let admitted_slot = request.admitted_slot;
            let task_exists = self.state.task(task_id).is_some();
            let effects = self.state.cancel_task_for_handle(task_id, &reason);
            let (route, task_wakes) = effects.into_parts();
            wakes.merge(task_wakes);

            let Some(route) = route else {
                if task_exists
                    && let Some(admitted_slot) = admitted_slot
                    && let Some(effects) = admitted_slot.take_spawn_effects_if_lane_published()
                {
                    spawn_effects_to_dispatch.push(effects);
                }
                continue;
            };
            let target = if route.delegated_initial {
                &mut delegated
            } else {
                &mut tasks
            };
            if let Some((_, queued_priority, queued_slot)) = target
                .iter_mut()
                .find(|(queued_task_id, _, _)| *queued_task_id == task_id)
            {
                *queued_priority = (*queued_priority).max(route.priority);
                if queued_slot.is_none() {
                    *queued_slot = admitted_slot;
                }
            } else {
                target.push((task_id, route.priority, admitted_slot));
            }
        }

        {
            let mut scheduler = self.scheduler.lock();
            for (task_id, priority, admitted_slot) in tasks {
                scheduler.schedule_cancel(task_id, priority);
                if let Some(admitted_slot) = admitted_slot
                    && let Some(effects) = admitted_slot.publish_spawn_lane_and_take_effects()
                {
                    spawn_effects_to_dispatch.push(effects);
                }
            }
        }

        for (task_id, requested_priority, admitted_slot) in delegated {
            let scheduler = &self.scheduler;
            let (published_priority, task_wakes) = self
                .state
                .publish_handle_cancel_lane(task_id, |priority, _, _| {
                    scheduler.lock().schedule_cancel(task_id, priority);
                    Some(priority)
                })
                .into_parts();
            if let Some(published_priority) = published_priority {
                let spawn_effects = admitted_slot
                    .as_ref()
                    .and_then(|slot| slot.publish_spawn_lane_and_take_effects());
                debug_assert!(published_priority >= requested_priority);
                if let Some(effects) = spawn_effects {
                    spawn_effects_to_dispatch.push(effects);
                }
            }
            wakes.merge(task_wakes);
        }
        for effects in spawn_effects_to_dispatch {
            effects.dispatch();
        }
        wakes.dispatch();
    }

    fn drain_deferred_cancel_dispatches(&mut self) {
        let batches = self.state.take_deferred_cancel_dispatches();
        if batches.is_empty() {
            return;
        }
        let mut wakes = Vec::with_capacity(batches.len());
        {
            let mut scheduler = self.scheduler.lock();
            for batch in batches {
                let (tasks, batch_wakes) = batch.into_parts();
                for (task_id, priority) in tasks {
                    scheduler.schedule_cancel(task_id, priority);
                }
                wakes.push(batch_wakes);
            }
        }
        for batch_wakes in wakes {
            batch_wakes.dispatch();
        }
    }

    /// Executes a single step.
    #[allow(clippy::too_many_lines)]
    fn step(&mut self) {
        self.step_inner(LabDispatchMode::Normal)
            .expect("normal lab scheduling cannot produce a forced-schedule error");
    }

    fn step_with_forced_dispatch(
        &mut self,
        expected: Option<(usize, &ForcedDispatch)>,
    ) -> Result<bool, ForcedScheduleError> {
        self.step_inner(LabDispatchMode::Forced { expected })
    }

    fn step_with_candidate_dispatch(
        &mut self,
        expected: Option<(usize, &ForcedDispatch)>,
    ) -> Result<bool, ForcedScheduleError> {
        self.step_inner(LabDispatchMode::Candidate { expected })
    }

    #[allow(clippy::too_many_lines)]
    fn step_inner(
        &mut self,
        dispatch_mode: LabDispatchMode<'_>,
    ) -> Result<bool, ForcedScheduleError> {
        self.steps += 1;
        self.drain_deferred_cancel_dispatches();
        self.drain_spawn_admissions();
        // Admission publication can invoke a retained cancellation Waker.
        // Consume any command it enqueued before selecting runnable work.
        self.drain_handle_cancel_requests();
        self.drain_deferred_cancel_dispatches();
        if !self.spawn_mailbox.handle_cancels_are_empty()
            || self.state.has_deferred_cancel_dispatches()
        {
            // Bound each deterministic step: reentrant cancellation gets the
            // next step, and ordinary ready work cannot overtake it.
            return Ok(false);
        }
        let rng_value = self.rng.next_u64();
        if self.steps < 50 {
            crate::tracing_compat::trace!(
                "lab runtime rng sample: rng_value={}, worker_hint={}",
                rng_value,
                (rng_value >> 32) as usize % self.config.worker_count.max(1)
            );
        }
        self.replay_recorder.record_rng_value(rng_value);
        self.check_futurelocks();
        if let Some(timer) = self.state.timer_driver_handle() {
            let _ = timer.process_timers();
        }
        self.poll_io();
        self.schedule_async_finalizers();

        // 1. Choose a worker and pop a task (deterministic multi-worker model)
        let worker_count = self.config.worker_count.max(1);
        // Use higher bits of rng_value since xorshift64 has poor low-bit entropy
        let worker_hint = ((rng_value >> 32) as usize) % worker_count;
        let now = self.now();
        let (task_id, dispatch_lane, dispatch_worker) = {
            let mut sched = self.scheduler.lock();
            match dispatch_mode {
                LabDispatchMode::Normal => {
                    if let Some((tid, lane)) = sched.pop_for_worker(worker_hint, rng_value, now) {
                        (tid, lane, worker_hint)
                    } else if let Some(tid) =
                        sched.steal_for_worker(worker_hint, rng_value.rotate_left(17))
                    {
                        (tid, DispatchLane::Stolen, worker_hint)
                    } else {
                        drop(sched);
                        self.check_deadline_monitor();
                        return Ok(false);
                    }
                }
                LabDispatchMode::Forced {
                    expected: Some((index, dispatch)),
                } => {
                    if self.steps < dispatch.at_step {
                        if sched.has_runnable_work(now) {
                            return Err(ForcedScheduleError::EarlyRunnable {
                                expected: dispatch.at_step,
                                actual: self.steps,
                            });
                        }
                        drop(sched);
                        self.check_deadline_monitor();
                        return Ok(false);
                    }
                    if self.steps > dispatch.at_step {
                        return Err(ForcedScheduleError::StepMismatch {
                            index,
                            expected: dispatch.at_step,
                            actual: self.steps,
                        });
                    }
                    if now.as_nanos() != dispatch.at_nanos {
                        return Err(ForcedScheduleError::TimeMismatch {
                            index,
                            expected: dispatch.at_nanos,
                            actual: now.as_nanos(),
                        });
                    }
                    let task_id = compact_task_id(dispatch.task);
                    sched.take_forced(
                        task_id,
                        dispatch.worker as usize,
                        dispatch.lane,
                        now,
                        index,
                    )?;
                    (task_id, dispatch.lane, dispatch.worker as usize)
                }
                LabDispatchMode::Forced { expected: None } => {
                    if !sched.is_empty() {
                        return Err(ForcedScheduleError::ScheduleExhausted {
                            consumed: self.certificate.decisions() as usize,
                        });
                    }
                    drop(sched);
                    self.check_deadline_monitor();
                    return Ok(false);
                }
                LabDispatchMode::Candidate {
                    expected: Some((index, dispatch)),
                } => {
                    let task_id = compact_task_id(dispatch.task);
                    sched.take_forced(
                        task_id,
                        dispatch.worker as usize,
                        dispatch.lane,
                        now,
                        index,
                    )?;
                    (task_id, dispatch.lane, dispatch.worker as usize)
                }
                LabDispatchMode::Candidate { expected: None } => {
                    drop(sched);
                    self.check_deadline_monitor();
                    return Ok(false);
                }
            }
        };

        self.dispatches = self.dispatches.saturating_add(1);

        // Record task scheduling in certificate and replay recorder
        self.certificate.record(task_id, dispatch_lane, self.steps);
        self.replay_recorder
            .record_task_scheduled(task_id, self.steps);
        if let Some(recorder) = &mut self.forced_schedule_recorder {
            if recorder.dispatches.len() < recorder.max_dispatches {
                recorder.dispatches.push(ForcedDispatch {
                    task: task_id.into(),
                    worker: u32::try_from(dispatch_worker)
                        .expect("lab worker index is bounded by LabConfig::worker_count"),
                    lane: dispatch_lane,
                    at_step: self.steps,
                    at_nanos: now.as_nanos(),
                });
            } else {
                recorder.truncated = true;
            }
        }

        // 2. Pre-poll chaos injection
        if self.inject_pre_poll_chaos(task_id) {
            // Chaos caused the task to be skipped (e.g., cancelled, budget exhausted)
            return Ok(true);
        }

        // 3. Prepare context, enforce budget, and take any cached wakers.
        let (priority, cached_waker, cached_cancel_waker, current_cx, cx_inner) = self
            .state
            .update_task(task_id, |record| {
                let priority = record.cx_inner.as_ref().map_or(0, |inner| {
                    let mut guard = inner.write();

                    // Enforce poll quota
                    if guard.budget.consume_poll().is_none() {
                        guard.set_cancel_requested(true);
                        if let Some(existing) = &mut guard.cancel_reason {
                            existing.strengthen(&crate::types::CancelReason::poll_quota());
                        } else {
                            guard.cancel_reason = Some(crate::types::CancelReason::poll_quota());
                        }
                    }

                    guard.budget.priority
                });

                (
                    priority,
                    record.cached_waker.take(),
                    record.cached_cancel_waker.take(),
                    record.cx.clone(),
                    record.cx_inner.clone(),
                )
            })
            .unwrap_or((0, None, None, None, None));

        let waker = match cached_waker {
            Some((waker, cached_priority)) if cached_priority == priority => waker,
            _ => Waker::from(Arc::new(TaskWaker {
                task_id,
                priority,
                scheduler: self.scheduler.clone(),
            })),
        };
        let mut cx = Context::from_waker(&waker);

        // Set cancel_waker so abort_with_reason can reschedule cancelled tasks.
        let cancel_waker_for_cache = cx_inner.as_ref().map(|_| match cached_cancel_waker {
            Some((waker, cached_priority)) if cached_priority == priority => (waker, priority),
            _ => (
                Waker::from(Arc::new(CancelTaskWaker {
                    task_id,
                    priority,
                    scheduler: self.scheduler.clone(),
                })),
                priority,
            ),
        });

        if let (Some(inner), Some((cancel_waker, _))) =
            (cx_inner.as_ref(), cancel_waker_for_cache.as_ref())
        {
            // Prepare and retire Wakers without a live CxInner guard: custom
            // callbacks may reenter the same task context.
            let mut incoming_waker = Some(Arc::new(crate::types::task_context::CancelWaker::new(
                cancel_waker.clone(),
            )));
            let retired_waker = {
                let mut guard = inner.write();
                if guard.cancel_waker_registry_closed {
                    None
                } else if !guard
                    .cancel_waker
                    .as_ref()
                    .is_some_and(|registered| registered.will_wake(cancel_waker))
                {
                    std::mem::replace(&mut guard.cancel_waker, incoming_waker.take())
                } else {
                    None
                }
            };
            drop(retired_waker);
            drop(incoming_waker);
        }

        let _cx_guard = crate::cx::Cx::set_current(current_cx);

        let started_running = self
            .state
            .update_task(task_id, |record| {
                let old_state = record.state.clone();
                if record.start_running() {
                    Some((old_state, record.state.clone()))
                } else {
                    None
                }
            })
            .flatten();

        if let Some((from_state, to_state)) = started_running.as_ref() {
            if self.config.has_cancellation_oracle() {
                self.notify_cancellation_oracle_task_transition(task_id, from_state, to_state);
            }
        }

        // 4. Poll the task
        if self.steps < 50 {
            crate::tracing_compat::trace!(
                "lab runtime executing task {:?} at step {}",
                task_id,
                self.steps
            );
        }

        // Notify oracle of task poll
        if self.config.has_cancellation_oracle() {
            self.notify_cancellation_oracle_task_poll(task_id);
        }

        let result = if let Some(stored) = self.state.get_stored_future(task_id) {
            stored.poll(&mut cx)
        } else {
            // Task lost (should not happen if consistent)
            return Ok(true);
        };

        // Record the poll so futurelock detection uses the correct idle step count.
        let _ = self.state.update_task(task_id, |record| {
            record.mark_polled(self.steps);
        });

        let (cancel_ack, cancel_wakes) = self.consume_cancel_ack(task_id).into_parts();

        // A checkpoint can win the race with the runtime-owned handle command.
        // Replay the logical RequestCancel -> acknowledgement ordering into the
        // oracle even though both TaskRecord mutations are already complete.
        if let Some(receipt) = cancel_ack.as_ref()
            && self.config.has_cancellation_oracle()
        {
            self.notify_cancellation_oracle_cancel_request(
                task_id,
                receipt.effective_reason.clone(),
            );
            if let Some((from_state, to_state)) = receipt.request_transition.as_ref() {
                self.notify_cancellation_oracle_task_transition(task_id, from_state, to_state);
            }
            if let Some((from_state, to_state)) = receipt.acknowledge_transition.as_ref() {
                self.notify_cancellation_oracle_task_transition(task_id, from_state, to_state);
            }
            self.notify_cancellation_oracle_cancel_ack(task_id);
        }
        let cancel_priority = cancel_ack.as_ref().map(|receipt| receipt.cleanup_priority);
        let cancel_ack = cancel_ack.is_some();

        // 5. Handle result
        match result {
            Poll::Ready(outcome) => {
                // Task completed
                self.state.remove_stored_future(task_id);
                self.scheduler.lock().forget_task(task_id);

                // Update state to Completed if not already terminal
                let mut oracle_transitions = Vec::new(); // Collect transitions for later oracle notification

                let _ = self.state.update_task(task_id, |record| {
                    if !record.state.is_terminal() {
                        let old_state = record.state.clone();
                        let record_outcome = match outcome {
                            crate::types::Outcome::Ok(()) => crate::types::Outcome::Ok(()),
                            crate::types::Outcome::Err(()) => crate::types::Outcome::Err(
                                crate::error::Error::new(crate::error::ErrorKind::Internal),
                            ),
                            crate::types::Outcome::Cancelled(r) => {
                                crate::types::Outcome::Cancelled(r)
                            }
                            crate::types::Outcome::Panicked(p) => {
                                crate::types::Outcome::Panicked(p)
                            }
                        };
                        let completed_via_cancel =
                            if matches!(record_outcome, crate::types::Outcome::Ok(())) {
                                let should_cancel = matches!(
                                    record.state,
                                    TaskState::Cancelling { .. } | TaskState::Finalizing { .. }
                                ) || (cancel_ack
                                    && matches!(record.state, TaskState::CancelRequested { .. }));
                                if should_cancel {
                                    if matches!(record.state, TaskState::CancelRequested { .. }) {
                                        let state_before = record.state.clone();
                                        let _ = record.acknowledge_cancel();
                                        oracle_transitions
                                            .push((state_before, record.state.clone()));
                                    }
                                    if matches!(record.state, TaskState::Cancelling { .. }) {
                                        let state_before = record.state.clone();
                                        record.cleanup_done();
                                        oracle_transitions
                                            .push((state_before, record.state.clone()));
                                    }
                                    if matches!(record.state, TaskState::Finalizing { .. }) {
                                        let state_before = record.state.clone();
                                        record.finalize_done();
                                        oracle_transitions
                                            .push((state_before, record.state.clone()));
                                    }
                                    matches!(
                                        record.state,
                                        TaskState::Completed(crate::types::Outcome::Cancelled(_))
                                    )
                                } else {
                                    false
                                }
                            } else {
                                false
                            };
                        if !completed_via_cancel {
                            record.complete(record_outcome);
                            oracle_transitions.push((old_state, record.state.clone()));
                        }
                    }
                });

                // Notify oracle of all state transitions after all mutations are complete
                if self.config.has_cancellation_oracle() {
                    for (from_state, to_state) in oracle_transitions {
                        self.notify_cancellation_oracle_task_transition(
                            task_id,
                            &from_state,
                            &to_state,
                        );
                    }
                }

                // Record task completion with severity from the finalized task
                // record. Must happen AFTER state finalization above because
                // create_task wraps user futures to always return Outcome::Ok(())
                // — the real severity comes from the cancel protocol state machine.
                let final_severity =
                    self.state
                        .task(task_id)
                        .map_or(crate::types::Severity::Ok, |record| match &record.state {
                            TaskState::Completed(outcome) => outcome.severity(),
                            _ => crate::types::Severity::Ok,
                        });
                self.replay_recorder
                    .record_task_completed(task_id, final_severity);

                if let Some(monitor) = &mut self.deadline_monitor {
                    if let Some(record) = self.state.task(task_id) {
                        let now = self.state.now;
                        let duration =
                            Duration::from_nanos(now.duration_since(record.created_at()));
                        let (task_type, deadline) = record
                            .cx_inner
                            .as_ref()
                            .map(|inner| inner.read())
                            .map_or_else(
                                || ("default".to_string(), None),
                                |inner| {
                                    (
                                        inner
                                            .task_type
                                            .clone()
                                            .unwrap_or_else(|| "default".to_string()),
                                        inner.budget.deadline,
                                    )
                                },
                            );
                        monitor.record_completion(task_id, &task_type, duration, deadline, now);
                    }
                }

                // Notify waiters
                let (waiters, completion_observer) =
                    self.state.task_completed(task_id).into_parts();

                // br-asupersync-iwqn3q: hoist priority lookup OUT of
                // the scheduler-locked scope. cx_inner is an
                // E(Config)-tier RwLock; the scheduler is an A(Tasks)
                // mutex. The project's lock ordering requires
                // E → D → B → A → C, so cx_inner.read() must precede
                // scheduler.lock(). Acquiring them in the loop
                // body inverted the order and could deadlock against
                // any thread holding cx_inner.write() while waiting
                // for the scheduler. Snapshot the (waiter, priority)
                // tuples first, THEN acquire the scheduler.
                //
                // The sibling pattern at schedule_for_cancel
                // (line ~2002) already gets this right; this site
                // was the asymmetric outlier.
                let scheduled: Vec<(TaskId, u8)> = waiters
                    .into_iter()
                    .map(|w| {
                        let prio = self
                            .state
                            .task(w)
                            .and_then(|t| t.cx_inner.as_ref())
                            .map_or(0, |inner| inner.read().budget.priority);
                        (w, prio)
                    })
                    .collect();
                let mut sched = self.scheduler.lock();
                for (waiter, prio) in scheduled {
                    sched.schedule(waiter, prio);
                }
                drop(sched);
                completion_observer.dispatch();
                cancel_wakes.dispatch();
            }
            Poll::Pending => {
                // Task yielded. Waker will reschedule it when ready.
                // Note: If the task yielded via `cx.waker().wake_by_ref()`, it might already be scheduled.
                // If it yielded for I/O or other events, it won't be scheduled until that event fires.

                // Record task yielding
                self.replay_recorder.record_task_yielded(task_id);
                let _ = self.state.update_task(task_id, |record| {
                    record.cached_waker = Some((waker, priority));
                    record.cached_cancel_waker = cancel_waker_for_cache;
                });

                if let Some(cancel_priority) = cancel_priority {
                    // The queued handle command may now coalesce against the
                    // reconciled TaskRecord, so this poll owns the replacement
                    // cancel-lane publication before any auxiliary Waker runs.
                    self.scheduler
                        .lock()
                        .schedule_cancel(task_id, cancel_priority);
                }
                cancel_wakes.dispatch();

                // 6. Post-poll chaos injection (spurious wakeups for pending tasks)
                self.inject_post_poll_chaos(task_id, priority);
            }
        }

        self.check_deadline_monitor();
        Ok(true)
    }

    fn check_deadline_monitor(&mut self) {
        if let Some(monitor) = &mut self.deadline_monitor {
            let now = self.state.now;
            monitor.check(now, self.state.tasks_iter().map(|(_, record)| record));
        }
    }

    fn poll_io(&mut self) {
        let Some(handle) = self.state.io_driver_handle() else {
            return;
        };
        let now = self.state.now;
        let (state, recorder, seen) = (
            &mut self.state,
            &mut self.replay_recorder,
            &mut self.seen_io_tokens,
        );
        if let Err(error) = handle.turn_with(Some(Duration::ZERO), |event, interest| {
            let token = event.token.0;
            let interest = interest.unwrap_or(event.ready);
            if seen.insert(token) {
                state.record_trace_event(|seq| {
                    TraceEvent::io_requested(seq, now, token as u64, interest.bits())
                });
            }
            state.record_trace_event(|seq| {
                TraceEvent::io_ready(seq, now, token as u64, event.ready.bits())
            });
            recorder.record_io_ready(
                token as u64,
                event.is_readable(),
                event.is_writable(),
                event.is_error(),
                event.is_hangup(),
            );
        }) {
            let _ = &error;
            crate::tracing_compat::warn!(
                error = ?error,
                "lab runtime io_driver poll failed"
            );
        }
        self.sync_reactor_chaos_stats();
    }

    /// Injects chaos before polling a task.
    ///
    /// Returns `true` if the task should be skipped (e.g., cancelled or budget exhausted).
    fn inject_pre_poll_chaos(&mut self, task_id: TaskId) -> bool {
        let Some(chaos_config) = self.config.chaos.clone() else {
            return false;
        };
        let Some(chaos_rng) = &mut self.chaos_rng else {
            return false;
        };

        let cancel = chaos_rng.should_inject_cancel(&chaos_config);

        // Check for delay injection
        let delay = chaos_rng
            .should_inject_delay(&chaos_config)
            .then(|| chaos_rng.next_delay(&chaos_config));

        // Check for budget exhaustion injection
        let budget_exhaust = chaos_rng.should_inject_budget_exhaust(&chaos_config);
        let skip_poll = cancel | budget_exhaust;
        self.chaos_stats
            .record_pre_poll_outcomes(cancel, delay, budget_exhaust);

        // Now apply the injections (no more borrowing chaos_rng).
        // Cancel and budget_exhaust are independent — apply both when both fire.
        let cancel_wakes = cancel.then(|| self.inject_cancel(task_id));
        if cancel {
            // Publish the cancelled task before any virtual-time advancement
            // or deferred cancellation callback can reenter the lab runtime.
            self.reschedule_after_chaos_skip(task_id);
        }

        if let Some(d) = delay {
            self.advance_time(Self::duration_nanos_saturating(d));
        }

        if budget_exhaust {
            self.inject_budget_exhaust(task_id);
        }

        if skip_poll && !cancel {
            self.reschedule_after_chaos_skip(task_id);
        }
        if let Some(cancel_wakes) = cancel_wakes {
            cancel_wakes.dispatch();
        }

        skip_poll
    }

    #[inline]
    fn duration_nanos_saturating(duration: Duration) -> u64 {
        u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
    }

    /// Injects chaos after polling a task that returned Pending.
    fn inject_post_poll_chaos(&mut self, task_id: TaskId, priority: u8) {
        let Some(chaos_config) = self.config.chaos.clone() else {
            return;
        };
        let Some(chaos_rng) = &mut self.chaos_rng else {
            return;
        };

        // br-asupersync-4so3w3: gate wakeup_storm injection on at-least-
        // one-open-region. After every region has closed, the lab is in
        // a quiescence state that production reaches via region drop;
        // injecting a spurious wakeup at that point would synthesize a
        // schedule that production cannot reproduce, defeating the
        // whole point of chaos-driven trace minimisation.
        let has_open_region = self.state.live_region_count() > 0;
        let wakeup_count = if chaos_rng.should_inject_wakeup_storm(&chaos_config, has_open_region) {
            Some(chaos_rng.next_wakeup_count(&chaos_config))
        } else {
            None
        };

        // br-asupersync-7uu7sa: even when SOME region is open, this
        // specific task may belong to a region that has already
        // transitioned to Closing/Draining/Finalizing/Closed during a different
        // chaos action in the same step. Re-polling such a task
        // violates the structured-concurrency contract the oracles
        // assume — it produces a 'cancel-aware future re-polled after
        // region close' code path that production never executes.
        // Filter post-decision so chaos budget accounting stays in
        // sync with the global gate decision.
        let target_region_open = self
            .state
            .task(task_id)
            .map(|t| t.owner)
            .and_then(|owner| self.state.region(owner))
            .is_some_and(|region| region.state().can_accept_work());

        // Apply the injection (no more borrowing chaos_rng)
        if let Some(count) = wakeup_count
            && target_region_open
        {
            self.chaos_stats.record_wakeup_storm(count as u64);
            self.inject_spurious_wakes(task_id, priority, count);
        } else {
            self.chaos_stats.record_no_injection();
        }
    }

    fn sync_reactor_chaos_stats(&mut self) {
        let current = self.lab_reactor.chaos_stats();
        let previous = &self.seen_reactor_chaos_stats;
        let delta = ChaosStats {
            cancellations: current.cancellations.saturating_sub(previous.cancellations),
            delays: current.delays.saturating_sub(previous.delays),
            total_delay: current.total_delay.saturating_sub(previous.total_delay),
            io_errors: current.io_errors.saturating_sub(previous.io_errors),
            wakeup_storms: current.wakeup_storms.saturating_sub(previous.wakeup_storms),
            spurious_wakeups: current
                .spurious_wakeups
                .saturating_sub(previous.spurious_wakeups),
            budget_exhaustions: current
                .budget_exhaustions
                .saturating_sub(previous.budget_exhaustions),
            decision_points: current
                .decision_points
                .saturating_sub(previous.decision_points),
        };
        self.chaos_stats.merge(&delta);
        self.seen_reactor_chaos_stats = current;
    }

    fn reschedule_after_chaos_skip(&self, task_id: TaskId) {
        let Some(record) = self.state.task(task_id) else {
            return;
        };
        if record.state.is_terminal() {
            return;
        }
        let priority = record
            .cx_inner
            .as_ref()
            .map_or(0, |inner| inner.read().budget.priority);
        let mut sched = self.scheduler.lock();
        sched.schedule_cancel(task_id, priority);
    }

    fn schedule_async_finalizers(&mut self) {
        let tasks = self.state.drain_ready_async_finalizers();
        if tasks.is_empty() {
            return;
        }
        let mut sched = self.scheduler.lock();
        let mut spawn_effects = Vec::with_capacity(tasks.len());
        for (task_id, priority, effects) in tasks {
            sched.schedule(task_id, priority);
            spawn_effects.push(effects);
        }
        drop(sched);
        for effects in spawn_effects {
            effects.dispatch();
        }
    }

    fn consume_cancel_ack(
        &mut self,
        task_id: TaskId,
    ) -> crate::types::task_context::CancellationEffects<
        Option<crate::record::task::CheckpointCancelAck>,
    > {
        self.state.consume_task_checkpoint_cancel_ack(task_id)
    }

    /// Injects a cancellation for a task.
    fn inject_cancel(&mut self, task_id: TaskId) -> crate::types::task_context::CancelWakeEffects {
        use crate::types::{Budget, CancelReason};

        // Record replay event
        self.replay_recorder.record_cancel_injection(task_id);

        let reason = CancelReason::user("chaos-injected");
        // Mark the task as cancel-requested with the chaos reason, preserving
        // any stronger cancellation that already won for this task.
        let transition = self
            .state
            .update_task(task_id, |record| {
                if !record.state.is_terminal() {
                    let old_state = record.state.clone();
                    let effects = record.request_cancel_with_budget(reason.clone(), Budget::ZERO);
                    let (_, cancel_wakes) = effects.into_parts();
                    let effective_reason = record
                        .cancel_reason()
                        .cloned()
                        .unwrap_or_else(|| reason.clone());
                    Some((
                        old_state,
                        record.state.clone(),
                        effective_reason,
                        cancel_wakes,
                    ))
                } else {
                    None
                }
            })
            .flatten();

        // Publish the authoritative post-strengthening reason to the oracle
        // after mutation, then record the corresponding state transition.
        let cancel_wakes =
            if let Some((old_state, new_state, effective_reason, cancel_wakes)) = transition {
                if self.config.has_cancellation_oracle() {
                    self.oracles.cancellation_protocol.on_cancel_request(
                        task_id,
                        effective_reason,
                        self.virtual_time,
                    );
                    self.oracles.cancellation_protocol.on_transition(
                        task_id,
                        &old_state,
                        &new_state,
                        self.virtual_time,
                    );
                }
                cancel_wakes
            } else {
                crate::types::task_context::CancelWakeEffects::empty()
            };

        // Emit trace event
        self.state.record_trace_event(|seq| {
            TraceEvent::new(
                seq,
                self.virtual_time,
                TraceEventKind::ChaosInjection,
                TraceData::Chaos {
                    kind: "cancel".to_string(),
                    task: Some(task_id),
                    detail: "chaos-injected cancellation".to_string(),
                },
            )
        });
        cancel_wakes
    }

    /// Notifies the cancellation protocol oracle about runtime events.
    pub fn notify_cancellation_oracle_task_create(&mut self, task_id: TaskId, region_id: RegionId) {
        self.oracles
            .cancellation_protocol
            .on_task_create(task_id, region_id);
    }

    /// Notifies the cancellation protocol oracle about region creation.
    pub fn notify_cancellation_oracle_region_create(
        &mut self,
        region_id: RegionId,
        parent: Option<RegionId>,
    ) {
        self.oracles
            .cancellation_protocol
            .on_region_create(region_id, parent);
    }

    /// Notifies the cancellation protocol oracle about task state transitions.
    pub fn notify_cancellation_oracle_task_transition(
        &mut self,
        task_id: TaskId,
        from: &crate::record::task::TaskState,
        to: &crate::record::task::TaskState,
    ) {
        self.oracles
            .cancellation_protocol
            .on_transition(task_id, from, to, self.virtual_time);
    }

    /// Notifies the cancellation protocol oracle about cancel requests.
    pub fn notify_cancellation_oracle_cancel_request(
        &mut self,
        task_id: TaskId,
        reason: crate::types::CancelReason,
    ) {
        self.oracles
            .cancellation_protocol
            .on_cancel_request(task_id, reason, self.virtual_time);
    }

    /// Notifies the cancellation protocol oracle about cancel acknowledgments.
    pub fn notify_cancellation_oracle_cancel_ack(&mut self, task_id: TaskId) {
        self.oracles
            .cancellation_protocol
            .on_cancel_ack(task_id, self.virtual_time);
    }

    /// Notifies the cancellation protocol oracle about task polling.
    pub fn notify_cancellation_oracle_task_poll(&mut self, task_id: TaskId) {
        self.oracles.cancellation_protocol.on_task_poll(task_id);
    }

    /// Notifies the cancellation protocol oracle about mask entry.
    pub fn notify_cancellation_oracle_mask_enter(&mut self, task_id: TaskId) {
        self.oracles
            .cancellation_protocol
            .on_mask_enter(task_id, self.virtual_time);
    }

    /// Notifies the cancellation protocol oracle about mask exit.
    pub fn notify_cancellation_oracle_mask_exit(&mut self, task_id: TaskId) {
        self.oracles
            .cancellation_protocol
            .on_mask_exit(task_id, self.virtual_time);
    }

    /// Notifies the cancellation protocol oracle about region cancellation.
    pub fn notify_cancellation_oracle_region_cancel(
        &mut self,
        region_id: RegionId,
        reason: crate::types::CancelReason,
    ) {
        self.oracles
            .cancellation_protocol
            .on_region_cancel(region_id, reason, self.virtual_time);
    }

    /// Checks the cancellation protocol oracle for violations and optionally enforces them.
    pub fn check_cancellation_protocol(
        &mut self,
    ) -> Result<(), crate::lab::oracle::CancellationProtocolViolation> {
        if !self.config.has_cancellation_oracle() {
            return Ok(());
        }

        let result = self.oracles.cancellation_protocol.check();

        if let Err(ref violation) = result {
            if self.config.panic_on_cancellation_violation {
                // Configurable enforcement: panic in enforce mode
                panic!("Cancellation protocol violation detected: {violation}");
            } else {
                // Warn mode: log the violation
                crate::tracing_compat::warn!(
                    violation = %violation,
                    "Cancellation protocol violation detected"
                );
            }
        }

        result
    }

    /// Injects budget exhaustion for a task.
    fn inject_budget_exhaust(&mut self, task_id: TaskId) {
        // Record replay event
        self.replay_recorder
            .record_budget_exhaust_injection(task_id);

        // Set the task's budget quotas to zero
        if let Some(record) = self.state.task(task_id) {
            if let Some(cx_inner) = &record.cx_inner {
                let mut inner = cx_inner.write();
                inner.budget.poll_quota = 0;
                inner.budget.cost_quota = Some(0);
            }
        }

        // Emit trace event
        self.state.record_trace_event(|seq| {
            TraceEvent::new(
                seq,
                self.virtual_time,
                TraceEventKind::ChaosInjection,
                TraceData::Chaos {
                    kind: "budget_exhaust".to_string(),
                    task: Some(task_id),
                    detail: "chaos-injected budget exhaustion".to_string(),
                },
            )
        });
    }

    /// Injects spurious wakeups for a task.
    fn inject_spurious_wakes(&mut self, task_id: TaskId, priority: u8, count: usize) {
        // br-asupersync-7uu7sa: defense-in-depth — even when the chaos
        // call site (inject_post_poll_chaos) gates correctly, future
        // callers may invoke this method directly. Refuse to wake a
        // task whose owning region is no longer accepting normal work
        // (Closing / Draining / Finalizing / Closed). This silently no-ops rather
        // than panicking so chaos campaigns with TaskId selection that
        // races region close don't artificially abort.
        let owner_open = self
            .state
            .task(task_id)
            .map(|t| t.owner)
            .and_then(|owner| self.state.region(owner))
            .is_some_and(|region| region.state().can_accept_work());
        if !owner_open {
            return;
        }

        // Record replay event
        self.replay_recorder
            .record_wakeup_storm_injection(task_id, u32::try_from(count).unwrap_or(u32::MAX));

        // Schedule the task multiple times (spurious wakeups)
        let mut sched = self.scheduler.lock();
        sched.inject_spurious_wakes(task_id, priority, count);
        drop(sched);

        // Emit trace event
        self.state.record_trace_event(|seq| {
            TraceEvent::new(
                seq,
                self.virtual_time,
                TraceEventKind::ChaosInjection,
                TraceData::Chaos {
                    kind: "wakeup_storm".to_string(),
                    task: Some(task_id),
                    detail: format!("chaos-injected {count} spurious wakeups"),
                },
            )
        });
    }

    /// Public wrapper for `step()` for use in tests.
    ///
    /// This is useful for testing determinism across multiple step executions.
    pub fn step_for_test(&mut self) {
        self.step();
    }

    /// Checks invariants and returns any violations.
    #[must_use]
    pub fn check_invariants(&mut self) -> Vec<InvariantViolation> {
        let mut violations = Vec::new();

        // Check cancellation protocol oracle
        if let Err(violation) = self.check_cancellation_protocol() {
            violations.push(InvariantViolation::CancellationProtocol {
                violation: violation.to_string(),
            });
        }

        // Check for obligation leaks
        let leaks = self.obligation_leaks();
        if !leaks.is_empty() {
            for leak in &leaks {
                let _ = self.state.mark_obligation_leaked(leak.obligation);
            }
            violations.push(InvariantViolation::ObligationLeak { leaks });
        }

        violations.extend(self.futurelock_violations());
        violations.extend(self.quiescence_violations());

        // Check for task leaks (non-terminal tasks)
        let task_leak_count = self.task_leaks();
        if task_leak_count > 0 {
            violations.push(InvariantViolation::TaskLeak {
                count: task_leak_count,
            });
        }

        violations
    }

    fn obligation_leaks(&self) -> Vec<ObligationLeak> {
        let mut leaks = Vec::new();

        for (_, obligation) in self.state.obligations_iter() {
            if !obligation.is_pending() {
                continue;
            }

            let holder_terminal = self
                .state
                .task(obligation.holder)
                .is_none_or(|t| t.state.is_terminal());
            let region_closed = self
                .state
                .region(obligation.region)
                .is_none_or(|r| r.state().is_terminal());

            if holder_terminal || region_closed {
                leaks.push(ObligationLeak {
                    obligation: obligation.id,
                    kind: obligation.kind,
                    holder: obligation.holder,
                    region: obligation.region,
                });
            }
        }

        leaks
    }

    fn task_leaks(&self) -> usize {
        self.state
            .tasks_iter()
            .filter(|(_, t)| !t.state.is_terminal())
            .count()
    }

    fn quiescence_violations(&self) -> Vec<InvariantViolation> {
        let mut violations = Vec::new();
        for (_, region) in self.state.regions_iter() {
            if region.state().is_terminal() {
                // Check if any children or tasks are NOT terminal
                let live_tasks = region
                    .task_ids()
                    .iter()
                    .any(|&tid| self.state.task(tid).is_some_and(|t| !t.state.is_terminal()));

                let live_children = region.child_ids().iter().any(|&rid| {
                    self.state
                        .region(rid)
                        .is_some_and(|r| !r.state().is_terminal())
                });

                if live_tasks || live_children {
                    violations.push(InvariantViolation::QuiescenceViolation);
                }
            }
        }
        violations
    }

    fn futurelock_violations(&self) -> Vec<InvariantViolation> {
        let threshold = self.config.futurelock_max_idle_steps;
        if threshold == 0 {
            return Vec::new();
        }

        let current_step = self.steps;
        let mut violations = Vec::new();

        for (_, task) in self.state.tasks_iter() {
            if task.state.is_terminal() {
                continue;
            }

            let mut held = Vec::new();
            for (_, obligation) in self.state.obligations_iter() {
                if obligation.is_pending() && obligation.holder == task.id {
                    held.push(obligation.id);
                }
            }

            if held.is_empty() {
                continue;
            }

            let idle_steps = current_step.saturating_sub(task.last_polled_step);
            if idle_steps > threshold {
                violations.push(InvariantViolation::Futurelock {
                    task: task.id,
                    region: task.owner,
                    idle_steps,
                    held,
                    last_checkpoint_message: self.futurelock_checkpoint_message(task.id),
                });
            }
        }

        violations
    }

    fn futurelock_checkpoint_message(&self, task_id: TaskId) -> Option<String> {
        self.state.task(task_id).and_then(|task| {
            task.cx
                .as_ref()
                .and_then(|cx| cx.checkpoint_state().last_message)
                .or_else(|| {
                    task.cx_inner
                        .as_ref()
                        .and_then(|inner| inner.read().materialised_checkpoint_state().last_message)
                })
        })
    }

    fn check_futurelocks(&self) {
        let violations = self.futurelock_violations();
        if violations.is_empty() {
            return;
        }

        for v in violations {
            let InvariantViolation::Futurelock {
                task,
                region,
                idle_steps,
                held,
                last_checkpoint_message,
            } = v
            else {
                continue;
            };

            let mut held_kinds = Vec::new();
            for oid in &held {
                for (_, obligation) in self.state.obligations_iter() {
                    if obligation.id == *oid {
                        held_kinds.push((obligation.id, obligation.kind));
                        break;
                    }
                }
            }

            self.state.record_trace_event(|seq| {
                TraceEvent::new(
                    seq,
                    self.virtual_time,
                    TraceEventKind::FuturelockDetected,
                    TraceData::Futurelock {
                        task,
                        region,
                        idle_steps,
                        held: held_kinds,
                    },
                )
            });

            assert!(
                !self.config.panic_on_futurelock,
                "[ASUP-E402] futurelock detected: seed={} {task} in {region} idle={idle_steps} held={held:?} last_checkpoint={}",
                self.config.seed,
                format_futurelock_checkpoint(last_checkpoint_message.as_deref())
            );
        }
    }
}

/// Run an async task under a fresh [`LabRuntime`] with the given seed.
///
/// This is the runtime half of the `#[lab_test]` macro. It creates a root
/// region, spawns one task under a current [`crate::cx::Cx`], drives the lab to
/// quiescence, and returns the task output together with the passing structured
/// [`LabRunReport`]. Any failed lab-test contract attempts to write an automatic
/// crashpack before panicking when auto-artifacts are enabled.
///
/// # Panics
///
/// Panics if the task cannot be spawned, does not finish after the lab run, is
/// cancelled, panics, fails an oracle or runtime invariant, or does not reach
/// quiescence. Test harness callers should treat those panics as deterministic
/// failures; a returned report always satisfies the lab-test success contract.
///
/// # Examples
///
/// ```rust
/// use asupersync::lab::run_async_under_lab;
///
/// let (value, report) = run_async_under_lab(7, |cx| async move {
///     assert_eq!(
///         cx.region_id(),
///         asupersync::cx::Cx::current().expect("current Cx").region_id()
///     );
///     42_u8
/// });
///
/// assert_eq!(value, 42);
/// assert!(report.quiescent);
/// assert!(report.oracle_report.all_passed());
/// assert!(report.invariant_violations.is_empty());
/// ```
#[must_use]
pub fn run_async_under_lab<F, Fut, T>(seed: u64, task: F) -> (T, LabRunReport)
where
    F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
    Fut: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    run_async_under_lab_with_config(LabConfig::new(seed), task)
}

/// Run an async task under a fresh [`LabRuntime`] using an explicit config.
///
/// This variant lets test macros and harnesses enable deterministic chaos or
/// tune step limits while preserving the same strict root-task execution and
/// automatic-crashpack contract as [`run_async_under_lab`].
///
/// # Panics
///
/// Panics under the same conditions as [`run_async_under_lab`].
#[must_use]
pub fn run_async_under_lab_with_config<F, Fut, T>(config: LabConfig, task: F) -> (T, LabRunReport)
where
    F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
    Fut: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    let test_name = std::thread::current()
        .name()
        .unwrap_or("run_async_under_lab")
        .to_owned();
    run_async_lab_test_with_config(config, &test_name, task)
}

/// Run an async `#[lab_test]` body under a fresh [`LabRuntime`].
///
/// This helper uses the same root-task model as [`run_async_under_lab_with_config`],
/// and adds lab-test failure handling: task failures, missing completion, oracle
/// failures, invariant violations, and non-quiescence all write an auto-crashpack
/// before panicking.
///
/// # Panics
///
/// Panics when the async body fails, does not finish, or when the final
/// [`LabRunReport`] violates the lab-test success contract.
///
/// Replay configuration overrides are applied from the environment before the
/// runtime is constructed. Generated test harnesses resolve the seed override
/// separately so seed-derived chaos configuration remains internally
/// consistent.
#[must_use]
pub fn run_async_lab_test_with_config<F, Fut, T>(
    config: LabConfig,
    test_name: &str,
    task: F,
) -> (T, LabRunReport)
where
    F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
    Fut: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    let config = lab_test_config_from_env(config);
    let seed = config.seed;
    let mut runtime = LabRuntime::new(config);
    let root = runtime
        .state
        .create_root_region(crate::types::Budget::INFINITE);
    let (task_id, mut handle, spawn_effects) = runtime
        .state
        .create_task_with_deferred_spawn_effects(root, crate::types::Budget::INFINITE, async move {
            let cx = crate::cx::Cx::current()
                .unwrap_or_else(|| panic!("lab task started without current Cx for seed {seed}"));
            task(cx).await
        })
        .unwrap_or_else(|error| panic!("failed to spawn lab task for seed {seed}: {error}"));
    runtime
        .scheduler
        .lock()
        .schedule(task_id, crate::types::Budget::INFINITE.priority);
    spawn_effects.dispatch();

    let report = runtime.run_until_quiescent_with_report();
    let output = match handle.try_join() {
        Ok(Some(output)) => output,
        Ok(None) => {
            let cause = format!(
                "lab task did not finish for seed {seed}: quiescent={}, steps_total={}",
                report.quiescent, report.steps_total
            );
            let artifact = runtime.write_auto_crashpack_for_task_failure(
                test_name,
                &report,
                task_id,
                root,
                FailureOutcome::Err,
                &cause,
            );
            panic!(
                "{}",
                lab_auto_failure_message(test_name, seed, &cause, artifact)
            );
        }
        Err(error) => {
            let cause = format!("lab task failed for seed {seed}: {error}");
            let outcome = failure_outcome_from_join_error(&error);
            let artifact = runtime.write_auto_crashpack_for_task_failure(
                test_name, &report, task_id, root, outcome, &cause,
            );
            panic!(
                "{}",
                lab_auto_failure_message(test_name, seed, &cause, artifact)
            );
        }
    };

    if !report.lab_test_passed() {
        let cause = lab_report_failure_summary(&report);
        let artifact = runtime.write_auto_crashpack_for_report(test_name, &report);
        panic!(
            "{}",
            lab_auto_failure_message(test_name, seed, &cause, artifact)
        );
    }

    (output, report)
}

fn failure_outcome_from_join_error(error: &crate::runtime::JoinError) -> FailureOutcome {
    match error {
        crate::runtime::JoinError::Cancelled(reason) => FailureOutcome::Cancelled {
            cancel_kind: reason.kind(),
        },
        crate::runtime::JoinError::Panicked(payload) => FailureOutcome::Panicked {
            message: payload.message().to_owned(),
        },
        crate::runtime::JoinError::PolledAfterCompletion => FailureOutcome::Err,
    }
}

/// Read the replay seed override consumed by generated lab-test harnesses.
///
/// # Panics
///
/// Panics when the variable is present but is not a valid `u64`.
#[doc(hidden)]
#[must_use]
pub fn lab_test_seed_override() -> Option<u64> {
    let value = lab_test_env_value(LAB_TEST_SEED_ENV)?;
    Some(value.parse::<u64>().unwrap_or_else(|error| {
        panic!("{LAB_TEST_SEED_ENV} must be a u64, got {value:?}: {error}")
    }))
}

/// Apply crashpack replay overrides to a lab-test configuration.
///
/// `ASUPERSYNC_MAX_STEPS=none` restores an unlimited step budget. Generated
/// harnesses resolve the seed before configuration construction; this helper
/// also updates seed-derived entropy and chaos seeds for direct callers while
/// preserving explicitly decoupled seeds.
///
/// # Panics
///
/// Panics when an override is present but malformed.
#[doc(hidden)]
#[must_use]
pub fn lab_test_config_from_env(mut config: LabConfig) -> LabConfig {
    if let Some(seed) = lab_test_seed_override() {
        let original_seed = config.seed;
        config.seed = seed;
        if config.entropy_seed == original_seed {
            config.entropy_seed = seed;
        }
        if let Some(chaos) = config.chaos.take() {
            config.chaos = Some(if chaos.seed == original_seed {
                chaos.with_seed(seed)
            } else {
                chaos
            });
        }
    }

    if let Some(value) = lab_test_env_value(LAB_TEST_WORKERS_ENV) {
        let workers = value.parse::<usize>().unwrap_or_else(|error| {
            panic!("{LAB_TEST_WORKERS_ENV} must be a positive integer, got {value:?}: {error}")
        });
        assert!(
            workers > 0,
            "{LAB_TEST_WORKERS_ENV} must be greater than zero"
        );
        config = config.worker_count(workers);
    }

    if let Some(value) = lab_test_env_value(LAB_TEST_MAX_STEPS_ENV) {
        config = if value == "none" {
            config.no_step_limit()
        } else {
            let steps = value.parse::<u64>().unwrap_or_else(|error| {
                panic!("{LAB_TEST_MAX_STEPS_ENV} must be a u64 or 'none', got {value:?}: {error}")
            });
            config.max_steps(steps)
        };
    }

    config
}

fn lab_test_env_value(name: &str) -> Option<String> {
    match std::env::var(name) {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(std::env::VarError::NotUnicode(_)) => {
            panic!("{name} must contain valid Unicode")
        }
    }
}

fn lab_auto_failure_message(
    test_name: &str,
    seed: u64,
    cause: &str,
    artifact: Result<Option<LabAutoCrashpack>, LabAutoCrashpackError>,
) -> String {
    let mut message = format!(
        "lab_test failed for {test_name} seed {seed}; rerun: \
         ASUPERSYNC_LAB_TEST_SEED={seed} cargo test {test_name} -- --exact --nocapture; \
         cause: {cause}"
    );
    match artifact {
        Ok(Some(artifact)) => {
            message.push_str(&format!(
                "\ncrashpack: {}\nreplay: {}",
                artifact.path, artifact.replay.command_line
            ));
        }
        Ok(None) => {}
        Err(error) => {
            message.push_str(&format!("\ncrashpack_error: {error}"));
        }
    }
    message
}

fn lab_report_failure_summary(report: &LabRunReport) -> String {
    format!(
        "quiescent={}; oracle_passed={}; invariant_violations={:?}; trace_fingerprint={}",
        report.quiescent,
        report.oracle_report.all_passed(),
        report.invariant_violations,
        report.trace_fingerprint
    )
}

fn auto_artifacts_enabled() -> bool {
    std::env::var(AUTO_ARTIFACTS_ENV).map_or(true, |value| value != "0")
}

fn compiled_commit_hash() -> Option<String> {
    option_env!("ASUPERSYNC_BUILD_GIT_COMMIT").map(str::to_owned)
}

fn auto_crashpack_dir(test_name: &str, pack: &CrashPack) -> PathBuf {
    let root = std::env::var_os(TEST_ARTIFACTS_DIR_ENV).map_or_else(
        || PathBuf::from("target").join("test-artifacts"),
        PathBuf::from,
    );
    root.join(sanitize_test_artifact_segment(test_name))
        .join(format!(
            "seed-{:016x}-trace-{:016x}",
            pack.seed(),
            pack.fingerprint()
        ))
}

fn sanitize_test_artifact_segment(test_name: &str) -> String {
    let mut sanitized = String::with_capacity(test_name.len());
    let mut last_was_separator = false;
    for ch in test_name.chars() {
        if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' {
            sanitized.push(ch);
            last_was_separator = false;
        } else if !last_was_separator {
            sanitized.push('_');
            last_was_separator = true;
        }
    }
    let sanitized = sanitized.trim_matches('_');
    if sanitized.is_empty() {
        "lab-test".to_string()
    } else {
        sanitized.to_string()
    }
}

const DEFAULT_LAB_CANCEL_STREAK_LIMIT: usize = 16;

#[derive(Debug, Clone, Copy)]
struct PendingSpuriousWake {
    priority: u8,
    remaining: usize,
}

#[derive(Debug)]
/// Deterministic lab scheduler with per-worker queues.
///
/// This is a single-threaded model of multi-worker scheduling used by the lab
/// runtime to simulate parallel execution deterministically.
pub struct LabScheduler {
    workers: Vec<crate::runtime::scheduler::PriorityScheduler>,
    scheduled: DetHashSet<TaskId>,
    pending_spurious_wakes: DetHashMap<TaskId, PendingSpuriousWake>,
    /// Task → worker assignment, indexed by arena slot.
    /// Task → worker assignment, indexed by arena slot and tagged with the
    /// generation the assignment was recorded for (GH#55). The generation tag
    /// keeps slot reuse from aliasing a live task's routing.
    assignments: Vec<Option<(u32, usize)>>,
    next_worker: usize,
    cancel_streak: Vec<usize>,
    cancel_streak_limit: usize,
}

impl LabScheduler {
    fn new(worker_count: usize, seed: u64) -> Self {
        let count = if worker_count == 0 { 1 } else { worker_count };
        let cancel_streak_limit = DEFAULT_LAB_CANCEL_STREAK_LIMIT.max(1);
        // GH#55: seed-derived hashing keeps `scheduled` iteration (and thus
        // every schedule-order decision that flows through it) identical for
        // identical lab seeds, regardless of the `test-internals` feature.
        let build_hasher = crate::util::det_hash::DetBuildHasher::with_seed(seed);
        Self {
            workers: (0..count)
                .map(|_| crate::runtime::scheduler::PriorityScheduler::new())
                .collect(),
            scheduled: DetHashSet::with_hasher(build_hasher.clone()),
            pending_spurious_wakes: DetHashMap::with_hasher(build_hasher),
            assignments: Vec::new(),
            next_worker: 0,
            cancel_streak: vec![0; count],
            cancel_streak_limit,
        }
    }

    /// Returns true if no tasks are currently scheduled.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.scheduled.is_empty()
    }

    fn has_runnable_work(&mut self, now: Time) -> bool {
        self.workers
            .iter_mut()
            .any(|worker| worker.has_runnable_work(now))
    }

    /// Returns the configured cancel streak limit for lab scheduling.
    #[must_use]
    pub fn cancel_streak_limit(&self) -> usize {
        self.cancel_streak_limit
    }

    #[inline]
    fn set_assignment(&mut self, task: TaskId, worker: usize) {
        let slot = task.arena_index().index() as usize;
        if slot >= self.assignments.len() {
            self.assignments.resize(slot + 1, None);
        }
        self.assignments[slot] = Some((task.arena_index().generation(), worker));
    }

    /// Returns the worker owning `task`, but only when the recorded assignment
    /// belongs to this exact task generation.
    ///
    /// GH#55: `assignments` is indexed by arena slot, while `scheduled` and the
    /// per-worker queues are keyed by the full `TaskId` (slot + generation).
    /// Without the generation check, a task that reuses a slot aliases the
    /// previous occupant's assignment and can be routed to a worker that does
    /// not hold its queue entry.
    #[inline]
    fn assignment_for(&self, task: TaskId) -> Option<usize> {
        let slot = task.arena_index().index() as usize;
        match self.assignments.get(slot) {
            Some(&Some((generation, worker))) if generation == task.arena_index().generation() => {
                Some(worker)
            }
            _ => None,
        }
    }

    fn assign_worker(&mut self, task: TaskId) -> usize {
        if let Some(worker) = self.assignment_for(task) {
            return worker;
        }
        let worker = self.next_worker % self.workers.len();
        self.next_worker = self.next_worker.wrapping_add(1);
        self.set_assignment(task, worker);
        worker
    }

    /// Schedules a task in the ready lane on its assigned worker.
    pub fn schedule(&mut self, task: TaskId, priority: u8) {
        if !self.scheduled.insert(task) {
            return;
        }

        let worker = self.assign_worker(task);
        self.workers[worker].schedule(task, priority);
    }

    /// Injects ready-lane wakeups that should survive normal deduplication.
    ///
    /// The first wake is scheduled immediately when needed. Remaining wakeups
    /// are re-armed one-by-one after each dequeue so wake storms trigger
    /// repeated polls instead of collapsing to a single queued wake.
    fn inject_spurious_wakes(&mut self, task: TaskId, priority: u8, count: usize) {
        if count == 0 {
            return;
        }

        let mut remaining = count;
        if self.scheduled.insert(task) {
            let worker = self.assign_worker(task);
            self.workers[worker].schedule(task, priority);
            remaining = remaining.saturating_sub(1);
        }

        if remaining == 0 {
            return;
        }

        self.pending_spurious_wakes
            .entry(task)
            .and_modify(|pending| {
                pending.priority = pending.priority.max(priority);
                pending.remaining = pending.remaining.saturating_add(remaining);
            })
            .or_insert(PendingSpuriousWake {
                priority,
                remaining,
            });
    }

    /// Schedules or promotes a task into the cancel lane.
    pub fn schedule_cancel(&mut self, task: TaskId, priority: u8) {
        if self.scheduled.insert(task) {
            let worker = self.assign_worker(task);
            self.workers[worker].schedule_cancel(task, priority);
            return;
        }

        // GH#55: the task is already in `scheduled`, so `is_empty()` reports
        // work pending. If we cannot promote it we must still queue it
        // somewhere, or it is stranded — present in `scheduled` with no entry
        // in any worker lane — and the runtime spins forever waiting for work
        // that can never be dispatched.
        if let Some(worker) = self.assignment_for(task) {
            self.workers[worker].move_to_cancel_lane(task, priority);
        } else {
            let worker = self.assign_worker(task);
            self.workers[worker].schedule_cancel(task, priority);
        }
    }

    /// Schedules a task in the timed lane on its assigned worker.
    pub fn schedule_timed(&mut self, task: TaskId, deadline: Time) {
        if !self.scheduled.insert(task) {
            return;
        }

        let worker = self.assign_worker(task);
        self.workers[worker].schedule_timed(task, deadline);
    }

    fn pop_for_worker(
        &mut self,
        worker: usize,
        rng_hint: u64,
        now: Time,
    ) -> Option<(TaskId, DispatchLane)> {
        if self.workers.is_empty() {
            return None;
        }

        let worker = worker % self.workers.len();
        let cancel_streak = &mut self.cancel_streak[worker];

        if *cancel_streak < self.cancel_streak_limit {
            if let Some((task, lane)) = self.workers[worker].pop_cancel_with_rng(rng_hint) {
                *cancel_streak += 1;
                self.scheduled.remove(&task);
                self.set_assignment(task, worker);
                self.rearm_spurious_wake(task);
                return Some((task, lane));
            }
        }

        if let Some(task) = self.workers[worker].pop_timed_only_with_hint(rng_hint, now) {
            *cancel_streak = 0;
            self.scheduled.remove(&task);
            self.set_assignment(task, worker);
            self.rearm_spurious_wake(task);
            return Some((task, DispatchLane::Timed));
        }

        if let Some(task) = self.workers[worker].pop_ready_only_with_hint(rng_hint) {
            *cancel_streak = 0;
            self.scheduled.remove(&task);
            self.set_assignment(task, worker);
            self.rearm_spurious_wake(task);
            return Some((task, DispatchLane::Ready));
        }

        if let Some((task, lane)) = self.workers[worker].pop_cancel_with_rng(rng_hint) {
            *cancel_streak = 1;
            self.scheduled.remove(&task);
            self.set_assignment(task, worker);
            self.rearm_spurious_wake(task);
            return Some((task, lane));
        }

        *cancel_streak = 0;
        None
    }

    fn steal_for_worker(&mut self, thief: usize, rng_hint: u64) -> Option<TaskId> {
        let count = self.workers.len();
        if count <= 1 {
            return None;
        }

        let thief = thief % count;
        let start = (rng_hint as usize) % count;

        for offset in 0..count {
            let victim = (start + offset) % count;
            if victim == thief {
                continue;
            }
            if let Some(task) =
                self.workers[victim].pop_ready_only_with_hint(rng_hint.wrapping_add(offset as u64))
            {
                self.scheduled.remove(&task);
                self.set_assignment(task, thief);
                self.rearm_spurious_wake(task);
                return Some(task);
            }
        }

        None
    }

    fn take_forced(
        &mut self,
        task: TaskId,
        expected_worker: usize,
        expected_lane: DispatchLane,
        now: Time,
        index: usize,
    ) -> Result<(), ForcedScheduleError> {
        if expected_worker >= self.workers.len() {
            return Err(ForcedScheduleError::WorkerUnavailable {
                worker: u32::try_from(expected_worker).unwrap_or(u32::MAX),
                worker_count: self.workers.len(),
            });
        }
        if !self.scheduled.contains(&task) {
            return Err(ForcedScheduleError::TaskUnavailable {
                index,
                task: task.into(),
            });
        }
        let actual_worker =
            self.assignment_for(task)
                .ok_or(ForcedScheduleError::TaskUnavailable {
                    index,
                    task: task.into(),
                })?;

        let queue_lane = if expected_lane == DispatchLane::Stolen {
            if expected_worker == actual_worker {
                return Err(ForcedScheduleError::LaneMismatch {
                    index,
                    expected: DispatchLane::Stolen,
                    actual: DispatchLane::Ready,
                });
            }
            DispatchLane::Ready
        } else {
            if expected_worker != actual_worker {
                return Err(ForcedScheduleError::WorkerMismatch {
                    index,
                    expected: u32::try_from(expected_worker).unwrap_or(u32::MAX),
                    actual: u32::try_from(actual_worker).unwrap_or(u32::MAX),
                });
            }
            expected_lane
        };

        match self.workers[actual_worker].take_exact(task, queue_lane, now) {
            Ok(()) => {}
            Err(ExactDispatchError::NotScheduled) => {
                return Err(ForcedScheduleError::TaskUnavailable {
                    index,
                    task: task.into(),
                });
            }
            Err(ExactDispatchError::TimedNotDue { deadline }) => {
                return Err(ForcedScheduleError::TimedNotDue {
                    index,
                    deadline: deadline.as_nanos(),
                    now: now.as_nanos(),
                });
            }
            Err(ExactDispatchError::LaneMismatch { actual }) => {
                return Err(ForcedScheduleError::LaneMismatch {
                    index,
                    expected: expected_lane,
                    actual,
                });
            }
            Err(ExactDispatchError::QueueInvariant) => {
                return Err(ForcedScheduleError::QueueInvariant { index });
            }
        }

        let removed = self.scheduled.remove(&task);
        debug_assert!(removed, "forced task was checked in lab scheduled set");
        if expected_lane == DispatchLane::Stolen {
            self.set_assignment(task, expected_worker);
            self.cancel_streak[expected_worker] = 0;
        } else if expected_lane == DispatchLane::Cancel {
            let cancel_streak = &mut self.cancel_streak[actual_worker];
            *cancel_streak = if *cancel_streak < self.cancel_streak_limit {
                (*cancel_streak).saturating_add(1)
            } else {
                1
            };
        } else {
            self.cancel_streak[actual_worker] = 0;
        }
        self.rearm_spurious_wake(task);
        Ok(())
    }

    fn forget_task(&mut self, task: TaskId) {
        self.scheduled.remove(&task);
        self.pending_spurious_wakes.remove(&task);
        // GH#55: only clear the slot when the recorded assignment belongs to
        // this generation. `scheduled` and the worker lanes are keyed by the
        // full `TaskId`, so clearing on slot alone would drop the routing of a
        // still-live task that merely reuses the arena slot.
        if self.assignment_for(task).is_some() {
            let slot = task.arena_index().index() as usize;
            self.assignments[slot] = None;
        }
        for worker in &mut self.workers {
            worker.remove(task);
        }
    }

    fn rearm_spurious_wake(&mut self, task: TaskId) {
        let Some(mut pending) = self.pending_spurious_wakes.remove(&task) else {
            return;
        };

        self.schedule(task, pending.priority);
        pending.remaining = pending.remaining.saturating_sub(1);
        if pending.remaining > 0 {
            self.pending_spurious_wakes.insert(task, pending);
        }
    }
}

struct TaskWaker {
    task_id: crate::types::TaskId,
    priority: u8,
    scheduler: Arc<Mutex<LabScheduler>>,
}

use std::task::Wake;
impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        self.scheduler.lock().schedule(self.task_id, self.priority);
    }
}

/// Waker that reschedules a task into the cancel lane.
///
/// Set as `cancel_waker` on each task's `CxInner` before polling so that
/// `abort_with_reason` can wake cancelled tasks.
struct CancelTaskWaker {
    task_id: crate::types::TaskId,
    priority: u8,
    scheduler: Arc<Mutex<LabScheduler>>,
}

impl Wake for CancelTaskWaker {
    fn wake(self: Arc<Self>) {
        self.scheduler
            .lock()
            .schedule_cancel(self.task_id, self.priority);
    }
}

/// An invariant violation detected by the lab runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InvariantViolation {
    /// Obligations were not resolved.
    ObligationLeak {
        /// Leaked obligations and diagnostic metadata.
        leaks: Vec<ObligationLeak>,
    },
    /// Tasks were not drained.
    TaskLeak {
        /// Number of leaked tasks.
        count: usize,
    },
    /// Actors were not stopped before region close.
    ActorLeak {
        /// Number of leaked actors.
        count: usize,
    },
    /// A region closed with live children.
    QuiescenceViolation,
    /// A task held obligations but stopped being polled (futurelock).
    Futurelock {
        /// The task that futurelocked.
        task: crate::types::TaskId,
        /// The owning region.
        region: crate::types::RegionId,
        /// How many lab steps since last poll.
        idle_steps: u64,
        /// Held obligations.
        held: Vec<ObligationId>,
        /// Last checkpoint message recorded by the task, when available.
        last_checkpoint_message: Option<String>,
    },
    /// Cancellation protocol violation detected.
    CancellationProtocol {
        /// The violation description.
        violation: String,
    },
    /// br-asupersync-ipejce: a fuzz / scenario test closure panicked.
    /// Recorded so the campaign can keep searching instead of
    /// aborting on the first finding (the most interesting outcome
    /// of any fuzz campaign).
    TestPanic {
        /// Stringified panic payload (extracted via `Any::downcast`
        /// of `&str` and `String` — falls back to `<unknown panic>`).
        message: String,
    },
}

/// Diagnostic details for a leaked obligation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObligationLeak {
    /// The leaked obligation id.
    pub obligation: ObligationId,
    /// Kind of obligation (permit/ack/lease/io).
    pub kind: ObligationKind,
    /// Task that held the obligation.
    pub holder: crate::types::TaskId,
    /// Region that owned the obligation.
    pub region: crate::types::RegionId,
}

impl std::fmt::Display for ObligationLeak {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "obligation={:?} kind={:?} holder={:?} region={:?}",
            self.obligation, self.kind, self.holder, self.region
        )
    }
}

fn format_futurelock_checkpoint(message: Option<&str>) -> String {
    match message {
        Some(message) => format!("{message:?}"),
        None => "<none>".to_string(),
    }
}

impl std::fmt::Display for InvariantViolation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ObligationLeak { leaks } => {
                write!(f, "[ASUP-E101] obligation leak: count={}", leaks.len())?;
                if !leaks.is_empty() {
                    write!(f, " leaks=[")?;
                    for (index, leak) in leaks.iter().enumerate() {
                        if index > 0 {
                            write!(f, "; ")?;
                        }
                        write!(f, "{leak}")?;
                    }
                    write!(f, "]")?;
                }
                Ok(())
            }
            Self::TaskLeak { count } => write!(f, "{count} tasks leaked"),
            Self::ActorLeak { count } => write!(f, "{count} actors leaked"),
            Self::QuiescenceViolation => write!(f, "region closed without quiescence"),
            Self::Futurelock {
                task,
                region,
                idle_steps,
                held,
                last_checkpoint_message,
            } => write!(
                f,
                "[ASUP-E402] futurelock: {task} in {region} idle={idle_steps} held={held:?} last_checkpoint={}",
                format_futurelock_checkpoint(last_checkpoint_message.as_deref())
            ),
            Self::CancellationProtocol { violation } => {
                write!(f, "cancellation protocol violation: {violation}")
            }
            Self::TestPanic { message } => write!(f, "test panic: {message}"),
        }
    }
}

/// Convenience function for running a test with the lab runtime.
pub fn test<F, R>(seed: u64, f: F) -> R
where
    F: FnOnce(&mut LabRuntime) -> R,
{
    let mut runtime = LabRuntime::with_seed(seed);
    let result = f(&mut runtime);

    // Check invariants
    let violations = runtime.check_invariants();
    assert!(
        violations.is_empty(),
        "Lab runtime invariant violations: {violations:?}"
    );

    result
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use crate::lab::chaos::ChaosConfig;
    use crate::record::TaskRecord;
    use crate::record::{ObligationAbortReason, ObligationKind};
    use crate::runtime::deadline_monitor::{AdaptiveDeadlineConfig, WarningReason};
    #[cfg(unix)]
    use crate::runtime::reactor::Interest;
    use crate::runtime::reactor::{Event, Token};
    use crate::types::{Budget, CancelKind, CancelReason, CxInner, Outcome, TaskId};
    use crate::util::ArenaIndex;
    use parking_lot::Mutex;
    use parking_lot::RwLock;
    use std::sync::Arc;
    use std::task::Waker;
    use std::time::Duration;

    #[cfg(unix)]
    struct TestFdSource;
    #[cfg(unix)]
    impl std::os::fd::AsRawFd for TestFdSource {
        fn as_raw_fd(&self) -> std::os::fd::RawFd {
            0
        }
    }

    #[cfg(unix)]
    fn noop_waker() -> Waker {
        std::task::Waker::noop().clone()
    }

    /// Waker that sets an `AtomicBool` when woken (for virtual time tests).
    struct FlagWaker(Arc<std::sync::atomic::AtomicBool>);
    impl Wake for FlagWaker {
        fn wake(self: Arc<Self>) {
            self.0.store(true, std::sync::atomic::Ordering::SeqCst);
        }
    }

    /// Waker that increments an `AtomicU64` counter when woken.
    struct CountWaker(Arc<std::sync::atomic::AtomicU64>);
    impl Wake for CountWaker {
        fn wake(self: Arc<Self>) {
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    struct HandleCancelWakeAudit {
        task_id: TaskId,
        caller_lock: Arc<Mutex<()>>,
        scheduler: Arc<Mutex<LabScheduler>>,
        wake_calls: Arc<std::sync::atomic::AtomicUsize>,
        calls_under_caller_lock: Arc<std::sync::atomic::AtomicUsize>,
        calls_under_scheduler_lock: Arc<std::sync::atomic::AtomicUsize>,
        cancel_lane_published: Arc<std::sync::atomic::AtomicBool>,
    }

    impl std::task::Wake for HandleCancelWakeAudit {
        fn wake(self: Arc<Self>) {
            use std::sync::atomic::Ordering;

            self.wake_calls.fetch_add(1, Ordering::SeqCst);
            let caller_guard = self.caller_lock.try_lock();
            if caller_guard.is_none() {
                self.calls_under_caller_lock.fetch_add(1, Ordering::SeqCst);
            }
            drop(caller_guard);

            if let Some(scheduler) = self.scheduler.try_lock() {
                let mut scheduler = scheduler;
                let observed = scheduler.pop_for_worker(0, 0, Time::ZERO);
                self.cancel_lane_published.store(
                    matches!(observed, Some((task, DispatchLane::Cancel)) if task == self.task_id),
                    Ordering::SeqCst,
                );
                if observed.is_some() {
                    scheduler.schedule_cancel(self.task_id, u8::MAX);
                }
            } else {
                self.calls_under_scheduler_lock
                    .fetch_add(1, Ordering::SeqCst);
            }
        }
    }

    fn exercise_managed_handle_cancel_boundary(via_join_drop: bool) {
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

        let mut runtime = LabRuntime::new(LabConfig::new(7));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, mut handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {
                std::future::poll_fn(|_| {
                    if crate::cx::Cx::with_current(|cx| cx.checkpoint().is_err()).unwrap_or(false) {
                        Poll::Ready(())
                    } else {
                        Poll::Pending
                    }
                })
                .await;
            })
            .expect("create managed task");
        let inner = runtime
            .state
            .task(task_id)
            .and_then(|task| task.cx_inner.clone())
            .expect("managed task has a Cx");

        runtime.scheduler.lock().schedule(task_id, 0);
        runtime.step_for_test();
        assert!(runtime.scheduler.lock().is_empty());

        let caller_lock = Arc::new(Mutex::new(()));
        let wake_calls = Arc::new(AtomicUsize::new(0));
        let calls_under_caller_lock = Arc::new(AtomicUsize::new(0));
        let calls_under_scheduler_lock = Arc::new(AtomicUsize::new(0));
        let cancel_lane_published = Arc::new(AtomicBool::new(false));
        let audit_waker = Waker::from(Arc::new(HandleCancelWakeAudit {
            task_id,
            caller_lock: Arc::clone(&caller_lock),
            scheduler: Arc::clone(&runtime.scheduler),
            wake_calls: Arc::clone(&wake_calls),
            calls_under_caller_lock: Arc::clone(&calls_under_caller_lock),
            calls_under_scheduler_lock: Arc::clone(&calls_under_scheduler_lock),
            cancel_lane_published: Arc::clone(&cancel_lane_published),
        }));
        let retired_waker = {
            let mut guard = inner.write();
            guard
                .cancel_waker
                .replace(Arc::new(crate::types::task_context::CancelWaker::new(
                    audit_waker,
                )))
        };
        drop(retired_waker);

        let join_cx = crate::cx::Cx::for_testing();
        if via_join_drop {
            let join = handle.join_with_drop_reason(&join_cx, CancelReason::timeout());
            let caller_guard = caller_lock.lock();
            drop(join);
            assert_eq!(
                wake_calls.load(Ordering::SeqCst),
                0,
                "JoinFuture::drop must not invoke a cancellation Waker inline"
            );
            drop(caller_guard);
        } else {
            let caller_guard = caller_lock.lock();
            handle.abort_with_reason(CancelReason::timeout());
            handle.abort_with_reason(CancelReason::timeout());
            assert_eq!(
                wake_calls.load(Ordering::SeqCst),
                0,
                "TaskHandle::abort must not invoke a cancellation Waker inline"
            );
            drop(caller_guard);
        }

        {
            let guard = inner.read();
            assert!(
                guard.cancel_requested,
                "managed handle cancellation is checkpoint-visible immediately"
            );
            assert_eq!(
                guard.cancel_reason.as_ref().map(|reason| reason.kind),
                Some(CancelKind::Timeout)
            );
        }
        assert_eq!(runtime.spawn_mailbox.len(), 1, "identical aborts coalesce");
        assert!(runtime.scheduler.lock().is_empty());

        assert_eq!(runtime.run_until_quiescent(), 1);
        assert_eq!(wake_calls.load(Ordering::SeqCst), 1);
        assert_eq!(calls_under_caller_lock.load(Ordering::SeqCst), 0);
        assert_eq!(calls_under_scheduler_lock.load(Ordering::SeqCst), 0);
        assert!(cancel_lane_published.load(Ordering::SeqCst));
        assert!(runtime.spawn_mailbox.handle_cancels_are_empty());
        assert!(handle.is_finished());
        assert!(runtime.state.task(task_id).is_none());
        assert!(matches!(
            runtime.state.region_close_outcome(root),
            Some(Outcome::Cancelled(reason)) if reason.is_kind(CancelKind::Timeout)
        ));
        assert!(runtime.is_quiescent());
    }

    #[test]
    fn managed_task_handle_abort_defers_waker_until_cancel_lane_publication() {
        init_test("managed_task_handle_abort_defers_waker_until_cancel_lane_publication");
        exercise_managed_handle_cancel_boundary(false);
        crate::test_complete!(
            "managed_task_handle_abort_defers_waker_until_cancel_lane_publication"
        );
    }

    #[test]
    fn managed_join_future_drop_defers_waker_until_cancel_lane_publication() {
        init_test("managed_join_future_drop_defers_waker_until_cancel_lane_publication");
        exercise_managed_handle_cancel_boundary(true);
        crate::test_complete!(
            "managed_join_future_drop_defers_waker_until_cancel_lane_publication"
        );
    }

    #[test]
    fn checkpoint_ack_ready_before_handle_command_reconciles_terminal_cancel() {
        use std::sync::Barrier;
        use std::sync::atomic::{AtomicU64, Ordering};

        init_test("checkpoint_ack_ready_before_handle_command_reconciles_terminal_cancel");
        let mut runtime = LabRuntime::new(LabConfig::new(19));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let entered = Arc::new(Barrier::new(2));
        let abort_done = Arc::new(Barrier::new(2));
        let auxiliary_calls = Arc::new(AtomicU64::new(0));
        let auxiliary_waker = Waker::from(Arc::new(CountWaker(Arc::clone(&auxiliary_calls))));

        let task_entered = Arc::clone(&entered);
        let task_abort_done = Arc::clone(&abort_done);
        let (task_id, handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                std::future::poll_fn(move |_| {
                    crate::cx::Cx::with_current(|cx| {
                        cx.register_cancel_waker(&auxiliary_waker);
                    })
                    .expect("task Cx is installed");
                    task_entered.wait();
                    task_abort_done.wait();
                    assert!(
                        crate::cx::Cx::with_current(|cx| cx.checkpoint().is_err()).unwrap_or(false),
                        "same-poll checkpoint observes the queued handle abort"
                    );
                    Poll::Ready(())
                })
                .await;
            })
            .expect("create managed task");
        runtime.scheduler.lock().schedule(task_id, 0);

        let canceller = std::thread::spawn(move || {
            let handle = handle;
            entered.wait();
            handle.abort_with_reason(CancelReason::race_loser());
            abort_done.wait();
            handle
        });

        runtime.step_for_test();
        let mut handle = canceller.join().expect("abort thread completes");
        assert!(
            !runtime.spawn_mailbox.handle_cancels_are_empty(),
            "command remains queued until the next runtime boundary"
        );
        assert!(runtime.state.task(task_id).is_none());
        assert!(matches!(
            runtime.state.region_close_outcome(root),
            Some(Outcome::Cancelled(reason)) if reason.is_kind(CancelKind::RaceLost)
        ));
        assert_eq!(
            auxiliary_calls.load(Ordering::SeqCst),
            1,
            "auxiliary cancellation Waker runs once after terminal publication"
        );
        assert!(handle.is_finished());
        assert!(
            !matches!(handle.try_join(), Ok(None)),
            "join result is available regardless of path-specific payload semantics"
        );

        runtime.step_for_test();
        assert!(runtime.spawn_mailbox.handle_cancels_are_empty());
        assert!(runtime.state.task(task_id).is_none());
        assert!(matches!(
            runtime.state.region_close_outcome(root),
            Some(Outcome::Cancelled(reason)) if reason.is_kind(CancelKind::RaceLost)
        ));
        assert_eq!(auxiliary_calls.load(Ordering::SeqCst), 1);
        assert!(runtime.check_invariants().is_empty());
        crate::test_complete!(
            "checkpoint_ack_ready_before_handle_command_reconciles_terminal_cancel"
        );
    }

    #[test]
    fn checkpoint_ack_pending_republishes_cancel_lane_before_waker_dispatch() {
        use std::sync::Barrier;
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

        init_test("checkpoint_ack_pending_republishes_cancel_lane_before_waker_dispatch");
        let mut runtime = LabRuntime::new(LabConfig::new(23));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let entered = Arc::new(Barrier::new(2));
        let abort_done = Arc::new(Barrier::new(2));
        let polls = Arc::new(AtomicUsize::new(0));
        let audit_target = Arc::new(Mutex::new(None));
        let caller_lock = Arc::new(Mutex::new(()));
        let wake_calls = Arc::new(AtomicUsize::new(0));
        let calls_under_caller_lock = Arc::new(AtomicUsize::new(0));
        let calls_under_scheduler_lock = Arc::new(AtomicUsize::new(0));
        let cancel_lane_published = Arc::new(AtomicBool::new(false));

        let task_entered = Arc::clone(&entered);
        let task_abort_done = Arc::clone(&abort_done);
        let task_polls = Arc::clone(&polls);
        let task_audit_target = Arc::clone(&audit_target);
        let (task_id, handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                std::future::poll_fn(move |_| {
                    let poll = task_polls.fetch_add(1, Ordering::SeqCst);
                    if poll == 0 {
                        let target = task_audit_target
                            .lock()
                            .as_ref()
                            .cloned()
                            .expect("audit Waker installed before first poll");
                        let retired = crate::cx::Cx::with_current(|cx| {
                            cx.inner.write().cancel_waker.replace(target)
                        })
                        .expect("task Cx is installed");
                        drop(retired);
                        task_entered.wait();
                        task_abort_done.wait();
                    }
                    assert!(
                        crate::cx::Cx::with_current(|cx| cx.checkpoint().is_err()).unwrap_or(false),
                        "checkpoint observes cancellation on every cleanup poll"
                    );
                    if poll == 0 {
                        Poll::Pending
                    } else {
                        Poll::Ready(())
                    }
                })
                .await;
            })
            .expect("create managed task");
        *audit_target.lock() = Some(Arc::new(crate::types::task_context::CancelWaker::new(
            Waker::from(Arc::new(HandleCancelWakeAudit {
                task_id,
                caller_lock: Arc::clone(&caller_lock),
                scheduler: Arc::clone(&runtime.scheduler),
                wake_calls: Arc::clone(&wake_calls),
                calls_under_caller_lock: Arc::clone(&calls_under_caller_lock),
                calls_under_scheduler_lock: Arc::clone(&calls_under_scheduler_lock),
                cancel_lane_published: Arc::clone(&cancel_lane_published),
            })),
        )));
        runtime.scheduler.lock().schedule(task_id, 0);

        let canceller = std::thread::spawn(move || {
            let handle = handle;
            entered.wait();
            handle.abort_with_reason(CancelReason::shutdown());
            abort_done.wait();
            handle
        });

        runtime.step_for_test();
        let handle = canceller.join().expect("abort thread completes");
        assert!(matches!(
            &runtime.state.task(task_id).expect("task record").state,
            TaskState::Cancelling { reason, .. } if reason.is_kind(CancelKind::Shutdown)
        ));
        assert!(
            !runtime.scheduler.lock().is_empty(),
            "acknowledged Pending task is republished on the cancel lane"
        );
        assert_eq!(
            wake_calls.load(Ordering::SeqCst),
            1,
            "first reconciliation dispatches the audit Waker once"
        );
        assert_eq!(calls_under_caller_lock.load(Ordering::SeqCst), 0);
        assert_eq!(calls_under_scheduler_lock.load(Ordering::SeqCst), 0);
        assert!(
            cancel_lane_published.load(Ordering::SeqCst),
            "the first Waker callback must observe an already-published cancel lane"
        );

        runtime.step_for_test();
        assert_eq!(polls.load(Ordering::SeqCst), 2);
        assert!(runtime.state.task(task_id).is_none());
        assert!(matches!(
            runtime.state.region_close_outcome(root),
            Some(Outcome::Cancelled(reason)) if reason.is_kind(CancelKind::Shutdown)
        ));
        assert_eq!(
            wake_calls.load(Ordering::SeqCst),
            1,
            "repeated acknowledged checkpoints do not duplicate Waker dispatch"
        );
        assert!(handle.is_finished());
        assert!(runtime.spawn_mailbox.handle_cancels_are_empty());
        assert!(runtime.check_invariants().is_empty());
        crate::test_complete!(
            "checkpoint_ack_pending_republishes_cancel_lane_before_waker_dispatch"
        );
    }

    #[test]
    fn handle_cancel_command_blocks_lab_quiescence_until_drained() {
        init_test("handle_cancel_command_blocks_lab_quiescence_until_drained");
        let mut runtime = LabRuntime::new(LabConfig::new(11));
        assert!(runtime.is_quiescent());

        let missing = TaskId::from_arena(ArenaIndex::new(usize::MAX as u32, 0));
        let gateway = runtime.state.spawn_gateway().expect("lab gateway");
        assert!(gateway.enqueue_handle_cancel(missing, CancelReason::shutdown()));
        assert!(
            !runtime.is_quiescent(),
            "a queued command is live runtime work even when its task is stale"
        );

        assert_eq!(runtime.run_until_quiescent(), 1);
        assert!(runtime.spawn_mailbox.handle_cancels_are_empty());
        assert!(runtime.is_quiescent());
        crate::test_complete!("handle_cancel_command_blocks_lab_quiescence_until_drained");
    }

    #[test]
    fn managed_pre_admission_abort_transitions_task_record_before_first_poll() {
        init_test("managed_pre_admission_abort_transitions_task_record_before_first_poll");
        let mut runtime = LabRuntime::new(LabConfig::new(13));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let pending = runtime
            .state
            .region(root)
            .expect("root region")
            .pending_spawn_handle();
        let parent: crate::cx::Cx = crate::cx::Cx::new(
            root,
            TaskId::from_arena(ArenaIndex::new(u32::MAX - 1, 0)),
            Budget::INFINITE,
        )
        .with_spawn_gateway(runtime.state.spawn_gateway())
        .with_pending_spawn_counter(Some(pending));

        let mut handle = parent
            .spawn(|child| async move {
                std::future::poll_fn(move |_| {
                    if child.checkpoint().is_err() {
                        Poll::Ready(())
                    } else {
                        Poll::Pending
                    }
                })
                .await;
            })
            .expect("managed spawn enqueues");
        let provisional = handle.task_id();
        handle.abort_with_reason(CancelReason::race_loser());
        assert!(
            runtime.spawn_mailbox.handle_cancels_are_empty(),
            "pre-admission abort remains cache-only until identity publication"
        );

        assert_eq!(runtime.run_until_quiescent(), 1);
        let canonical = handle.task_id();
        assert_ne!(canonical, provisional);
        assert!(
            runtime.state.task(canonical).is_none(),
            "quiescent completion retires the canonical task record"
        );
        assert!(handle.is_finished());
        assert!(runtime.spawn_mailbox.is_empty());
        assert!(runtime.is_quiescent());
        assert!(matches!(
            handle.try_join(),
            Err(crate::runtime::JoinError::Cancelled(reason))
                if reason.is_kind(CancelKind::RaceLost)
        ));
        crate::test_complete!(
            "managed_pre_admission_abort_transitions_task_record_before_first_poll"
        );
    }

    #[test]
    fn stale_handle_cancel_command_cannot_weaken_newer_cx_reason() {
        init_test("stale_handle_cancel_command_cannot_weaken_newer_cx_reason");
        let mut runtime = LabRuntime::new(LabConfig::new(17));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {
                std::future::pending::<()>().await;
            })
            .expect("create managed task");
        let inner = runtime
            .state
            .task(task_id)
            .and_then(|task| task.cx_inner.clone())
            .expect("managed task Cx");

        handle.abort_with_reason(CancelReason::user("stale"));
        let mut stale = Vec::new();
        assert_eq!(
            runtime
                .spawn_mailbox
                .dequeue_handle_cancels_into(1, &mut stale),
            1
        );
        handle.abort_with_reason(CancelReason::shutdown());
        let stale = stale.pop().expect("saved stale command");

        let (route, wakes) = runtime
            .state
            .cancel_task_for_handle(stale.task_id, &stale.reason)
            .into_parts();
        assert_eq!(route.map(|route| route.priority), Some(u8::MAX));
        assert!(route.is_some_and(|route| !route.delegated_initial));
        assert!(wakes.is_empty());
        wakes.dispatch();
        assert!(
            runtime
                .state
                .task(task_id)
                .and_then(TaskRecord::cancel_reason)
                .is_some_and(|reason| reason.is_kind(CancelKind::Shutdown))
        );
        assert!(
            inner
                .read()
                .cancel_reason
                .as_ref()
                .is_some_and(|reason| reason.is_kind(CancelKind::Shutdown))
        );
        crate::test_complete!("stale_handle_cancel_command_cannot_weaken_newer_cx_reason");
    }

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    struct TimerAdvanceOutcome {
        advance_points: Vec<Time>,
        total_wakeups: u64,
        final_time: Time,
        cancelled_wakeups: u64,
    }

    fn collect_timer_advances(
        deadlines_secs: &[u64],
        cancelled_indices: &[usize],
    ) -> TimerAdvanceOutcome {
        let mut runtime = LabRuntime::with_seed(42);
        let timer_handle = runtime.state.timer_driver_handle().expect("timer handle");
        let live_wakeups = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let cancelled_wakeups = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let mut handles = Vec::with_capacity(deadlines_secs.len());

        for (idx, secs) in deadlines_secs.iter().copied().enumerate() {
            let counter = if cancelled_indices.contains(&idx) {
                cancelled_wakeups.clone()
            } else {
                live_wakeups.clone()
            };
            let waker = Waker::from(Arc::new(CountWaker(counter)));
            handles.push(timer_handle.register(Time::from_secs(secs), waker));
        }

        for &idx in cancelled_indices {
            let cancelled = timer_handle.cancel(&handles[idx]);
            crate::assert_with_log!(
                cancelled,
                "cancelled timer handle remains removable before auto-advance",
                true,
                cancelled
            );
        }

        let mut advance_points = Vec::new();
        while runtime.pending_timer_count() > 0 {
            let before = runtime.now();
            let next_deadline = runtime.next_timer_deadline().expect("pending deadline");
            let wakeups = runtime.advance_to_next_timer();
            let after = runtime.now();

            crate::assert_with_log!(
                after >= before,
                "virtual time stays monotone while advancing timers",
                true,
                after >= before
            );
            crate::assert_with_log!(
                after >= next_deadline,
                "advance reaches or passes scheduled deadline",
                true,
                after >= next_deadline
            );
            crate::assert_with_log!(
                wakeups > 0,
                "each advance drains at least one live timer",
                true,
                wakeups > 0
            );

            advance_points.push(after);
        }

        TimerAdvanceOutcome {
            advance_points,
            total_wakeups: live_wakeups.load(std::sync::atomic::Ordering::SeqCst),
            final_time: runtime.now(),
            cancelled_wakeups: cancelled_wakeups.load(std::sync::atomic::Ordering::SeqCst),
        }
    }

    #[asupersync::lab_test(seeds = 42..43)]
    fn empty_runtime_is_quiescent(runtime: &mut LabRuntime) {
        let quiescent = runtime.is_quiescent();
        crate::assert_with_log!(quiescent, "quiescent", true, quiescent);
    }

    #[asupersync::lab_test(seeds = 42..43)]
    fn advance_time(runtime: &mut LabRuntime) {
        let now = runtime.now();
        crate::assert_with_log!(now == Time::ZERO, "now", Time::ZERO, now);

        runtime.advance_time(1_000_000);
        let now = runtime.now();
        crate::assert_with_log!(
            now == Time::from_millis(1),
            "now",
            Time::from_millis(1),
            now
        );
    }

    #[test]
    fn duration_nanos_saturating_clamps_large_duration() {
        init_test("duration_nanos_saturating_clamps_large_duration");
        let huge = Duration::from_secs(u64::MAX);
        let saturated = LabRuntime::duration_nanos_saturating(huge);
        crate::assert_with_log!(
            saturated == u64::MAX,
            "huge duration saturates",
            u64::MAX,
            saturated
        );

        let small = Duration::from_nanos(123);
        let exact = LabRuntime::duration_nanos_saturating(small);
        crate::assert_with_log!(exact == 123, "small duration exact", 123u64, exact);
        crate::test_complete!("duration_nanos_saturating_clamps_large_duration");
    }

    #[cfg(unix)]
    #[test]
    fn lab_runtime_records_io_ready_trace() {
        init_test("lab_runtime_records_io_ready_trace");

        let mut runtime = LabRuntime::with_seed(42);
        let handle = runtime.state.io_driver_handle().expect("io driver");
        let waker = noop_waker();
        let source = TestFdSource;

        let registration = handle
            .register(&source, Interest::READABLE, waker)
            .expect("register source");
        let token = registration.token();

        runtime
            .lab_reactor()
            .inject_event(token, Event::readable(token), Duration::from_millis(1));
        runtime.advance_time(1_000_000);
        runtime.step_for_test();

        let mut saw_requested = false;
        let mut saw_ready = false;
        for event in runtime.state.trace.snapshot() {
            if event.kind == TraceEventKind::IoRequested {
                saw_requested = true;
            }
            if event.kind == TraceEventKind::IoReady {
                saw_ready = true;
            }
        }
        crate::assert_with_log!(
            saw_requested,
            "io requested trace recorded",
            true,
            saw_requested
        );
        crate::assert_with_log!(saw_ready, "io ready trace recorded", true, saw_ready);
        crate::test_complete!("lab_runtime_records_io_ready_trace");
    }

    #[cfg(unix)]
    #[test]
    fn lab_runtime_chaos_stats_include_reactor_io_error_injections() {
        init_test("lab_runtime_chaos_stats_include_reactor_io_error_injections");

        let config = LabConfig::new(7).with_chaos(
            ChaosConfig::new(7)
                .with_io_error_probability(1.0)
                .with_io_error_kinds(vec![std::io::ErrorKind::TimedOut]),
        );
        let mut runtime = LabRuntime::new(config);
        let handle = runtime.state.io_driver_handle().expect("io driver");
        let waker = noop_waker();
        let source = TestFdSource;

        let registration = handle
            .register(&source, Interest::READABLE, waker)
            .expect("register source");
        let token = registration.token();

        runtime
            .lab_reactor()
            .inject_event(token, Event::readable(token), Duration::ZERO);
        runtime.step_for_test();

        let stats = runtime.chaos_stats();
        crate::assert_with_log!(
            stats.io_errors == 1,
            "io errors aggregated",
            1u64,
            stats.io_errors
        );
        crate::assert_with_log!(
            stats.decision_points == 1,
            "reactor decision points aggregated",
            1u64,
            stats.decision_points
        );
        crate::assert_with_log!(
            runtime.lab_reactor().last_io_error_kind() == Some(std::io::ErrorKind::TimedOut),
            "reactor last error kind surfaced",
            Some(std::io::ErrorKind::TimedOut),
            runtime.lab_reactor().last_io_error_kind()
        );

        crate::test_complete!("lab_runtime_chaos_stats_include_reactor_io_error_injections");
    }

    #[test]
    fn pending_task_without_wakeup_storm_still_counts_chaos_decision_point() {
        init_test("pending_task_without_wakeup_storm_still_counts_chaos_decision_point");

        let config =
            LabConfig::new(99).with_chaos(ChaosConfig::new(99).with_wakeup_storm_probability(0.0));
        let mut runtime = LabRuntime::new(config);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = runtime
            .state
            .create_task(region, Budget::INFINITE, async {
                std::future::pending::<()>().await;
            })
            .expect("create task");
        runtime.scheduler.lock().schedule(task_id, 0);

        runtime.step_for_test();

        let stats = runtime.chaos_stats();
        crate::assert_with_log!(
            stats.decision_points == 2,
            "pending-task decision point counted",
            2u64,
            stats.decision_points
        );
        crate::assert_with_log!(
            stats.wakeup_storms == 0,
            "no wakeup storm recorded",
            0u64,
            stats.wakeup_storms
        );

        crate::test_complete!(
            "pending_task_without_wakeup_storm_still_counts_chaos_decision_point"
        );
    }

    #[test]
    fn pre_poll_multi_injection_counts_one_chaos_decision_point() {
        init_test("pre_poll_multi_injection_counts_one_chaos_decision_point");

        let config = LabConfig::new(123).with_chaos(
            ChaosConfig::new(123)
                .with_cancel_probability(1.0)
                .with_delay_probability(1.0)
                .with_delay_range(Duration::ZERO..Duration::from_nanos(2))
                .with_budget_exhaust_probability(1.0),
        );
        let mut runtime = LabRuntime::new(config);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = runtime
            .state
            .create_task(region, Budget::INFINITE, async {
                std::future::pending::<()>().await;
            })
            .expect("create task");
        runtime.scheduler.lock().schedule(task_id, 0);

        runtime.step_for_test();

        let stats = runtime.chaos_stats();
        crate::assert_with_log!(
            stats.decision_points == 1,
            "multi-injection pre-poll counts once",
            1u64,
            stats.decision_points
        );
        crate::assert_with_log!(
            stats.cancellations == 1,
            "cancel recorded",
            1u64,
            stats.cancellations
        );
        crate::assert_with_log!(stats.delays == 1, "delay recorded", 1u64, stats.delays);
        crate::assert_with_log!(
            stats.budget_exhaustions == 1,
            "budget exhaust recorded",
            1u64,
            stats.budget_exhaustions
        );
        crate::assert_with_log!(
            stats.total_delay == Duration::from_nanos(1),
            "positive delay preserved",
            Duration::from_nanos(1),
            stats.total_delay
        );

        crate::test_complete!("pre_poll_multi_injection_counts_one_chaos_decision_point");
    }

    #[test]
    fn deterministic_rng() {
        init_test("deterministic_rng");
        let mut r1 = LabRuntime::with_seed(42);
        let mut r2 = LabRuntime::with_seed(42);

        let a = r1.rng.next_u64();
        let b = r2.rng.next_u64();
        crate::assert_with_log!(a == b, "rng", b, a);
        crate::test_complete!("deterministic_rng");
    }

    #[test]
    fn lab_scheduler_pop_for_worker_respects_timed_deadlines() {
        init_test("lab_scheduler_pop_for_worker_respects_timed_deadlines");
        let mut scheduler = LabScheduler::new(1, 0);
        let timed = TaskId::from_arena(ArenaIndex::new(1, 0));
        let ready = TaskId::from_arena(ArenaIndex::new(2, 0));

        scheduler.schedule_timed(timed, Time::from_nanos(100));
        scheduler.schedule(ready, 10);

        let first = scheduler.pop_for_worker(0, 0, Time::ZERO);
        crate::assert_with_log!(
            first == Some((ready, DispatchLane::Ready)),
            "ready task dispatches before not-due timed task",
            Some((ready, DispatchLane::Ready)),
            first
        );

        let second = scheduler.pop_for_worker(0, 1, Time::ZERO);
        crate::assert_with_log!(
            second.is_none(),
            "future timed task stays queued before deadline",
            true,
            second.is_none()
        );

        let third = scheduler.pop_for_worker(0, 2, Time::from_nanos(100));
        crate::assert_with_log!(
            third == Some((timed, DispatchLane::Timed)),
            "timed task dispatches at deadline",
            Some((timed, DispatchLane::Timed)),
            third
        );

        crate::test_complete!("lab_scheduler_pop_for_worker_respects_timed_deadlines");
    }

    #[test]
    fn forced_cancel_dispatch_preserves_normal_fairness_state() {
        init_test("forced_cancel_dispatch_preserves_normal_fairness_state");
        let task = TaskId::from_arena(ArenaIndex::new(3, 0));
        let mut normal = LabScheduler::new(1, 0);
        let mut forced = LabScheduler::new(1, 0);

        normal.cancel_streak[0] = normal.cancel_streak_limit;
        forced.cancel_streak[0] = forced.cancel_streak_limit;
        normal.schedule_cancel(task, 10);
        forced.schedule_cancel(task, 10);

        assert_eq!(
            normal.pop_for_worker(0, 0, Time::ZERO),
            Some((task, DispatchLane::Cancel))
        );
        forced
            .take_forced(task, 0, DispatchLane::Cancel, Time::ZERO, 0)
            .expect("forced cancel dispatch must remain available");

        assert_eq!(normal.cancel_streak[0], 1);
        assert_eq!(forced.cancel_streak[0], normal.cancel_streak[0]);
        crate::test_complete!("forced_cancel_dispatch_preserves_normal_fairness_state");
    }

    #[test]
    fn lab_scheduler_steal_for_worker_only_steals_ready_tasks() {
        init_test("lab_scheduler_steal_for_worker_only_steals_ready_tasks");
        let mut scheduler = LabScheduler::new(2, 0);
        let cancel = TaskId::from_arena(ArenaIndex::new(10, 0));
        let timed = TaskId::from_arena(ArenaIndex::new(11, 0));
        let ready = TaskId::from_arena(ArenaIndex::new(12, 0));

        // With 2 workers, assignment is round-robin: cancel->w0, timed->w1, ready->w0.
        scheduler.schedule_cancel(cancel, 100);
        scheduler.schedule_timed(timed, Time::ZERO);
        scheduler.schedule(ready, 50);

        let stolen = scheduler.steal_for_worker(1, 0);
        crate::assert_with_log!(
            stolen == Some(ready),
            "steal path takes only ready lane work",
            Some(ready),
            stolen
        );

        crate::assert_with_log!(
            scheduler.workers[0].has_cancel_work(),
            "victim cancel lane remains intact after steal",
            true,
            scheduler.workers[0].has_cancel_work()
        );

        let cancel_dispatch = scheduler.pop_for_worker(0, 0, Time::ZERO);
        crate::assert_with_log!(
            cancel_dispatch == Some((cancel, DispatchLane::Cancel)),
            "cancel lane still dispatches from victim worker",
            Some((cancel, DispatchLane::Cancel)),
            cancel_dispatch
        );

        let timed_dispatch = scheduler.pop_for_worker(1, 0, Time::ZERO);
        crate::assert_with_log!(
            timed_dispatch == Some((timed, DispatchLane::Timed)),
            "timed lane remains on owning worker",
            Some((timed, DispatchLane::Timed)),
            timed_dispatch
        );

        crate::test_complete!("lab_scheduler_steal_for_worker_only_steals_ready_tasks");
    }

    #[test]
    fn lab_scheduler_spurious_wakes_do_not_collapse_duplicates() {
        init_test("lab_scheduler_spurious_wakes_do_not_collapse_duplicates");
        let mut scheduler = LabScheduler::new(1, 0);
        let task = TaskId::from_arena(ArenaIndex::new(13, 0));

        scheduler.inject_spurious_wakes(task, 42, 3);

        let first = scheduler.pop_for_worker(0, 0, Time::ZERO);
        crate::assert_with_log!(
            first == Some((task, DispatchLane::Ready)),
            "first spurious wake dispatches",
            Some((task, DispatchLane::Ready)),
            first
        );

        let second = scheduler.pop_for_worker(0, 1, Time::ZERO);
        crate::assert_with_log!(
            second == Some((task, DispatchLane::Ready)),
            "second spurious wake remains queued",
            Some((task, DispatchLane::Ready)),
            second
        );

        let third = scheduler.pop_for_worker(0, 2, Time::ZERO);
        crate::assert_with_log!(
            third == Some((task, DispatchLane::Ready)),
            "third spurious wake remains queued",
            Some((task, DispatchLane::Ready)),
            third
        );

        let fourth = scheduler.pop_for_worker(0, 3, Time::ZERO);
        crate::assert_with_log!(
            fourth.is_none(),
            "storm drains after requested wake count",
            true,
            fourth.is_none()
        );
        crate::assert_with_log!(
            scheduler.is_empty(),
            "scheduler empty after spurious storm drains",
            true,
            scheduler.is_empty()
        );

        crate::test_complete!("lab_scheduler_spurious_wakes_do_not_collapse_duplicates");
    }

    #[test]
    fn lab_scheduler_forget_task_clears_pending_spurious_wakes() {
        init_test("lab_scheduler_forget_task_clears_pending_spurious_wakes");
        let mut scheduler = LabScheduler::new(1, 0);
        let task = TaskId::from_arena(ArenaIndex::new(14, 0));

        scheduler.inject_spurious_wakes(task, 42, 3);
        let first = scheduler.pop_for_worker(0, 0, Time::ZERO);
        crate::assert_with_log!(
            first == Some((task, DispatchLane::Ready)),
            "first spurious wake dispatches before forget",
            Some((task, DispatchLane::Ready)),
            first
        );

        scheduler.forget_task(task);

        let second = scheduler.pop_for_worker(0, 1, Time::ZERO);
        crate::assert_with_log!(
            second.is_none(),
            "forget_task drains queued spurious wakes",
            true,
            second.is_none()
        );
        crate::assert_with_log!(
            scheduler.pending_spurious_wakes.is_empty(),
            "forget_task clears pending spurious wake budget",
            true,
            scheduler.pending_spurious_wakes.is_empty()
        );
        crate::assert_with_log!(
            scheduler.is_empty(),
            "scheduler empty after forget_task",
            true,
            scheduler.is_empty()
        );

        crate::test_complete!("lab_scheduler_forget_task_clears_pending_spurious_wakes");
    }

    #[test]
    fn lab_scheduler_steal_preserves_pending_spurious_wakes() {
        init_test("lab_scheduler_steal_preserves_pending_spurious_wakes");
        let mut scheduler = LabScheduler::new(2, 0);
        let task = TaskId::from_arena(ArenaIndex::new(15, 0));

        scheduler.inject_spurious_wakes(task, 42, 3);

        let stolen = scheduler.steal_for_worker(1, 0);
        crate::assert_with_log!(
            stolen == Some(task),
            "steal dispatches first storm wake",
            Some(task),
            stolen
        );

        let second = scheduler.pop_for_worker(1, 1, Time::ZERO);
        crate::assert_with_log!(
            second == Some((task, DispatchLane::Ready)),
            "steal path re-arms second storm wake on thief worker",
            Some((task, DispatchLane::Ready)),
            second
        );

        let third = scheduler.pop_for_worker(1, 2, Time::ZERO);
        crate::assert_with_log!(
            third == Some((task, DispatchLane::Ready)),
            "steal path preserves final pending storm wake",
            Some((task, DispatchLane::Ready)),
            third
        );

        let fourth = scheduler.pop_for_worker(1, 3, Time::ZERO);
        crate::assert_with_log!(
            fourth.is_none(),
            "all stolen storm wakes drain after requested count",
            true,
            fourth.is_none()
        );
        crate::assert_with_log!(
            scheduler.is_empty(),
            "scheduler empty after stolen storm drains",
            true,
            scheduler.is_empty()
        );

        crate::test_complete!("lab_scheduler_steal_preserves_pending_spurious_wakes");
    }

    #[test]
    fn deterministic_multiworker_schedule() {
        init_test("deterministic_multiworker_schedule");
        let config = LabConfig::new(7).worker_count(4);

        crate::lab::assert_deterministic(config, |runtime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);
            for _ in 0..4 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async {
                        crate::runtime::yield_now::yield_now().await;
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }
            runtime.run_until_quiescent();
        });

        crate::test_complete!("deterministic_multiworker_schedule");
    }

    #[test]
    fn run_until_quiescent_with_report_is_deterministic() {
        init_test("run_until_quiescent_with_report_is_deterministic");

        let config = LabConfig::new(123).worker_count(4).max_steps(10_000);
        let mut r1 = LabRuntime::new(config.clone());
        let mut r2 = LabRuntime::new(config);

        let setup = |runtime: &mut LabRuntime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);
            for _ in 0..4 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async {
                        crate::runtime::yield_now::yield_now().await;
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }
        };

        setup(&mut r1);
        setup(&mut r2);

        let rep1 = r1.run_until_quiescent_with_report();
        let rep2 = r2.run_until_quiescent_with_report();

        crate::assert_with_log!(rep1.quiescent, "quiescent", true, rep1.quiescent);
        crate::assert_with_log!(rep2.quiescent, "quiescent", true, rep2.quiescent);

        assert_eq!(rep1.trace_fingerprint, rep2.trace_fingerprint);
        assert_eq!(rep1.trace_certificate, rep2.trace_certificate);
        assert_eq!(rep1.oracle_report.to_json(), rep2.oracle_report.to_json());
        assert_eq!(rep1.invariant_violations, rep2.invariant_violations);

        crate::assert_with_log!(
            rep1.oracle_report.all_passed(),
            "oracles passed",
            true,
            rep1.oracle_report.all_passed()
        );
        crate::assert_with_log!(
            rep2.oracle_report.all_passed(),
            "oracles passed",
            true,
            rep2.oracle_report.all_passed()
        );

        crate::test_complete!("run_until_quiescent_with_report_is_deterministic");
    }

    #[test]
    fn deadline_monitor_emits_warning() {
        init_test("deadline_monitor_emits_warning");
        let mut runtime = LabRuntime::with_seed(42);

        let warnings: Arc<Mutex<Vec<DeadlineWarning>>> = Arc::new(Mutex::new(Vec::new()));
        let warnings_clone = Arc::clone(&warnings);

        let config = MonitorConfig {
            check_interval: Duration::from_secs(0),
            warning_threshold_fraction: 1.0,
            checkpoint_timeout: Duration::from_secs(0),
            adaptive: AdaptiveDeadlineConfig::default(),
            enabled: true,
        };

        runtime.enable_deadline_monitoring_with_handler(config, move |warning| {
            warnings_clone.lock().push(warning);
        });

        let root = runtime.state.create_root_region(Budget::INFINITE);
        let budget = Budget::new().with_deadline(Time::from_millis(10));

        let task_idx = runtime.state.insert_task(TaskRecord::new_with_time(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            budget,
            runtime.state.now,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        let mut inner = CxInner::new(root, task_id, budget);
        inner.checkpoint_state.last_checkpoint = None;
        runtime
            .state
            .task_mut(task_id)
            .unwrap()
            .set_cx_inner(Arc::new(RwLock::new(inner)));

        runtime.step();

        let warnings = warnings.lock();
        let warning = warnings.first().expect("expected warning");
        crate::assert_with_log!(
            warning.task_id == task_id,
            "task_id",
            task_id,
            warning.task_id
        );
        crate::assert_with_log!(
            warning.region_id == root,
            "region_id",
            root,
            warning.region_id
        );
        let ok = matches!(
            warning.reason,
            WarningReason::ApproachingDeadline | WarningReason::ApproachingDeadlineNoProgress
        );
        crate::assert_with_log!(ok, "reason", true, ok);
        drop(warnings);
        crate::test_complete!("deadline_monitor_emits_warning");
    }

    #[test]
    fn deadline_monitor_e2e_stuck_detection() {
        init_test("deadline_monitor_e2e_stuck_detection");
        let mut runtime = LabRuntime::with_seed(42);

        let warnings: Arc<Mutex<Vec<DeadlineWarning>>> = Arc::new(Mutex::new(Vec::new()));
        let warnings_clone = Arc::clone(&warnings);

        let config = MonitorConfig {
            check_interval: Duration::ZERO,
            warning_threshold_fraction: 0.0,
            checkpoint_timeout: Duration::ZERO,
            adaptive: AdaptiveDeadlineConfig::default(),
            enabled: true,
        };

        runtime.enable_deadline_monitoring_with_handler(config, move |warning| {
            warnings_clone.lock().push(warning);
        });

        let root = runtime.state.create_root_region(Budget::INFINITE);
        let budget = Budget::new().with_deadline(Time::from_secs(10));
        let (task_id, _handle) = runtime
            .state
            .create_task(root, budget, async {})
            .expect("create task");

        {
            let task = runtime.state.task_mut(task_id).unwrap();
            let cx = task.cx.as_ref().expect("task cx");
            cx.checkpoint_with("starting work").expect("checkpoint");
        }

        runtime.step();

        let warnings = warnings.lock();
        let warning = warnings.first().expect("expected warning");
        crate::assert_with_log!(
            warning.task_id == task_id,
            "task_id",
            task_id,
            warning.task_id
        );
        crate::assert_with_log!(
            warning.reason == WarningReason::NoProgress,
            "reason",
            WarningReason::NoProgress,
            warning.reason
        );
        crate::assert_with_log!(
            warning.last_checkpoint_message.as_deref() == Some("starting work"),
            "checkpoint message",
            Some("starting work"),
            warning.last_checkpoint_message.as_deref()
        );
        drop(warnings);
        crate::test_complete!("deadline_monitor_e2e_stuck_detection");
    }

    #[test]
    fn futurelock_emits_trace_event() {
        init_test("futurelock_emits_trace_event");
        let config = LabConfig::new(42)
            .futurelock_max_idle_steps(3)
            .panic_on_futurelock(false);
        let mut runtime = LabRuntime::new(config);

        let root = runtime.state.create_root_region(Budget::INFINITE);

        // Create a task.
        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        // Create a pending obligation held by that task.
        let obl_id = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        for _ in 0..4 {
            runtime.step();
        }

        let futurelock = runtime
            .trace()
            .snapshot()
            .into_iter()
            .find(|e| e.kind == TraceEventKind::FuturelockDetected)
            .expect("expected futurelock trace event");

        match &futurelock.data {
            TraceData::Futurelock {
                task,
                region,
                idle_steps,
                held,
            } => {
                crate::assert_with_log!(*task == task_id, "task", task_id, *task);
                crate::assert_with_log!(*region == root, "region", root, *region);
                let idle_ok = *idle_steps > 3;
                crate::assert_with_log!(idle_ok, "idle_steps > 3", true, idle_ok);
                let ok = held.as_slice() == [(obl_id, ObligationKind::SendPermit)];
                crate::assert_with_log!(
                    ok,
                    "held",
                    &[(obl_id, ObligationKind::SendPermit)],
                    held.as_slice()
                );
            }
            other => panic!("unexpected trace data: {other:?}"),
        }
        crate::test_complete!("futurelock_emits_trace_event");
    }

    #[test]
    fn futurelock_display_includes_error_code() {
        init_test("futurelock_display_includes_error_code");
        let task = TaskId::from_arena(ArenaIndex::new(2, 0));
        let region = RegionId::from_arena(ArenaIndex::new(3, 0));
        let obligation = ObligationId::from_arena(ArenaIndex::new(4, 0));
        let violation = InvariantViolation::Futurelock {
            task,
            region,
            idle_steps: 8,
            held: vec![obligation],
            last_checkpoint_message: Some("waiting on permit".to_string()),
        };

        let rendered = violation.to_string();
        let has_code = rendered.starts_with("[ASUP-E402] futurelock:");
        crate::assert_with_log!(has_code, "futurelock display error code", true, has_code);
        crate::assert_with_log!(
            rendered.contains("idle=8"),
            "futurelock display idle steps",
            true,
            rendered.contains("idle=8")
        );
        crate::assert_with_log!(
            rendered.contains("last_checkpoint=\"waiting on permit\""),
            "futurelock display checkpoint message",
            true,
            rendered.contains("last_checkpoint=\"waiting on permit\"")
        );
        crate::test_complete!("futurelock_display_includes_error_code");
    }

    #[test]
    fn obligation_leak_display_includes_error_code_and_owner_facts() {
        init_test("obligation_leak_display_includes_error_code_and_owner_facts");
        let task = TaskId::from_arena(ArenaIndex::new(2, 0));
        let region = RegionId::from_arena(ArenaIndex::new(3, 0));
        let obligation = ObligationId::from_arena(ArenaIndex::new(4, 0));
        let violation = InvariantViolation::ObligationLeak {
            leaks: vec![ObligationLeak {
                obligation,
                kind: ObligationKind::SendPermit,
                holder: task,
                region,
            }],
        };

        let rendered = violation.to_string();
        let has_code = rendered.starts_with("[ASUP-E101] obligation leak:");
        crate::assert_with_log!(
            has_code,
            "obligation leak display error code",
            true,
            has_code
        );
        crate::assert_with_log!(
            rendered.contains("count=1"),
            "obligation leak display count",
            true,
            rendered.contains("count=1")
        );
        crate::assert_with_log!(
            rendered.contains("obligation="),
            "obligation leak display obligation id",
            true,
            rendered.contains("obligation=")
        );
        crate::assert_with_log!(
            rendered.contains("kind=SendPermit"),
            "obligation leak display kind",
            true,
            rendered.contains("kind=SendPermit")
        );
        crate::assert_with_log!(
            rendered.contains("holder="),
            "obligation leak display holder",
            true,
            rendered.contains("holder=")
        );
        crate::assert_with_log!(
            rendered.contains("region="),
            "obligation leak display region",
            true,
            rendered.contains("region=")
        );
        crate::test_complete!("obligation_leak_display_includes_error_code_and_owner_facts");
    }

    #[test]
    fn futurelock_panic_includes_last_checkpoint_message() {
        init_test("futurelock_panic_includes_last_checkpoint_message");
        let config = LabConfig::new(42)
            .futurelock_max_idle_steps(1)
            .panic_on_futurelock(true);
        let mut runtime = LabRuntime::new(config);

        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        runtime
            .state
            .task(task_id)
            .expect("task")
            .cx
            .as_ref()
            .expect("task cx")
            .checkpoint_with("waiting on downstream permit")
            .expect("checkpoint");

        let _ = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            for _ in 0..3 {
                runtime.step();
            }
        }));
        let payload = result.expect_err("futurelock should panic");
        let message = if let Some(message) = payload.downcast_ref::<String>() {
            message.clone()
        } else if let Some(message) = payload.downcast_ref::<&str>() {
            (*message).to_string()
        } else {
            String::from("<non-string panic>")
        };

        crate::assert_with_log!(
            message.contains("[ASUP-E402] futurelock detected"),
            "futurelock panic error code",
            true,
            message.contains("[ASUP-E402] futurelock detected")
        );
        crate::assert_with_log!(
            message.contains("last_checkpoint=\"waiting on downstream permit\""),
            "futurelock panic checkpoint message",
            true,
            message.contains("last_checkpoint=\"waiting on downstream permit\"")
        );
        crate::assert_with_log!(
            message.contains("seed=42"),
            "futurelock panic seed",
            true,
            message.contains("seed=42")
        );
        crate::test_complete!("futurelock_panic_includes_last_checkpoint_message");
    }

    #[test]
    #[should_panic(expected = "[ASUP-E402] futurelock detected")]
    fn futurelock_can_panic() {
        init_test("futurelock_can_panic");
        let config = LabConfig::new(42).futurelock_max_idle_steps(1);
        let mut runtime = LabRuntime::new(config);

        let root = runtime.state.create_root_region(Budget::INFINITE);

        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        let _ = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        // Run enough steps to exceed threshold and trigger panic.
        for _ in 0..3 {
            runtime.step();
        }
    }

    /// Regression test: actively polled tasks must NOT be flagged as futurelocked.
    ///
    /// Before the fix, `mark_polled()` was never called from `step()`, so
    /// `last_polled_step` stayed at 0. After threshold+1 steps, even a
    /// task polled every single step would be falsely flagged.
    #[test]
    fn polled_task_not_flagged_as_futurelocked() {
        init_test("polled_task_not_flagged_as_futurelocked");
        let config = LabConfig::new(42)
            .futurelock_max_idle_steps(5)
            .panic_on_futurelock(false);
        let mut runtime = LabRuntime::new(config);

        let root = runtime.state.create_root_region(Budget::INFINITE);

        // Create a task with a stored future that always yields (Pending).
        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {
                loop {
                    crate::runtime::yield_now::yield_now().await;
                }
            })
            .expect("create task");

        // Give the task a pending obligation so it's eligible for futurelock.
        let _obl = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        // Schedule and run well past the threshold.
        runtime.scheduler.lock().schedule(task_id, 0);
        for _ in 0..20 {
            runtime.step();
        }

        // The task was polled every step, so no futurelock should fire.
        let violations = runtime.futurelock_violations();
        crate::assert_with_log!(
            violations.is_empty(),
            "no futurelock for actively polled task",
            true,
            violations.is_empty()
        );
        crate::test_complete!("polled_task_not_flagged_as_futurelocked");
    }

    #[test]
    fn immediate_completion_marks_running_before_completion() {
        init_test("immediate_completion_marks_running_before_completion");
        let mut runtime = LabRuntime::new(LabConfig::new(42));
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, _) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        runtime.scheduler.lock().schedule(task_id, 0);

        runtime.run_until_quiescent();

        let protocol_ok = runtime.check_cancellation_protocol().is_ok();
        crate::assert_with_log!(
            runtime.is_quiescent(),
            "runtime reached quiescence after immediate completion",
            true,
            runtime.is_quiescent()
        );
        crate::assert_with_log!(
            protocol_ok,
            "cancellation oracle accepted Created -> Running -> Completed",
            true,
            protocol_ok
        );

        crate::test_complete!("immediate_completion_marks_running_before_completion");
    }

    #[test]
    fn obligation_leak_detected_when_holder_completed() {
        init_test("obligation_leak_detected_when_holder_completed");
        let mut runtime = LabRuntime::with_seed(7);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        let obl_id = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        runtime
            .state
            .update_task(task_id, |record| record.complete(Outcome::Ok(())))
            .unwrap();

        let violations = runtime.check_invariants();
        let mut found = false;
        for violation in violations {
            if let InvariantViolation::ObligationLeak { leaks } = violation {
                found = true;
                let len = leaks.len();
                crate::assert_with_log!(len == 1, "leaks len", 1, len);
                let leak = &leaks[0];
                crate::assert_with_log!(
                    leak.obligation == obl_id,
                    "obligation",
                    obl_id,
                    leak.obligation
                );
                crate::assert_with_log!(
                    leak.kind == ObligationKind::SendPermit,
                    "kind",
                    ObligationKind::SendPermit,
                    leak.kind
                );
                crate::assert_with_log!(leak.holder == task_id, "holder", task_id, leak.holder);
                crate::assert_with_log!(leak.region == root, "region", root, leak.region);
            }
        }
        crate::assert_with_log!(found, "found leak", true, found);
        crate::test_complete!("obligation_leak_detected_when_holder_completed");
    }

    #[test]
    fn obligation_leak_ignored_when_resolved() {
        init_test("obligation_leak_ignored_when_resolved");
        let mut runtime = LabRuntime::with_seed(11);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        let obl_id = runtime
            .state
            .create_obligation(ObligationKind::Ack, task_id, root, None)
            .expect("create obligation");
        runtime
            .state
            .commit_obligation(obl_id)
            .expect("commit obligation");

        runtime
            .state
            .update_task(task_id, |record| record.complete(Outcome::Ok(())))
            .unwrap();

        let violations = runtime.check_invariants();
        let has_leak = violations
            .iter()
            .any(|v| matches!(v, InvariantViolation::ObligationLeak { .. }));
        crate::assert_with_log!(!has_leak, "no leak", false, has_leak);
        crate::test_complete!("obligation_leak_ignored_when_resolved");
    }

    #[test]
    fn report_hydrates_temporal_oracles_from_state_snapshot() {
        init_test("report_hydrates_temporal_oracles_from_state_snapshot");
        let mut runtime = LabRuntime::with_seed(31);
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (_task, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");

        // Force-close the region while a task is still live to simulate a
        // temporal invariant break that must be surfaced by report hydration.
        runtime
            .state
            .region(root)
            .expect("region exists")
            .set_state(crate::record::region::RegionState::Closed);

        let report = runtime.report();
        let task_leak = report
            .oracle_report
            .entry("task_leak")
            .expect("task_leak entry");
        let quiescence = report
            .oracle_report
            .entry("quiescence")
            .expect("quiescence entry");

        crate::assert_with_log!(
            !task_leak.passed,
            "task_leak failed",
            false,
            task_leak.passed
        );
        crate::assert_with_log!(
            !quiescence.passed,
            "quiescence failed",
            false,
            quiescence.passed
        );
        let has_temporal_tag = report
            .invariant_violations
            .iter()
            .any(|v| v == "temporal:task_leak");
        crate::assert_with_log!(
            has_temporal_tag,
            "temporal marker present",
            true,
            has_temporal_tag
        );
        let temporal_failed = report
            .temporal_invariant_failures
            .iter()
            .any(|v| v == "task_leak");
        crate::assert_with_log!(
            temporal_failed,
            "temporal failure surfaced",
            true,
            temporal_failed
        );
        crate::test_complete!("report_hydrates_temporal_oracles_from_state_snapshot");
    }

    #[test]
    fn report_hydrates_quiescence_from_finalizers_and_obligations() {
        init_test("report_hydrates_quiescence_from_finalizers_and_obligations");
        let mut runtime = LabRuntime::with_seed(32);
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");

        runtime.state.now = Time::from_nanos(10);
        let registered = runtime.state.register_sync_finalizer(root, || {});
        crate::assert_with_log!(registered, "registered finalizer", true, registered);

        runtime.state.now = Time::from_nanos(20);
        let _obligation = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        runtime.state.now = Time::from_nanos(30);
        runtime
            .state
            .update_task(task_id, |record| record.complete(Outcome::Ok(())))
            .expect("complete task without auto-resolving obligation");

        runtime.state.now = Time::from_nanos(40);
        runtime.state.record_finalizer_close_for_test(root);
        runtime
            .state
            .region(root)
            .expect("region exists")
            .set_state(crate::record::region::RegionState::Closed);

        let report = runtime.report();
        let quiescence = report
            .oracle_report
            .entry("quiescence")
            .expect("quiescence entry");
        let finalizer = report
            .oracle_report
            .entry("finalizer")
            .expect("finalizer entry");
        let obligation_leak = report
            .oracle_report
            .entry("obligation_leak")
            .expect("obligation entry");

        crate::assert_with_log!(
            !quiescence.passed,
            "quiescence failed",
            false,
            quiescence.passed
        );
        let quiescence_text = quiescence
            .violation
            .as_deref()
            .expect("quiescence violation text");
        crate::assert_with_log!(
            quiescence_text.contains("1 unrun finalizers"),
            "quiescence mentions finalizers",
            true,
            quiescence_text.contains("1 unrun finalizers")
        );
        crate::assert_with_log!(
            quiescence_text.contains("1 leaked obligations"),
            "quiescence mentions obligations",
            true,
            quiescence_text.contains("1 leaked obligations")
        );
        crate::assert_with_log!(
            !finalizer.passed,
            "finalizer failed",
            false,
            finalizer.passed
        );
        crate::assert_with_log!(
            !obligation_leak.passed,
            "obligation_leak failed",
            false,
            obligation_leak.passed
        );
        for failed in report.oracle_report.failures() {
            let marker = format!("oracle:{}", failed.invariant);
            crate::assert_with_log!(
                report.invariant_violations.contains(&marker),
                "every failed oracle has aggregate marker",
                true,
                report.invariant_violations.contains(&marker)
            );
        }
        crate::test_complete!("report_hydrates_quiescence_from_finalizers_and_obligations");
    }

    #[test]
    fn report_hydrates_cancellation_propagation_from_state_snapshot() {
        init_test("report_hydrates_cancellation_propagation_from_state_snapshot");
        // This test intentionally drives a cancellation-propagation violation
        // to verify it surfaces in the temporal report. Default configs panic
        // on such violations during `report()`, so the oracle must be allowed
        // to merely *record* the violation instead of aborting the test.
        let config = LabConfig::new(32).panic_on_cancellation_violation(false);
        let mut runtime = LabRuntime::new(config);
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let _child = runtime
            .state
            .create_child_region(root, Budget::INFINITE)
            .expect("create child");

        runtime
            .state
            .region(root)
            .expect("root exists")
            .cancel_request(crate::types::CancelReason::shutdown());

        let report = runtime.report();
        let cancellation = report
            .oracle_report
            .entry("cancellation_protocol")
            .expect("cancellation_protocol entry");
        crate::assert_with_log!(
            !cancellation.passed,
            "cancellation_protocol failed",
            false,
            cancellation.passed
        );
        let has_temporal_tag = report
            .invariant_violations
            .iter()
            .any(|v| v == "temporal:cancellation_protocol");
        crate::assert_with_log!(
            has_temporal_tag,
            "temporal cancellation marker present",
            true,
            has_temporal_tag
        );
        crate::test_complete!("report_hydrates_cancellation_propagation_from_state_snapshot");
    }

    #[test]
    fn report_surfaces_refinement_firewall_violation_from_trace_snapshot() {
        init_test("report_surfaces_refinement_firewall_violation_from_trace_snapshot");
        let mut runtime = LabRuntime::with_seed(33);
        let region = RegionId::new_for_test(41, 0);
        let task = TaskId::new_for_test(7, 0);

        runtime
            .state
            .trace
            .push_event(TraceEvent::spawn(1, Time::ZERO, task, region));
        runtime
            .state
            .trace
            .push_event(TraceEvent::spawn(2, Time::ZERO, task, region));

        let report = runtime.report();
        crate::assert_with_log!(
            report.refinement_firewall_rule_id.as_deref() == Some("RFW-SPAWN-001"),
            "refinement rule id surfaced",
            Some("RFW-SPAWN-001"),
            report.refinement_firewall_rule_id.as_deref()
        );
        crate::assert_with_log!(
            report.refinement_firewall_event_index == Some(1),
            "refinement event index surfaced",
            Some(1usize),
            report.refinement_firewall_event_index
        );
        crate::assert_with_log!(
            report.refinement_counterexample_prefix_len == Some(2),
            "refinement prefix len surfaced",
            Some(2usize),
            report.refinement_counterexample_prefix_len
        );
        let has_marker = report
            .invariant_violations
            .iter()
            .any(|v| v == "refinement_firewall:RFW-SPAWN-001");
        crate::assert_with_log!(
            has_marker,
            "refinement invariant marker present",
            true,
            has_marker
        );
        let json = report.to_json();
        crate::assert_with_log!(
            json["refinement_firewall"]["rule_id"] == "RFW-SPAWN-001",
            "refinement json rule id",
            "RFW-SPAWN-001",
            json["refinement_firewall"]["rule_id"]
        );
        crate::assert_with_log!(
            json["refinement_firewall"]["counterexample_prefix_len"] == 2,
            "refinement json prefix len",
            2,
            json["refinement_firewall"]["counterexample_prefix_len"]
        );
        crate::assert_with_log!(
            json["refinement_firewall"]["skipped_due_to_trace_truncation"] == false,
            "refinement json not skipped",
            false,
            json["refinement_firewall"]["skipped_due_to_trace_truncation"]
        );
        crate::test_complete!("report_surfaces_refinement_firewall_violation_from_trace_snapshot");
    }

    // br-asupersync-9ri7x0: trace truncation no longer silently
    // disables the refinement-firewall oracle. The flag remains set
    // (it is part of the report contract) and the rule_id is None
    // because the firewall did not run, but the scenario must now
    // surface a hard 'scenario_failed_due_to_trace_truncation'
    // invariant_violations entry so any caller that gates on
    // invariant_violations.is_empty() will fail loudly. The seed and
    // truncation watermark are embedded in the message so an
    // operator can immediately bump trace_capacity or split the
    // scenario.
    #[test]
    fn report_fails_loudly_when_trace_buffer_is_truncated_l9ri7x0() {
        init_test("report_fails_loudly_when_trace_buffer_is_truncated_l9ri7x0");
        let seed = 35;
        let config = LabConfig::new(seed).trace_capacity(1);
        let mut runtime = LabRuntime::new(config);
        let region = RegionId::new_for_test(43, 0);
        let task = TaskId::new_for_test(9, 0);

        runtime
            .state
            .trace
            .push_event(TraceEvent::spawn(1, Time::ZERO, task, region));
        runtime
            .state
            .trace
            .push_event(TraceEvent::complete(2, Time::ZERO, task, region));

        let report = runtime.report();
        crate::assert_with_log!(
            report.refinement_firewall_skipped_due_to_trace_truncation,
            "refinement_firewall_skipped_due_to_trace_truncation",
            true,
            report.refinement_firewall_skipped_due_to_trace_truncation
        );
        crate::assert_with_log!(
            report.refinement_firewall_rule_id.is_none(),
            "no real rule_id when firewall could not run",
            true,
            report.refinement_firewall_rule_id.is_none()
        );

        // The new contract: invariant_violations MUST contain a
        // hard-fail marker that names the truncation cause + seed +
        // watermark. The substring is checked rather than equality
        // so future format adjustments stay backward-compatible.
        let truncation_marker = report
            .invariant_violations
            .iter()
            .find(|v| v.starts_with("refinement_firewall:scenario_failed_due_to_trace_truncation"));
        let marker = truncation_marker.expect(
            "truncation must surface as a hard refinement_firewall:scenario_failed_due_to_trace_truncation marker",
        );
        assert!(
            marker.contains(&format!("seed={seed}")),
            "truncation marker must embed the seed, got: {marker}"
        );
        assert!(
            marker.contains("total_pushed=") && marker.contains("buffered="),
            "truncation marker must embed total_pushed + buffered watermark, got: {marker}"
        );
        // And of course the scenario must NOT report 'passed':
        // invariant_violations.is_empty() is the standard pass gate.
        crate::assert_with_log!(
            !report.invariant_violations.is_empty(),
            "scenario must fail loudly when trace buffer truncates",
            true,
            !report.invariant_violations.is_empty()
        );

        let json = report.to_json();
        crate::assert_with_log!(
            json["refinement_firewall"]["skipped_due_to_trace_truncation"] == true,
            "skipped flag still serialized for downstream tooling",
            true,
            json["refinement_firewall"]["skipped_due_to_trace_truncation"]
        );
        crate::test_complete!("report_fails_loudly_when_trace_buffer_is_truncated_l9ri7x0");
    }

    // br-asupersync-7uu7sa: chaos-injected wakeup_storm must be
    // suppressed when the targeted task's owning region has already
    // transitioned to Closing/Draining/Closed. Drives the inner
    // method directly, then drives it again after flipping the
    // owning region's state to Closing — the second call must NOT
    // schedule the task.
    #[test]
    fn inject_spurious_wakes_suppressed_when_owning_region_is_closing_l7uu7sa() {
        init_test("inject_spurious_wakes_suppressed_when_owning_region_is_closing_l7uu7sa");

        let mut runtime = LabRuntime::with_seed(42);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let task_idx = runtime.state.insert_task(TaskRecord::new_with_time(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            region,
            Budget::INFINITE,
            runtime.state.now,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        // Region is Open: the inner method must schedule the task.
        runtime.inject_spurious_wakes(task_id, 0, 2);
        let scheduled_open = {
            let mut sched = runtime.scheduler.lock();
            let mut count = 0u32;
            while sched.pop_for_worker(0, count.into(), Time::ZERO).is_some() {
                count += 1;
            }
            count
        };
        crate::assert_with_log!(
            scheduled_open == 2,
            "while region is Open, 2 spurious wakes are scheduled",
            2u32,
            scheduled_open
        );

        // Transition the region into a non-accepting state.
        runtime
            .state
            .region(region)
            .expect("region exists")
            .set_state(crate::record::region::RegionState::Closing);

        // Now the call must be silently suppressed — no work on the queue.
        runtime.inject_spurious_wakes(task_id, 0, 5);
        let scheduled_closing = {
            let mut sched = runtime.scheduler.lock();
            let mut count = 0u32;
            while sched.pop_for_worker(0, count.into(), Time::ZERO).is_some() {
                count += 1;
            }
            count
        };
        crate::assert_with_log!(
            scheduled_closing == 0,
            "after region.set_state(Closing), spurious wakes are suppressed",
            0u32,
            scheduled_closing
        );

        // Defense-in-depth: walk every other terminal-ish state.
        for state in [
            crate::record::region::RegionState::Draining,
            crate::record::region::RegionState::Closed,
        ] {
            runtime
                .state
                .region(region)
                .expect("region exists")
                .set_state(state);
            runtime.inject_spurious_wakes(task_id, 0, 3);
            let scheduled = {
                let mut sched = runtime.scheduler.lock();
                let mut count = 0u32;
                while sched.pop_for_worker(0, count.into(), Time::ZERO).is_some() {
                    count += 1;
                }
                count
            };
            assert_eq!(
                scheduled, 0,
                "spurious wakes must be suppressed in region state {state:?}"
            );
        }

        crate::test_complete!(
            "inject_spurious_wakes_suppressed_when_owning_region_is_closing_l7uu7sa"
        );
    }

    #[test]
    fn crashpack_includes_refinement_firewall_markers() {
        init_test("crashpack_includes_refinement_firewall_markers");
        let mut runtime = LabRuntime::with_seed(34);
        let region = RegionId::new_for_test(42, 0);
        let task = TaskId::new_for_test(8, 0);

        runtime
            .state
            .trace
            .push_event(TraceEvent::spawn(1, Time::ZERO, task, region));
        runtime
            .state
            .trace
            .push_event(TraceEvent::spawn(2, Time::ZERO, task, region));

        let run = runtime.report();
        let crashpack = runtime
            .build_crashpack_for_report(&run)
            .expect("refinement-firewall failure should build crashpack");
        let has_rule_marker = crashpack
            .oracle_violations
            .iter()
            .any(|entry| entry == "refinement_firewall:RFW-SPAWN-001");
        crate::assert_with_log!(
            has_rule_marker,
            "crashpack includes refinement rule marker",
            true,
            has_rule_marker
        );
        let has_prefix_marker = crashpack
            .oracle_violations
            .iter()
            .any(|entry| entry == "refinement_firewall:minimal_counterexample_prefix_len=2");
        crate::assert_with_log!(
            has_prefix_marker,
            "crashpack includes refinement prefix marker",
            true,
            has_prefix_marker
        );
        crate::test_complete!("crashpack_includes_refinement_firewall_markers");
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn obligation_trace_events_emitted() {
        init_test("obligation_trace_events_emitted");
        let mut runtime = LabRuntime::with_seed(21);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        runtime.advance_time_to(Time::from_nanos(10));
        let ob1 = runtime
            .state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .unwrap();

        runtime.advance_time_to(Time::from_nanos(25));
        runtime.state.commit_obligation(ob1).unwrap();

        runtime.advance_time_to(Time::from_nanos(30));
        let ob2 = runtime
            .state
            .create_obligation(ObligationKind::Ack, task_id, root, None)
            .unwrap();

        runtime.advance_time_to(Time::from_nanos(50));
        runtime
            .state
            .abort_obligation(ob2, ObligationAbortReason::Cancel)
            .unwrap();

        let commit_event = runtime
            .trace()
            .snapshot()
            .into_iter()
            .find(|e| e.kind == TraceEventKind::ObligationCommit)
            .expect("commit event");
        match &commit_event.data {
            TraceData::Obligation {
                obligation,
                task,
                region,
                kind,
                state,
                duration_ns,
                abort_reason,
            } => {
                crate::assert_with_log!(*obligation == ob1, "obligation", ob1, *obligation);
                crate::assert_with_log!(*task == task_id, "task", task_id, *task);
                crate::assert_with_log!(*region == root, "region", root, *region);
                crate::assert_with_log!(
                    *kind == ObligationKind::SendPermit,
                    "kind",
                    ObligationKind::SendPermit,
                    *kind
                );
                crate::assert_with_log!(
                    *state == crate::record::ObligationState::Committed,
                    "state",
                    crate::record::ObligationState::Committed,
                    *state
                );
                crate::assert_with_log!(
                    duration_ns == &Some(15),
                    "duration",
                    &Some(15),
                    duration_ns
                );
                crate::assert_with_log!(
                    abort_reason.is_none(),
                    "abort_reason",
                    &None::<crate::record::ObligationAbortReason>,
                    abort_reason
                );
            }
            other => panic!("unexpected commit data: {other:?}"),
        }

        let abort_event = runtime
            .trace()
            .snapshot()
            .into_iter()
            .find(|e| e.kind == TraceEventKind::ObligationAbort)
            .expect("abort event");
        match &abort_event.data {
            TraceData::Obligation {
                obligation,
                task,
                region,
                kind,
                state,
                duration_ns,
                abort_reason,
            } => {
                crate::assert_with_log!(*obligation == ob2, "obligation", ob2, *obligation);
                crate::assert_with_log!(*task == task_id, "task", task_id, *task);
                crate::assert_with_log!(*region == root, "region", root, *region);
                crate::assert_with_log!(
                    *kind == ObligationKind::Ack,
                    "kind",
                    ObligationKind::Ack,
                    *kind
                );
                crate::assert_with_log!(
                    *state == crate::record::ObligationState::Aborted,
                    "state",
                    crate::record::ObligationState::Aborted,
                    *state
                );
                crate::assert_with_log!(
                    duration_ns == &Some(20),
                    "duration",
                    &Some(20),
                    duration_ns
                );
                crate::assert_with_log!(
                    abort_reason == &Some(ObligationAbortReason::Cancel),
                    "abort_reason",
                    &Some(ObligationAbortReason::Cancel),
                    abort_reason
                );
            }
            other => panic!("unexpected abort data: {other:?}"),
        }
        crate::test_complete!("obligation_trace_events_emitted");
    }

    #[test]
    fn obligation_leak_emits_trace_event() {
        init_test("obligation_leak_emits_trace_event");
        let mut runtime = LabRuntime::with_seed(22);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let task_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            root,
            Budget::INFINITE,
        ));
        let task_id = TaskId::from_arena(task_idx);
        runtime.state.task_mut(task_id).unwrap().id = task_id;

        runtime.advance_time_to(Time::from_nanos(100));
        let obligation = runtime
            .state
            .create_obligation(ObligationKind::Lease, task_id, root, None)
            .unwrap();

        runtime.advance_time_to(Time::from_nanos(140));
        runtime
            .state
            .update_task(task_id, |record| record.complete(Outcome::Ok(())))
            .unwrap();

        let violations = runtime.check_invariants();
        let has_leak = violations
            .iter()
            .any(|v| matches!(v, InvariantViolation::ObligationLeak { .. }));
        crate::assert_with_log!(has_leak, "has leak", true, has_leak);

        let leak_event = runtime
            .trace()
            .snapshot()
            .into_iter()
            .find(|e| e.kind == TraceEventKind::ObligationLeak)
            .expect("leak event");
        match &leak_event.data {
            TraceData::Obligation {
                obligation: leaked,
                task,
                region,
                kind,
                state,
                duration_ns,
                abort_reason,
            } => {
                crate::assert_with_log!(*leaked == obligation, "obligation", obligation, *leaked);
                crate::assert_with_log!(*task == task_id, "task", task_id, *task);
                crate::assert_with_log!(*region == root, "region", root, *region);
                crate::assert_with_log!(
                    *kind == ObligationKind::Lease,
                    "kind",
                    ObligationKind::Lease,
                    *kind
                );
                crate::assert_with_log!(
                    *state == crate::record::ObligationState::Leaked,
                    "state",
                    crate::record::ObligationState::Leaked,
                    *state
                );
                crate::assert_with_log!(
                    duration_ns == &Some(40),
                    "duration",
                    &Some(40),
                    duration_ns
                );
                crate::assert_with_log!(
                    abort_reason.is_none(),
                    "abort_reason",
                    &None::<crate::record::ObligationAbortReason>,
                    abort_reason
                );
            }
            other => panic!("unexpected leak data: {other:?}"),
        }
        crate::test_complete!("obligation_leak_emits_trace_event");
    }

    // =========================================================================
    // Agent Report Contract tests (bd-f262i)
    // =========================================================================

    /// The JSON schema must contain all required top-level keys.
    #[test]
    fn contract_json_has_required_top_level_keys() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_json_has_required_top_level_keys");

        let app = crate::app::AppSpec::new("contract_test");
        let harness = crate::lab::SporkAppHarness::with_seed(42, app).unwrap();
        let report = harness.run_to_report().unwrap();
        let json = report.to_json();

        // Required top-level keys per bd-f262i contract.
        let required_keys = [
            "schema_version",
            "verdict",
            "app",
            "lab",
            "fingerprints",
            "run",
            "crashpack",
            "attachments",
        ];
        for key in &required_keys {
            assert!(
                json.get(key).is_some(),
                "missing required top-level key: {key}"
            );
        }

        // Nested required keys.
        assert!(json["app"]["name"].is_string(), "app.name must be a string");
        assert!(
            json["lab"]["config"].is_object(),
            "lab.config must be an object"
        );
        assert!(
            json["lab"]["config_hash"].is_u64(),
            "lab.config_hash must be a u64"
        );
        assert!(
            json["fingerprints"]["trace"].is_u64(),
            "fingerprints.trace must be a u64"
        );
        assert!(
            json["fingerprints"]["event_hash"].is_u64(),
            "fingerprints.event_hash must be a u64"
        );
        assert!(
            json["fingerprints"]["event_count"].is_u64(),
            "fingerprints.event_count must be a u64"
        );
        assert!(
            json["fingerprints"]["schedule_hash"].is_u64(),
            "fingerprints.schedule_hash must be a u64"
        );
        assert!(json["run"]["seed"].is_u64(), "run.seed must be a u64");
        assert!(
            json["run"]["oracles"].is_object(),
            "run.oracles must be an object"
        );
        assert!(
            json["run"]["invariants"].is_array(),
            "run.invariants must be an array"
        );
        assert!(
            json["run"]["refinement_firewall"].is_object(),
            "run.refinement_firewall must be an object"
        );
        assert!(
            json["run"]["refinement_firewall"]["skipped_due_to_trace_truncation"].is_boolean(),
            "run.refinement_firewall.skipped_due_to_trace_truncation must be a boolean"
        );
        assert!(
            json["attachments"].is_array(),
            "attachments must be an array"
        );
        assert!(
            json["crashpack"].is_null(),
            "passing runs should have null crashpack linkage"
        );

        crate::test_complete!("contract_json_has_required_top_level_keys");
    }

    /// Schema version must be the current constant.
    #[test]
    fn contract_schema_version_is_current() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_schema_version_is_current");

        let app = crate::app::AppSpec::new("version_test");
        let harness = crate::lab::SporkAppHarness::with_seed(1, app).unwrap();
        let report = harness.run_to_report().unwrap();

        assert_eq!(report.schema_version, SporkHarnessReport::SCHEMA_VERSION);
        assert_eq!(
            report.to_json()["schema_version"],
            SporkHarnessReport::SCHEMA_VERSION
        );

        crate::test_complete!("contract_schema_version_is_current");
    }

    /// Config hash is deterministic: same config -> same hash.
    #[test]
    fn contract_config_hash_deterministic() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_config_hash_deterministic");

        let config = LabConfig::new(42);
        let summary_a = LabConfigSummary::from_config(&config);
        let summary_b = LabConfigSummary::from_config(&config);

        assert_eq!(summary_a.config_hash(), summary_b.config_hash());

        // Different seed -> different hash.
        let config_2 = LabConfig::new(99);
        let summary_c = LabConfigSummary::from_config(&config_2);
        assert_ne!(summary_a.config_hash(), summary_c.config_hash());

        crate::test_complete!("contract_config_hash_deterministic");
    }

    /// Verdict field correctly reflects pass/fail.
    #[test]
    fn contract_verdict_reflects_oracle_state() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_verdict_reflects_oracle_state");

        let app = crate::app::AppSpec::new("verdict_test");
        let harness = crate::lab::SporkAppHarness::with_seed(42, app).unwrap();
        let report = harness.run_to_report().unwrap();

        // Empty app should pass.
        assert!(report.passed());
        assert_eq!(report.to_json()["verdict"], "pass");
        assert!(report.summary_line().starts_with("[PASS]"));

        let mut truncated = report.clone();
        truncated.run.quiescent = false;
        assert!(!truncated.passed());
        assert_eq!(truncated.to_json()["verdict"], "fail");
        assert!(truncated.summary_line().starts_with("[FAIL]"));
        let runtime = LabRuntime::with_seed(42);
        assert!(runtime.build_crashpack_for_report(&truncated.run).is_some());

        crate::test_complete!("contract_verdict_reflects_oracle_state");
    }

    #[test]
    fn crashpack_prefers_failed_terminal_task_over_live_task() {
        init_test("crashpack_prefers_failed_terminal_task_over_live_task");
        let mut runtime = LabRuntime::with_seed(0x4b_78);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let live_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::testing_default(),
            root,
            Budget::INFINITE,
        ));
        let live_task = TaskId::from_arena(live_idx);
        runtime.state.task_mut(live_task).unwrap().id = live_task;

        let failed_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::testing_default(),
            root,
            Budget::INFINITE,
        ));
        let failed_task = TaskId::from_arena(failed_idx);
        runtime.state.task_mut(failed_task).unwrap().id = failed_task;
        runtime
            .state
            .update_task(failed_task, |record| {
                record.complete(Outcome::Panicked(crate::types::PanicPayload::new(
                    "intentional crashpack attribution panic",
                )))
            })
            .expect("complete failed task");

        let report = runtime.report();
        let crashpack = runtime
            .build_crashpack_for_report(&report)
            .expect("live task should make the report fail");
        assert_eq!(crashpack.failure.task, failed_task);
        assert_eq!(crashpack.failure.region, root);
        assert!(matches!(
            crashpack.failure.outcome,
            FailureOutcome::Panicked { ref message }
                if message == "intentional crashpack attribution panic"
        ));
        crate::test_complete!("crashpack_prefers_failed_terminal_task_over_live_task");
    }

    #[test]
    fn crashpack_preserves_cancelled_terminal_task_kind() {
        init_test("crashpack_preserves_cancelled_terminal_task_kind");
        let mut runtime = LabRuntime::with_seed(0x4b_79);
        let root = runtime.state.create_root_region(Budget::INFINITE);

        let live_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::testing_default(),
            root,
            Budget::INFINITE,
        ));
        let live_task = TaskId::from_arena(live_idx);
        runtime.state.task_mut(live_task).unwrap().id = live_task;

        let cancelled_idx = runtime.state.insert_task(TaskRecord::new(
            TaskId::testing_default(),
            root,
            Budget::INFINITE,
        ));
        let cancelled_task = TaskId::from_arena(cancelled_idx);
        runtime.state.task_mut(cancelled_task).unwrap().id = cancelled_task;
        runtime
            .state
            .update_task(cancelled_task, |record| {
                record.complete(Outcome::Cancelled(crate::types::CancelReason::timeout()))
            })
            .expect("complete cancelled task");

        let report = runtime.report();
        let crashpack = runtime
            .build_crashpack_for_report(&report)
            .expect("live task should make the report fail");
        assert_eq!(crashpack.failure.task, cancelled_task);
        assert_eq!(crashpack.failure.region, root);
        assert_eq!(
            crashpack.failure.outcome,
            FailureOutcome::Cancelled {
                cancel_kind: crate::types::CancelKind::Timeout,
            }
        );
        crate::test_complete!("crashpack_preserves_cancelled_terminal_task_kind");
    }

    const PLAIN_RUNNER_FAILURE_PROBE: &str = "lab::runtime::tests::plain_runner_failure_probe";
    const PLAIN_RUNNER_FAILURE_SEED: u64 = 0x4b78_0003;

    fn trigger_plain_runner_failure_probe() {
        panic!("intentional plain-runner failure probe"); // ubs:ignore — deliberate subprocess failure injection in a test-only helper
    }

    #[test]
    #[ignore = "subprocess-only probe for plain-runner crashpack emission"]
    fn plain_runner_failure_probe() {
        if std::env::var_os(PLAIN_RUNNER_FAILURE_PROBE_ENV).is_none() {
            return;
        }
        let _ = run_async_under_lab(PLAIN_RUNNER_FAILURE_SEED, |_cx| async move {
            trigger_plain_runner_failure_probe();
        });
    }

    #[test]
    fn plain_runner_failure_writes_crashpack() {
        init_test("plain_runner_failure_writes_crashpack");
        let now = std::time::SystemTime::now(); // ubs:ignore — test-directory uniqueness only, not a security token
        let nonce = now
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock after Unix epoch")
            .as_nanos();
        let artifact_root = std::env::temp_dir().join(format!(
            "asupersync-fgdb-4bxh-{}-{nonce}",
            std::process::id()
        ));
        let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
            .args([
                "--ignored",
                "--exact",
                PLAIN_RUNNER_FAILURE_PROBE,
                "--nocapture",
            ])
            .env(AUTO_ARTIFACTS_ENV, "1")
            .env(TEST_ARTIFACTS_DIR_ENV, &artifact_root)
            .env(PLAIN_RUNNER_FAILURE_PROBE_ENV, "1")
            .env_remove(LAB_TEST_SEED_ENV)
            .env_remove(LAB_TEST_WORKERS_ENV)
            .env_remove(LAB_TEST_MAX_STEPS_ENV)
            .output()
            .expect("run plain-runner failure probe");
        assert!(!output.status.success(), "failure probe must fail");

        let mut transcript = String::from_utf8_lossy(&output.stdout).into_owned();
        transcript.push_str(&String::from_utf8_lossy(&output.stderr));
        assert!(
            transcript.contains(&format!("seed {PLAIN_RUNNER_FAILURE_SEED}")),
            "failure transcript must name the replay seed: {transcript}"
        );
        let crashpack_path = transcript
            .lines()
            .find_map(|line| line.trim().strip_prefix("crashpack: "))
            .expect("failure transcript must name the crashpack path");
        assert!(
            std::path::Path::new(crashpack_path).is_file(),
            "crashpack path must exist: {crashpack_path}"
        );
        let crashpack_json = std::fs::read_to_string(crashpack_path)
            .expect("plain-runner crashpack must be readable");
        let crashpack: serde_json::Value =
            serde_json::from_str(&crashpack_json).expect("plain-runner crashpack JSON");
        assert_eq!(
            crashpack["manifest"]["config"]["seed"],
            PLAIN_RUNNER_FAILURE_SEED
        );
        assert_eq!(
            crashpack["failure"]["outcome"]["Panicked"]["message"].as_str(),
            Some("intentional plain-runner failure probe")
        );
        crate::test_complete!("plain_runner_failure_writes_crashpack");
    }

    #[test]
    fn join_error_crashpack_outcome_preserves_kind_and_payload() {
        init_test("join_error_crashpack_outcome_preserves_kind_and_payload");
        let cancelled = crate::runtime::JoinError::Cancelled(crate::types::CancelReason::timeout());
        assert_eq!(
            failure_outcome_from_join_error(&cancelled),
            FailureOutcome::Cancelled {
                cancel_kind: crate::types::CancelKind::Timeout,
            }
        );

        let panicked = crate::runtime::JoinError::Panicked(crate::types::PanicPayload::new(
            "exact panic payload",
        ));
        assert_eq!(
            failure_outcome_from_join_error(&panicked),
            FailureOutcome::Panicked {
                message: "exact panic payload".to_owned(),
            }
        );
        crate::test_complete!("join_error_crashpack_outcome_preserves_kind_and_payload");
    }

    /// Agent UX convenience methods return consistent values.
    #[test]
    fn contract_convenience_methods_consistent() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_convenience_methods_consistent");

        let app = crate::app::AppSpec::new("ux_test");
        let harness = crate::lab::SporkAppHarness::with_seed(42, app).unwrap();
        let report = harness.run_to_report().unwrap();
        let json = report.to_json();

        // trace_fingerprint() matches JSON.
        assert_eq!(
            report.trace_fingerprint(),
            json["fingerprints"]["trace"].as_u64().unwrap()
        );

        // seed() matches JSON.
        assert_eq!(report.seed(), json["run"]["seed"].as_u64().unwrap());

        // config_hash() matches JSON.
        assert_eq!(
            report.config_hash(),
            json["lab"]["config_hash"].as_u64().unwrap()
        );

        // No crashpack by default.
        assert!(report.crashpack_path().is_none());

        // Empty app -> no oracle failures.
        assert!(report.oracle_failures().is_empty());

        crate::test_complete!("contract_convenience_methods_consistent");
    }

    /// Failing runs auto-attach a deterministic crashpack reference.
    #[test]
    fn contract_auto_crashpack_on_failure() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_auto_crashpack_on_failure");

        let config = LabConfig::new(17).panic_on_leak(false);
        let mut runtime = LabRuntime::new(config);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let (task, _) = runtime
            .state
            .create_task(region, Budget::INFINITE, async {})
            .expect("create task");
        runtime.scheduler.lock().schedule(task, 0);
        // Create the obligation while the task is still live, then run to
        // quiescence so the task completes without resolving it (intentional leak).
        runtime
            .state
            .create_obligation(
                ObligationKind::SendPermit,
                task,
                region,
                Some("intentional leak".to_string()),
            )
            .expect("create obligation");
        runtime.run_until_quiescent();

        let report = runtime.spork_report("failing_app", Vec::new());
        assert!(!report.passed(), "failing run must not report PASS");
        let crashpack_path = report
            .crashpack_path()
            .expect("failing run should include crashpack attachment");
        assert!(
            crashpack_path.starts_with("crashpack-"),
            "unexpected crashpack path: {crashpack_path}"
        );
        assert!(
            report
                .attachments
                .iter()
                .any(|attachment| attachment.kind == HarnessAttachmentKind::CrashPack),
            "crashpack attachment kind must be present"
        );
        let crashpack_link = report
            .crashpack_link()
            .expect("failing run should expose crashpack link metadata");
        assert_eq!(crashpack_link.path, crashpack_path);
        assert_eq!(crashpack_link.fingerprint, report.trace_fingerprint());
        assert!(
            crashpack_link.id.starts_with("crashpack-"),
            "unexpected crashpack id: {}",
            crashpack_link.id
        );
        assert!(
            crashpack_link.replay.command_line.contains(crashpack_path),
            "replay command should include crashpack path"
        );

        crate::test_complete!("contract_auto_crashpack_on_failure");
    }

    /// Failing runs with replay recording enabled include a deterministic
    /// divergent prefix in the auto-built crashpack.
    #[test]
    fn contract_auto_crashpack_contains_divergent_prefix_when_replay_enabled() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_auto_crashpack_contains_divergent_prefix_when_replay_enabled");

        let config = LabConfig::new(1701)
            .panic_on_leak(false)
            .with_default_replay_recording();
        let mut runtime = LabRuntime::new(config);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let (task, _) = runtime
            .state
            .create_task(region, Budget::INFINITE, async {})
            .expect("create task");
        runtime.scheduler.lock().schedule(task, 0);
        runtime
            .state
            .create_obligation(
                ObligationKind::SendPermit,
                task,
                region,
                Some("intentional leak".to_string()),
            )
            .expect("create obligation");
        runtime.run_until_quiescent();

        let run = runtime.report();
        let crashpack = runtime
            .build_crashpack_for_report(&run)
            .expect("failing run should build crashpack");

        assert!(crashpack.has_divergent_prefix());
        assert!(
            crashpack
                .manifest
                .has_attachment(&crate::trace::crashpack::AttachmentKind::DivergentPrefix),
            "manifest must include divergent prefix attachment"
        );
        assert!(
            crashpack.replay.is_some(),
            "crashpack should carry replay command metadata"
        );

        crate::test_complete!(
            "contract_auto_crashpack_contains_divergent_prefix_when_replay_enabled"
        );
    }

    /// Manual crashpack attachments are preserved without auto-duplication.
    #[test]
    fn contract_manual_crashpack_not_duplicated_on_failure() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_manual_crashpack_not_duplicated_on_failure");

        let config = LabConfig::new(18).panic_on_leak(false);
        let mut runtime = LabRuntime::new(config);
        let region = runtime.state.create_root_region(Budget::INFINITE);
        let (task, _) = runtime
            .state
            .create_task(region, Budget::INFINITE, async {})
            .expect("create task");
        runtime.scheduler.lock().schedule(task, 0);
        runtime
            .state
            .create_obligation(
                ObligationKind::SendPermit,
                task,
                region,
                Some("intentional leak".to_string()),
            )
            .expect("create obligation");
        runtime.run_until_quiescent();

        let report = runtime.spork_report(
            "failing_app_manual",
            vec![HarnessAttachmentRef::crashpack("manual-crashpack.json")],
        );
        let crashpack_count = report
            .attachments
            .iter()
            .filter(|attachment| attachment.kind == HarnessAttachmentKind::CrashPack)
            .count();
        assert_eq!(
            crashpack_count, 1,
            "manual crashpack should not be duplicated"
        );
        assert_eq!(report.crashpack_path(), Some("manual-crashpack.json"));
        let crashpack_link = report
            .crashpack_link()
            .expect("manual crashpack should still produce metadata");
        assert_eq!(crashpack_link.path, "manual-crashpack.json");
        assert!(
            crashpack_link
                .replay
                .command_line
                .contains("manual-crashpack.json"),
            "replay command should include manual crashpack path"
        );

        crate::test_complete!("contract_manual_crashpack_not_duplicated_on_failure");
    }

    /// JSON output is deterministic across runs with same seed.
    #[test]
    fn contract_json_deterministic_same_seed() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_json_deterministic_same_seed");

        let json_a = {
            let app = crate::app::AppSpec::new("det_contract");
            let harness = crate::lab::SporkAppHarness::with_seed(42, app).unwrap();
            harness.run_to_report().unwrap().to_json()
        };

        let json_b = {
            let app = crate::app::AppSpec::new("det_contract");
            let harness = crate::lab::SporkAppHarness::with_seed(42, app).unwrap();
            harness.run_to_report().unwrap().to_json()
        };

        // The canonical Foata `trace_fingerprint` is the semantic determinism
        // signal. The sequential `event_hash` additionally embeds per-event
        // data (e.g. ephemeral IDs allocated from process-global counters)
        // that benignly drifts across invocations in the same process even
        // for the same seed. Normalise it before comparing so the assertion
        // targets what the test actually contracts for ("same seed →
        // equivalent run artefact") rather than incidental monotonic counters.
        fn strip_event_hash(obj: &mut serde_json::Map<String, serde_json::Value>) {
            if obj.contains_key("event_hash") {
                obj.insert("event_hash".into(), serde_json::Value::Null);
            }
            for val in obj.values_mut() {
                if let Some(sub) = val.as_object_mut() {
                    strip_event_hash(sub);
                }
            }
        }
        let normalize = |mut v: serde_json::Value| -> serde_json::Value {
            if let Some(obj) = v.as_object_mut() {
                strip_event_hash(obj);
            }
            v
        };

        assert_eq!(
            normalize(json_a),
            normalize(json_b),
            "same seed must produce identical JSON (mod sequential event_hash)",
        );

        crate::test_complete!("contract_json_deterministic_same_seed");
    }

    /// Attachments appear in the report, sorted by (kind, path).
    #[test]
    fn contract_attachments_sorted_in_json() {
        crate::test_utils::init_test_logging();
        crate::test_phase!("contract_attachments_sorted_in_json");

        let app = crate::app::AppSpec::new("attach_contract");
        let mut harness = crate::lab::SporkAppHarness::with_seed(7, app).unwrap();
        // Add in reverse order to verify sorting.
        harness.attach(HarnessAttachmentRef::trace("z_trace.json"));
        harness.attach(HarnessAttachmentRef::crashpack("a_crash.tar"));

        let report = harness.run_to_report().unwrap();

        // crashpack_path() returns the crashpack.
        assert_eq!(report.crashpack_path(), Some("a_crash.tar"));

        let json = report.to_json();
        let attachments = json["attachments"].as_array().unwrap();
        assert_eq!(attachments.len(), 2);

        // CrashPack sorts before Trace (enum ordering).
        assert_eq!(attachments[0]["kind"], "crashpack");
        assert_eq!(attachments[1]["kind"], "trace");

        crate::test_complete!("contract_attachments_sorted_in_json");
    }

    // =========================================================================
    // Virtual Time Control Tests (bd-1hu19.3)
    // =========================================================================

    #[asupersync::lab_test(seeds = 42..43)]
    fn advance_to_next_timer_empty(runtime: &mut LabRuntime) {
        let wakeups = runtime.advance_to_next_timer();
        crate::assert_with_log!(wakeups == 0, "no timers → 0 wakeups", 0, wakeups);

        let deadline = runtime.next_timer_deadline();
        crate::assert_with_log!(
            deadline.is_none(),
            "no pending deadline",
            true,
            deadline.is_none()
        );
    }

    #[test]
    fn advance_to_next_timer_fires_timer() {
        init_test("advance_to_next_timer_fires_timer");
        let mut runtime = LabRuntime::with_seed(42);

        // Register a timer at t=1s via the timer driver handle
        let timer_handle = runtime.state.timer_driver_handle().unwrap();
        let woken = Arc::new(std::sync::atomic::AtomicBool::new(false));

        let waker = Waker::from(Arc::new(FlagWaker(woken.clone())));
        let _ = timer_handle.register(Time::from_secs(1), waker);

        // Should have 1 pending timer
        let count = runtime.pending_timer_count();
        crate::assert_with_log!(count == 1, "1 pending timer", 1, count);

        // Advance to next timer
        let wakeups = runtime.advance_to_next_timer();
        crate::assert_with_log!(wakeups == 1, "1 wakeup", 1, wakeups);

        // Time should now be at 1 second
        let now = runtime.now();
        crate::assert_with_log!(
            now == Time::from_secs(1),
            "time at 1s",
            Time::from_secs(1),
            now
        );

        // Waker should have been called
        let was_woken = woken.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(was_woken, "waker fired", true, was_woken);
        crate::test_complete!("advance_to_next_timer_fires_timer");
    }

    #[test]
    fn metamorphic_timer_registration_permutation_preserves_virtual_time_progression() {
        init_test("metamorphic_timer_registration_permutation_preserves_virtual_time_progression");

        let baseline = collect_timer_advances(&[5, 1, 3, 1, 8], &[]);
        let permuted = collect_timer_advances(&[1, 8, 5, 1, 3], &[]);

        crate::assert_with_log!(
            baseline.advance_points == permuted.advance_points,
            "deadline multiset permutation preserves advance points",
            &baseline.advance_points,
            &permuted.advance_points
        );
        crate::assert_with_log!(
            baseline.total_wakeups == permuted.total_wakeups,
            "deadline multiset permutation preserves wakeup count",
            baseline.total_wakeups,
            permuted.total_wakeups
        );
        crate::assert_with_log!(
            baseline.final_time == permuted.final_time,
            "deadline multiset permutation preserves final virtual time",
            baseline.final_time,
            permuted.final_time
        );
        crate::assert_with_log!(
            baseline.advance_points
                == vec![
                    Time::from_secs(1),
                    Time::from_secs(3),
                    Time::from_secs(5),
                    Time::from_secs(8)
                ],
            "advance points collapse duplicate deadlines without moving backward",
            vec![
                Time::from_secs(1),
                Time::from_secs(3),
                Time::from_secs(5),
                Time::from_secs(8)
            ],
            baseline.advance_points.clone()
        );

        crate::test_complete!(
            "metamorphic_timer_registration_permutation_preserves_virtual_time_progression"
        );
    }

    #[test]
    fn metamorphic_cancelled_timer_does_not_skew_virtual_time_progression() {
        init_test("metamorphic_cancelled_timer_does_not_skew_virtual_time_progression");

        let baseline = collect_timer_advances(&[2, 4, 9], &[]);
        let with_cancelled_timer = collect_timer_advances(&[2, 4, 6, 9], &[2]);

        crate::assert_with_log!(
            baseline.advance_points == with_cancelled_timer.advance_points,
            "cancelling an intermediate timer preserves surviving advance points",
            &baseline.advance_points,
            &with_cancelled_timer.advance_points
        );
        crate::assert_with_log!(
            baseline.total_wakeups == with_cancelled_timer.total_wakeups,
            "cancelling an intermediate timer preserves surviving wakeup count",
            baseline.total_wakeups,
            with_cancelled_timer.total_wakeups
        );
        crate::assert_with_log!(
            baseline.final_time == with_cancelled_timer.final_time,
            "cancelling an intermediate timer preserves final virtual time",
            baseline.final_time,
            with_cancelled_timer.final_time
        );
        crate::assert_with_log!(
            with_cancelled_timer.cancelled_wakeups == 0,
            "cancelled timer never wakes after auto-advance",
            0u64,
            with_cancelled_timer.cancelled_wakeups
        );

        crate::test_complete!("metamorphic_cancelled_timer_does_not_skew_virtual_time_progression");
    }

    #[cfg(unix)]
    #[test]
    fn run_with_auto_advance_delivers_delayed_reactor_events() {
        init_test("run_with_auto_advance_delivers_delayed_reactor_events");
        let config = LabConfig::new(42).with_auto_advance().max_steps(32);
        let mut runtime = LabRuntime::new(config);
        let handle = runtime.state.io_driver_handle().expect("io driver");
        let wake_count = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
        let source = TestFdSource;

        let registration = handle
            .register(&source, Interest::READABLE, waker)
            .expect("register source");
        let token = registration.token();

        runtime
            .lab_reactor()
            .inject_event(token, Event::readable(token), Duration::from_secs(1));

        let report = runtime.run_with_auto_advance();

        crate::assert_with_log!(
            report.auto_advances >= 1,
            "auto-advance reaches delayed reactor deadline",
            true,
            report.auto_advances >= 1
        );
        crate::assert_with_log!(
            runtime.now() >= Time::from_secs(1),
            "virtual time advanced to delayed reactor event",
            true,
            runtime.now() >= Time::from_secs(1)
        );
        let wakeups = wake_count.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(
            wakeups == 1,
            "reactor event woke registration",
            1u64,
            wakeups
        );
        let saw_ready = runtime
            .state
            .trace
            .snapshot()
            .iter()
            .any(|event| event.kind == TraceEventKind::IoReady);
        crate::assert_with_log!(saw_ready, "io ready trace recorded", true, saw_ready);
        let next_event = runtime.lab_reactor().next_event_time();
        crate::assert_with_log!(
            next_event.is_none(),
            "delayed reactor event drained",
            true,
            next_event.is_none()
        );

        crate::test_complete!("run_with_auto_advance_delivers_delayed_reactor_events");
    }

    #[test]
    fn run_with_auto_advance_basic() {
        init_test("run_with_auto_advance_basic");
        let config = LabConfig::new(42).with_auto_advance();
        let mut runtime = LabRuntime::new(config);

        // No tasks, no timers → immediate quiescence
        let report = runtime.run_with_auto_advance();
        crate::assert_with_log!(report.steps == 0, "0 steps", 0u64, report.steps);
        crate::assert_with_log!(
            report.auto_advances == 0,
            "0 auto-advances",
            0u64,
            report.auto_advances
        );
        crate::test_complete!("run_with_auto_advance_basic");
    }

    #[test]
    fn run_with_auto_advance_jumps_past_timer_deadlines() {
        init_test("run_with_auto_advance_jumps_past_timer_deadlines");
        let config = LabConfig::new(42).with_auto_advance().max_steps(1_000);
        let mut runtime = LabRuntime::new(config);

        // Register timers at 1s, 5s, and 10s via timer driver
        let timer_handle = runtime.state.timer_driver_handle().unwrap();
        let wake_count = Arc::new(std::sync::atomic::AtomicU64::new(0));

        for secs in [1, 5, 10] {
            let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
            let _ = timer_handle.register(Time::from_secs(secs), waker);
        }

        let report = runtime.run_with_auto_advance();

        // All 3 timer deadlines should have been auto-advanced to
        crate::assert_with_log!(
            report.auto_advances >= 3,
            "at least 3 auto-advances",
            true,
            report.auto_advances >= 3
        );

        // Virtual time should be at or past 10 seconds
        let now = runtime.now();
        crate::assert_with_log!(
            now >= Time::from_secs(10),
            "time >= 10s",
            true,
            now >= Time::from_secs(10)
        );

        // All wakers should have been called
        let count = wake_count.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(count == 3, "3 wakeups", 3u64, count);
        crate::test_complete!("run_with_auto_advance_jumps_past_timer_deadlines");
    }

    #[test]
    fn virtual_time_24_hour_instant_test() {
        init_test("virtual_time_24_hour_instant_test");
        // Acceptance criterion: 24 hours of virtual time in <1 second wall time.
        let config = LabConfig::new(42).with_auto_advance().max_steps(100_000);
        let mut runtime = LabRuntime::new(config);

        // Register timers spread across 24 hours (every hour)
        let timer_handle = runtime.state.timer_driver_handle().unwrap();
        let wake_count = Arc::new(std::sync::atomic::AtomicU64::new(0));

        for hour in 1..=24 {
            let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
            let _ = timer_handle.register(Time::from_secs(hour * 3600), waker);
        }

        let wall_start = std::time::Instant::now();
        let report = runtime.run_with_auto_advance();
        let wall_elapsed = wall_start.elapsed();

        // Virtual time should span 24 hours = 86400 seconds
        crate::assert_with_log!(
            report.virtual_elapsed_secs() >= 86400,
            "24h virtual",
            true,
            report.virtual_elapsed_secs() >= 86400
        );

        // All 24 timers fired
        let count = wake_count.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(count == 24, "24 wakeups", 24u64, count);

        // Wall time should be well under 1 second (typically <1ms)
        let wall_ms = wall_elapsed.as_millis();
        crate::assert_with_log!(wall_ms < 1000, "wall time < 1s", true, wall_ms < 1000);
        crate::test_complete!("virtual_time_24_hour_instant_test");
    }

    #[asupersync::lab_test(seeds = 42..43)]
    fn clock_pause_resume(runtime: &mut LabRuntime) {
        let not_paused = !runtime.is_clock_paused();
        crate::assert_with_log!(not_paused, "not paused initially", true, not_paused);

        runtime.pause_clock();
        let paused = runtime.is_clock_paused();
        crate::assert_with_log!(paused, "paused", true, paused);

        runtime.resume_clock();
        let resumed = !runtime.is_clock_paused();
        crate::assert_with_log!(resumed, "resumed", true, resumed);
    }

    #[asupersync::lab_test(seeds = 42..43)]
    fn inject_clock_skew(runtime: &mut LabRuntime) {
        runtime.advance_time(1_000_000_000); // 1 second
        let before = runtime.now();

        // Inject 5 second skew
        runtime.inject_clock_skew(5_000_000_000);
        let after = runtime.now();

        let delta = after.as_nanos() - before.as_nanos();
        crate::assert_with_log!(
            delta == 5_000_000_000,
            "5s skew applied",
            5_000_000_000u64,
            delta
        );

        crate::assert_with_log!(
            after == Time::from_secs(6),
            "time at 6s",
            Time::from_secs(6),
            after
        );
    }

    #[test]
    fn virtual_time_report_conversions() {
        init_test("virtual_time_report_conversions");
        let report = VirtualTimeReport {
            steps: 100,
            auto_advances: 5,
            total_wakeups: 10,
            time_start: Time::ZERO,
            time_end: Time::from_secs(3600),
            virtual_elapsed_nanos: 3_600_000_000_000,
            termination: AutoAdvanceTermination::Quiescent,
        };

        let ms = report.virtual_elapsed_ms();
        crate::assert_with_log!(ms == 3_600_000, "3600000 ms", 3_600_000u64, ms);

        let secs = report.virtual_elapsed_secs();
        crate::assert_with_log!(secs == 3600, "3600 secs", 3600u64, secs);
        crate::test_complete!("virtual_time_report_conversions");
    }

    // =========================================================================
    // Replay severity correctness (bd-beuyd)
    // =========================================================================

    fn forced_schedule_fixture(config: LabConfig, observations: Arc<Mutex<Vec<u8>>>) -> LabRuntime {
        let mut runtime = LabRuntime::new(config);
        let root = runtime.state.create_root_region(Budget::INFINITE);
        for label in 0..3u8 {
            let observations = Arc::clone(&observations);
            let (task, _handle) = runtime
                .state
                .create_task(root, Budget::INFINITE, async move {
                    observations.lock().push(label);
                    futures_lite::future::yield_now().await;
                    observations.lock().push(label + 10);
                })
                .expect("create forced-schedule fixture task");
            runtime.scheduler.lock().schedule(task, label);
        }
        runtime
    }

    #[test]
    fn forced_schedule_artifact_codec_is_canonical_bounded_and_replayable() {
        init_test("forced_schedule_artifact_codec_is_canonical_bounded_and_replayable");

        fn rewrite_checksum(bytes: &mut [u8]) {
            let checksum_offset = bytes
                .len()
                .checked_sub(FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN)
                .expect("canonical artifact contains checksum");
            let checksum = forced_schedule_artifact_checksum(&bytes[..checksum_offset]);
            bytes[checksum_offset..].copy_from_slice(&checksum);
        }

        fn write_u32(bytes: &mut [u8], offset: usize, value: u32) {
            bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
        }

        fn write_u64(bytes: &mut [u8], offset: usize, value: u64) {
            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
        }

        let config = LabConfig::new(0xF0CE_D5CE).worker_count(2).max_steps(128);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), Arc::clone(&source_observations));
        source
            .start_forced_schedule_recording(32)
            .expect("start complete dispatch capture");
        let source_report = source.run_until_quiescent_with_report();
        assert!(source_report.quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete source schedule");
        assert_eq!(schedule.dispatches().len(), 6);

        let canonical = schedule
            .to_canonical_bytes()
            .expect("encode complete source schedule");
        let decoded_dispatch_bytes =
            schedule.dispatches().len() * std::mem::size_of::<ForcedDispatch>();
        let decode_limits =
            ForcedScheduleDecodeLimits::new(canonical.len(), 32, decoded_dispatch_bytes);
        assert_eq!(
            canonical.len(),
            FORCED_SCHEDULE_ARTIFACT_HEADER_LEN
                + 6 * FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN
                + FORCED_SCHEDULE_ARTIFACT_TERMINAL_LEN
                + FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN
        );
        let decoded = ForcedSchedule::try_from_canonical_bytes(&canonical, decode_limits)
            .expect("decode canonical schedule");
        assert_eq!(decoded, schedule);
        assert_eq!(
            decoded.to_canonical_bytes().expect("re-encode schedule"),
            canonical,
            "encode-decode-encode must be byte-identical"
        );
        for (decoded_dispatch, source_dispatch) in
            decoded.dispatches().iter().zip(schedule.dispatches())
        {
            assert_eq!(decoded_dispatch.task(), source_dispatch.task());
            assert_eq!(decoded_dispatch.worker(), source_dispatch.worker());
            assert_eq!(decoded_dispatch.lane(), source_dispatch.lane());
            assert_eq!(decoded_dispatch.at_step(), source_dispatch.at_step());
            assert_eq!(decoded_dispatch.at_nanos(), source_dispatch.at_nanos());
        }
        assert_eq!(decoded.seed(), schedule.seed());
        assert_eq!(decoded.config_hash(), schedule.config_hash());
        assert_eq!(decoded.terminal_steps(), schedule.terminal_steps());
        assert_eq!(decoded.terminal_nanos(), schedule.terminal_nanos());
        assert_eq!(
            decoded.terminal_schedule_hash(),
            schedule.terminal_schedule_hash()
        );
        assert!(decoded.terminal_quiescent());
        assert!(!decoded.truncated());

        let replay_observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&replay_observations));
        let replay_report = replay
            .run_forced_schedule(&decoded, ForcedScheduleLimits::new(32, 128))
            .expect("decoded schedule replays exactly");
        assert_eq!(replay_report.dispatches, 6);
        assert_eq!(replay_report.steps, decoded.terminal_steps());
        assert_eq!(
            replay_report.schedule_hash,
            decoded.terminal_schedule_hash()
        );
        assert_eq!(*replay_observations.lock(), *source_observations.lock());

        let candidate_limits = ForcedScheduleCandidateLimits::new(32, 32, 128);
        let all_indices = (0..decoded.dispatches().len()).collect::<Vec<_>>();
        let candidate = decoded
            .derive_candidate(&all_indices, candidate_limits)
            .expect("derive candidate from decoded authority");
        assert_eq!(candidate.source_version(), decoded.version());
        assert_eq!(candidate.seed(), decoded.seed());
        assert_eq!(candidate.config_hash(), decoded.config_hash());
        assert_eq!(
            candidate.source_dispatch_count(),
            decoded.dispatches().len()
        );
        assert_eq!(
            candidate.source_terminal_schedule_hash(),
            decoded.terminal_schedule_hash()
        );
        for (index, (retained, source_dispatch)) in candidate
            .dispatches()
            .iter()
            .zip(decoded.dispatches())
            .enumerate()
        {
            assert_eq!(retained.source_index(), index);
            assert_eq!(retained.task(), source_dispatch.task());
            assert_eq!(retained.worker(), source_dispatch.worker());
            assert_eq!(retained.lane(), source_dispatch.lane());
            assert_eq!(retained.source_step(), source_dispatch.at_step());
            assert_eq!(retained.source_nanos(), source_dispatch.at_nanos());
        }
        let candidate_observations = Arc::new(Mutex::new(Vec::new()));
        let mut candidate_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&candidate_observations));
        let candidate_report = candidate_replay
            .run_forced_schedule_candidate(&candidate, candidate_limits)
            .expect("decoded candidate executes exact retained choices");
        assert_eq!(
            candidate_report.termination,
            ForcedScheduleCandidateTermination::Quiescent
        );
        assert_eq!(candidate_report.consumed_source_indices, all_indices);
        assert_eq!(*candidate_observations.lock(), *source_observations.lock());

        for prefix_len in 0..canonical.len() {
            assert!(matches!(
                ForcedSchedule::try_from_canonical_bytes(&canonical[..prefix_len], decode_limits),
                Err(ForcedScheduleArtifactError::Truncated { .. })
            ));
        }
        let mut trailing = canonical.clone();
        trailing.push(0);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &trailing,
                ForcedScheduleDecodeLimits::new(trailing.len(), 32, decoded_dispatch_bytes)
            ),
            Err(ForcedScheduleArtifactError::TrailingBytes { .. })
        ));

        for byte_index in 0..canonical.len() {
            let mut corrupted = canonical.clone();
            corrupted[byte_index] ^= 0x80;
            assert!(
                ForcedSchedule::try_from_canonical_bytes(&corrupted, decode_limits).is_err(),
                "byte mutation {byte_index} was accepted"
            );
        }

        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &canonical,
                ForcedScheduleDecodeLimits::new(canonical.len() - 1, 32, decoded_dispatch_bytes)
            ),
            Err(ForcedScheduleArtifactError::ByteLimitExceeded { .. })
        ));
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &canonical,
                ForcedScheduleDecodeLimits::new(
                    canonical.len(),
                    schedule.dispatches().len() - 1,
                    decoded_dispatch_bytes
                )
            ),
            Err(ForcedScheduleArtifactError::DispatchLimitExceeded { .. })
        ));
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &canonical,
                ForcedScheduleDecodeLimits::new(canonical.len(), 32, decoded_dispatch_bytes - 1)
            ),
            Err(ForcedScheduleArtifactError::DecodedAllocationLimitExceeded { .. })
        ));
        let mut impossible_count = canonical[..FORCED_SCHEDULE_ARTIFACT_HEADER_LEN].to_vec();
        write_u64(
            &mut impossible_count,
            FORCED_SCHEDULE_ARTIFACT_COUNT_OFFSET,
            u64::MAX,
        );
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &impossible_count,
                ForcedScheduleDecodeLimits::new(impossible_count.len(), usize::MAX, usize::MAX)
            ),
            Err(ForcedScheduleArtifactError::LengthOverflow { .. })
        ));

        let dispatch0 = FORCED_SCHEDULE_ARTIFACT_HEADER_LEN;
        let dispatch1 = dispatch0 + FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN;
        let terminal = FORCED_SCHEDULE_ARTIFACT_HEADER_LEN
            + schedule.dispatches().len() * FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN;

        let mut wrong_magic = canonical.clone();
        wrong_magic[0] ^= 1;
        rewrite_checksum(&mut wrong_magic);
        assert_eq!(
            ForcedSchedule::try_from_canonical_bytes(&wrong_magic, decode_limits),
            Err(ForcedScheduleArtifactError::MagicMismatch)
        );
        let mut wrong_artifact_version = canonical.clone();
        write_u32(
            &mut wrong_artifact_version,
            8,
            FORCED_SCHEDULE_ARTIFACT_VERSION + 1,
        );
        rewrite_checksum(&mut wrong_artifact_version);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&wrong_artifact_version, decode_limits),
            Err(ForcedScheduleArtifactError::VersionMismatch { .. })
        ));
        let mut wrong_schema = canonical.clone();
        write_u32(&mut wrong_schema, 12, FORCED_SCHEDULE_SCHEMA_VERSION + 1);
        rewrite_checksum(&mut wrong_schema);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&wrong_schema, decode_limits),
            Err(ForcedScheduleArtifactError::SchemaMismatch { .. })
        ));
        let mut unknown_lane = canonical.clone();
        unknown_lane[dispatch0 + 12] = 0xff;
        rewrite_checksum(&mut unknown_lane);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&unknown_lane, decode_limits),
            Err(ForcedScheduleArtifactError::LaneTag {
                index: 0,
                tag: 0xff
            })
        ));
        let mut duplicate_step = canonical.clone();
        write_u64(
            &mut duplicate_step,
            dispatch1 + 13,
            schedule.dispatches()[0].at_step(),
        );
        rewrite_checksum(&mut duplicate_step);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&duplicate_step, decode_limits),
            Err(ForcedScheduleArtifactError::Schedule(
                ForcedScheduleError::StepOrder { index: 1, .. }
            ))
        ));
        let mut backwards_time = canonical.clone();
        write_u64(&mut backwards_time, dispatch0 + 21, 1);
        write_u64(&mut backwards_time, dispatch1 + 21, 0);
        rewrite_checksum(&mut backwards_time);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&backwards_time, decode_limits),
            Err(ForcedScheduleArtifactError::Schedule(
                ForcedScheduleError::TimeOrder { index: 1, .. }
            ))
        ));
        for (offset, field) in [
            (terminal + 24, "terminal_quiescent"),
            (terminal + 25, "truncated"),
        ] {
            let mut invalid_bool = canonical.clone();
            invalid_bool[offset] = 2;
            rewrite_checksum(&mut invalid_bool);
            assert_eq!(
                ForcedSchedule::try_from_canonical_bytes(&invalid_bool, decode_limits),
                Err(ForcedScheduleArtifactError::BooleanTag { field, tag: 2 })
            );
        }
        for (offset, value) in [(terminal + 24, 0), (terminal + 25, 1)] {
            let mut partial = canonical.clone();
            partial[offset] = value;
            rewrite_checksum(&mut partial);
            assert_eq!(
                ForcedSchedule::try_from_canonical_bytes(&partial, decode_limits),
                Err(ForcedScheduleArtifactError::Schedule(
                    ForcedScheduleError::PartialSource
                ))
            );
        }
        let mut impossible_terminal = canonical.clone();
        write_u64(
            &mut impossible_terminal,
            terminal,
            schedule
                .dispatches()
                .last()
                .expect("last dispatch")
                .at_step()
                - 1,
        );
        rewrite_checksum(&mut impossible_terminal);
        assert_eq!(
            ForcedSchedule::try_from_canonical_bytes(&impossible_terminal, decode_limits),
            Err(ForcedScheduleArtifactError::Schedule(
                ForcedScheduleError::PartialSource
            ))
        );

        let mut wrong_seed = canonical.clone();
        write_u64(&mut wrong_seed, 16, schedule.seed() ^ 1);
        rewrite_checksum(&mut wrong_seed);
        let wrong_seed = ForcedSchedule::try_from_canonical_bytes(&wrong_seed, decode_limits)
            .expect("authenticated alternate seed decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_seed, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::SeedMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_config = canonical.clone();
        write_u64(&mut wrong_config, 24, schedule.config_hash() ^ 1);
        rewrite_checksum(&mut wrong_config);
        let wrong_config = ForcedSchedule::try_from_canonical_bytes(&wrong_config, decode_limits)
            .expect("authenticated alternate config decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_config, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::ConfigMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_task = canonical.clone();
        write_u64(
            &mut wrong_task,
            dispatch0,
            schedule.dispatches()[0].task().0 ^ 1,
        );
        rewrite_checksum(&mut wrong_task);
        let wrong_task = ForcedSchedule::try_from_canonical_bytes(&wrong_task, decode_limits)
            .expect("authenticated alternate task decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_task, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::TaskUnavailable { index: 0, .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_worker = canonical.clone();
        write_u32(&mut wrong_worker, dispatch0 + 8, u32::MAX);
        rewrite_checksum(&mut wrong_worker);
        let wrong_worker = ForcedSchedule::try_from_canonical_bytes(&wrong_worker, decode_limits)
            .expect("authenticated alternate worker decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_worker, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::WorkerUnavailable { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_lane = canonical.clone();
        wrong_lane[dispatch0 + 12] = match schedule.dispatches()[0].lane() {
            DispatchLane::Cancel => forced_schedule_lane_tag(DispatchLane::Ready),
            DispatchLane::Timed | DispatchLane::Ready | DispatchLane::Stolen => {
                forced_schedule_lane_tag(DispatchLane::Cancel)
            }
        };
        rewrite_checksum(&mut wrong_lane);
        let wrong_lane = ForcedSchedule::try_from_canonical_bytes(&wrong_lane, decode_limits)
            .expect("authenticated alternate lane decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_lane, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::LaneMismatch { index: 0, .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_terminal_hash = canonical.clone();
        write_u64(
            &mut wrong_terminal_hash,
            terminal + 16,
            schedule.terminal_schedule_hash() ^ 1,
        );
        rewrite_checksum(&mut wrong_terminal_hash);
        let wrong_terminal_hash =
            ForcedSchedule::try_from_canonical_bytes(&wrong_terminal_hash, decode_limits)
                .expect("authenticated alternate terminal hash decodes");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = forced_schedule_fixture(config, Arc::clone(&observations));
        assert!(matches!(
            runtime.run_forced_schedule(&wrong_terminal_hash, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::CertificateMismatch { .. })
        ));
        assert_eq!(observations.lock().len(), 6);

        crate::test_complete!("forced_schedule_artifact_codec_is_canonical_bounded_and_replayable");
    }

    fn pending_spawn_with_future_reactor_fixture(
        config: LabConfig,
        observations: Arc<Mutex<Vec<u64>>>,
    ) -> LabRuntime {
        let mut runtime = LabRuntime::new(config);
        let token = Token::new(0xCAAD);
        runtime
            .lab_reactor()
            .inject_event(token, Event::readable(token), Duration::from_secs(1));

        let root = runtime.state.create_root_region(Budget::INFINITE);
        let pending = runtime
            .state
            .region(root)
            .expect("root region")
            .pending_spawn_handle();
        let parent: crate::cx::Cx = crate::cx::Cx::new_with_drivers(
            root,
            TaskId::from_arena(ArenaIndex::new(u32::MAX - 1, 0)),
            Budget::INFINITE,
            None,
            runtime.state.io_driver_handle(),
            None,
            runtime.state.timer_driver_handle(),
            None,
        )
        .with_spawn_gateway(runtime.state.spawn_gateway())
        .with_pending_spawn_counter(Some(pending));
        let _handle = parent
            .spawn(|child| async move {
                observations.lock().push(child.now().as_nanos());
            })
            .expect("managed spawn enqueues");
        assert_eq!(runtime.spawn_mailbox.len(), 1);
        runtime
    }

    fn pending_command_before_timer_fixture(
        config: LabConfig,
        observations: Arc<Mutex<Vec<u64>>>,
    ) -> LabRuntime {
        let mut runtime = LabRuntime::new(config);
        let root = runtime.state.create_root_region(Budget::INFINITE);
        let gateway = runtime.state.spawn_gateway().expect("lab spawn gateway");
        let missing = TaskId::from_arena(ArenaIndex::new(u32::MAX - 2, 0));
        let (task, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                let now = crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                observations.lock().push(now.as_nanos());
                assert!(gateway.enqueue_handle_cancel(missing, CancelReason::shutdown()));
                crate::time::sleep(now, Duration::from_secs(1)).await;
                let now = crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                observations.lock().push(now.as_nanos());
            })
            .expect("create command-before-timer task");
        runtime.scheduler.lock().schedule(task, 0);
        runtime
    }

    #[test]
    fn pending_dispatch_auto_advance_before_future_deadline() {
        init_test("pending_dispatch_auto_advance_before_future_deadline");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = pending_spawn_with_future_reactor_fixture(
            LabConfig::new(0xCAAD_A070).max_steps(32),
            Arc::clone(&observations),
        );

        let report = runtime.run_with_auto_advance();

        assert_eq!(
            *observations.lock(),
            vec![0],
            "queued spawn work must run before an unrelated future reactor deadline"
        );
        assert_eq!(report.termination, AutoAdvanceTermination::Quiescent);
        assert_eq!(runtime.now(), Time::from_secs(1));
        crate::test_complete!("pending_dispatch_auto_advance_before_future_deadline");
    }

    #[test]
    fn pending_dispatch_run_until_idle_admits_spawn() {
        init_test("pending_dispatch_run_until_idle_admits_spawn");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut runtime = pending_spawn_with_future_reactor_fixture(
            LabConfig::new(0x1D1E_CAAD).max_steps(32),
            Arc::clone(&observations),
        );

        assert_eq!(runtime.run_until_idle(), 1);
        assert_eq!(
            *observations.lock(),
            vec![0],
            "idle detection must admit and poll queued managed spawns"
        );
        assert!(runtime.spawn_mailbox.is_empty());
        crate::test_complete!("pending_dispatch_run_until_idle_admits_spawn");
    }

    #[test]
    fn pending_dispatch_forced_candidate_before_future_deadline() {
        init_test("pending_dispatch_forced_candidate_before_future_deadline");
        let config = LabConfig::new(0xCAAD_CAAD).max_steps(32);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = pending_spawn_with_future_reactor_fixture(
            config.clone(),
            Arc::clone(&source_observations),
        );
        source
            .start_forced_schedule_recording(4)
            .expect("start exact dispatch capture");
        source.step();
        assert!(source.is_quiescent());
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("capture one pending-spawn dispatch");
        assert_eq!(schedule.dispatches().len(), 1);
        assert_eq!(schedule.dispatches()[0].at_nanos(), 0);
        assert_eq!(*source_observations.lock(), vec![0]);

        let limits = ForcedScheduleCandidateLimits::new(4, 4, 16);
        let candidate = schedule
            .derive_candidate(&[0], limits)
            .expect("derive full-retention candidate");
        let replay_observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay =
            pending_spawn_with_future_reactor_fixture(config, Arc::clone(&replay_observations));
        let report = replay
            .run_forced_schedule_candidate(&candidate, limits)
            .expect("candidate must drain spawn admission before time advancement");

        assert_eq!(
            report.termination,
            ForcedScheduleCandidateTermination::Quiescent
        );
        assert_eq!(report.consumed_source_indices, vec![0]);
        assert_eq!(*replay_observations.lock(), vec![0]);
        assert_eq!(report.lab.now_nanos, 0);
        crate::test_complete!("pending_dispatch_forced_candidate_before_future_deadline");
    }

    #[test]
    fn pending_dispatch_forced_candidate_before_later_retained_dispatch() {
        init_test("pending_dispatch_forced_candidate_before_later_retained_dispatch");
        let config = LabConfig::new(0xCAAD_C0DE).max_steps(32);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source =
            pending_command_before_timer_fixture(config.clone(), Arc::clone(&source_observations));
        source
            .start_forced_schedule_recording(4)
            .expect("start exact dispatch capture");
        let source_report = source.run_with_auto_advance();
        assert_eq!(source_report.termination, AutoAdvanceTermination::Quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("capture both task dispatches");
        assert_eq!(schedule.dispatches().len(), 2);
        assert_eq!(*source_observations.lock(), vec![0, 1_000_000_000]);

        let limits = ForcedScheduleCandidateLimits::new(4, 4, 16);
        let candidate = schedule
            .derive_candidate(&[0, 1], limits)
            .expect("derive full-retention candidate");
        let replay_observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay =
            pending_command_before_timer_fixture(config, Arc::clone(&replay_observations));
        let report = replay
            .run_forced_schedule_candidate(&candidate, limits)
            .expect("candidate must pump the command before advancing to the retained wake");

        assert_eq!(
            report.termination,
            ForcedScheduleCandidateTermination::Quiescent
        );
        assert_eq!(report.consumed_source_indices, vec![0, 1]);
        assert_eq!(*replay_observations.lock(), vec![0, 1_000_000_000]);
        assert_eq!(report.lab.now_nanos, 1_000_000_000);
        crate::test_complete!("pending_dispatch_forced_candidate_before_later_retained_dispatch");
    }

    #[test]
    fn forced_schedule_replay_executes_recorded_choices_before_polling() {
        init_test("forced_schedule_replay_executes_recorded_choices_before_polling");
        let config = LabConfig::new(0xF0CE_D5CE).worker_count(2).max_steps(128);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), Arc::clone(&source_observations));
        source
            .start_forced_schedule_recording(32)
            .expect("start exact dispatch capture");
        let source_report = source.run_until_quiescent_with_report();
        assert!(source_report.quiescent, "source fixture must quiesce");
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete exact dispatch projection");
        assert_eq!(schedule.version(), FORCED_SCHEDULE_SCHEMA_VERSION);
        assert_eq!(schedule.seed(), config.seed);
        assert_eq!(schedule.dispatches().len(), 6);
        assert_eq!(
            schedule.terminal_schedule_hash(),
            source_report.trace_certificate.schedule_hash
        );

        let replay_observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config, Arc::clone(&replay_observations));
        let receipt = replay
            .run_forced_schedule(&schedule, ForcedScheduleLimits::new(32, 128))
            .expect("recorded dispatch projection must execute exactly");

        assert!(receipt.quiescent);
        assert_eq!(receipt.dispatches, schedule.dispatches().len());
        assert_eq!(receipt.steps, schedule.terminal_steps());
        assert_eq!(receipt.terminal_nanos, schedule.terminal_nanos());
        assert_eq!(receipt.schedule_hash, schedule.terminal_schedule_hash());
        assert_eq!(*replay_observations.lock(), *source_observations.lock());
        crate::test_complete!("forced_schedule_replay_executes_recorded_choices_before_polling");
    }

    fn recorded_forced_schedule_fixture() -> ForcedSchedule {
        let config = LabConfig::new(0xA471_FAC7).worker_count(2).max_steps(128);
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config, observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start artifact fixture capture");
        assert!(source.run_until_quiescent_with_report().quiescent);
        source
            .finish_forced_schedule_recording()
            .expect("finish complete artifact fixture capture")
    }

    fn reseal_forced_schedule_artifact(bytes: &mut [u8]) {
        let checksum_offset = bytes.len() - FORCED_SCHEDULE_ARTIFACT_CHECKSUM_LEN;
        let checksum = forced_schedule_artifact_checksum(&bytes[..checksum_offset]);
        bytes[checksum_offset..].copy_from_slice(&checksum);
    }

    #[test]
    fn forced_schedule_artifact_roundtrip_is_exact_and_bounded() {
        init_test("forced_schedule_artifact_roundtrip_is_exact_and_bounded");
        let schedule = recorded_forced_schedule_fixture();
        let bytes = schedule
            .to_canonical_bytes()
            .expect("encode complete forced schedule");
        assert_eq!(
            schedule.to_canonical_bytes().expect("repeat encoding"),
            bytes,
            "canonical encoding must be deterministic"
        );

        let decoded_bytes = schedule.dispatches().len() * std::mem::size_of::<ForcedDispatch>();
        let limits = ForcedScheduleDecodeLimits::new(
            bytes.len(),
            schedule.dispatches().len(),
            decoded_bytes,
        );
        assert_eq!(
            ForcedSchedule::try_from_canonical_bytes(&bytes, limits)
                .expect("decode canonical artifact"),
            schedule
        );

        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &bytes,
                ForcedScheduleDecodeLimits::new(
                    bytes.len() - 1,
                    schedule.dispatches().len(),
                    decoded_bytes,
                ),
            ),
            Err(ForcedScheduleArtifactError::ByteLimitExceeded { .. })
        ));
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &bytes,
                ForcedScheduleDecodeLimits::new(
                    bytes.len(),
                    schedule.dispatches().len() - 1,
                    decoded_bytes,
                ),
            ),
            Err(ForcedScheduleArtifactError::DispatchLimitExceeded { .. })
        ));
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(
                &bytes,
                ForcedScheduleDecodeLimits::new(
                    bytes.len(),
                    schedule.dispatches().len(),
                    decoded_bytes - 1,
                ),
            ),
            Err(ForcedScheduleArtifactError::DecodedAllocationLimitExceeded { .. })
        ));
        crate::test_complete!("forced_schedule_artifact_roundtrip_is_exact_and_bounded");
    }

    #[test]
    fn forced_schedule_artifact_rejects_hostile_encodings() {
        init_test("forced_schedule_artifact_rejects_hostile_encodings");
        let schedule = recorded_forced_schedule_fixture();
        let bytes = schedule
            .to_canonical_bytes()
            .expect("encode complete forced schedule");
        let limits = ForcedScheduleDecodeLimits::new(
            bytes.len() + 1,
            schedule.dispatches().len() + 1,
            (schedule.dispatches().len() + 1) * std::mem::size_of::<ForcedDispatch>(),
        );

        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&bytes[..12], limits),
            Err(ForcedScheduleArtifactError::Truncated { .. })
        ));

        let mut malformed = bytes.clone();
        malformed[0] ^= 0x80;
        assert_eq!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::MagicMismatch)
        );

        let mut malformed = bytes.clone();
        malformed[8..12].copy_from_slice(&(FORCED_SCHEDULE_ARTIFACT_VERSION + 1).to_le_bytes());
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::VersionMismatch { .. })
        ));

        let mut malformed = bytes.clone();
        malformed.push(0);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::TrailingBytes { .. })
        ));

        let mut malformed = bytes.clone();
        let last = malformed.len() - 1;
        malformed[last] ^= 1;
        assert_eq!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::ChecksumMismatch)
        );

        let mut malformed = bytes.clone();
        malformed[FORCED_SCHEDULE_ARTIFACT_HEADER_LEN + 12] = u8::MAX;
        reseal_forced_schedule_artifact(&mut malformed);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::LaneTag { index: 0, .. })
        ));

        let mut malformed = bytes;
        let terminal_offset = FORCED_SCHEDULE_ARTIFACT_HEADER_LEN
            + schedule.dispatches().len() * FORCED_SCHEDULE_ARTIFACT_DISPATCH_LEN;
        malformed[terminal_offset + 24] = 2;
        reseal_forced_schedule_artifact(&mut malformed);
        assert!(matches!(
            ForcedSchedule::try_from_canonical_bytes(&malformed, limits),
            Err(ForcedScheduleArtifactError::BooleanTag {
                field: "terminal_quiescent",
                tag: 2,
            })
        ));
        crate::test_complete!("forced_schedule_artifact_rejects_hostile_encodings");
    }

    #[test]
    fn forced_schedule_artifact_refuses_partial_authority() {
        init_test("forced_schedule_artifact_refuses_partial_authority");
        let config = LabConfig::new(0xA471_0BAD).max_steps(128);
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config, observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start partial artifact fixture capture");
        let partial = source
            .finish_forced_schedule_recording()
            .expect("finish represented partial capture");

        assert_eq!(
            partial.to_canonical_bytes(),
            Err(ForcedScheduleArtifactError::Schedule(
                ForcedScheduleError::PartialSource
            ))
        );
        crate::test_complete!("forced_schedule_artifact_refuses_partial_authority");
    }

    #[test]
    fn forced_schedule_candidate_executes_only_retained_source_choices() {
        init_test("forced_schedule_candidate_executes_only_retained_source_choices");
        let config = LabConfig::new(0xCAAD_1DA7).worker_count(2).max_steps(128);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), Arc::clone(&source_observations));
        source
            .start_forced_schedule_recording(32)
            .expect("start exact dispatch capture");
        let source_report = source.run_until_quiescent_with_report();
        assert!(source_report.quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete exact dispatch projection");
        let limits = ForcedScheduleCandidateLimits::new(32, 32, 128);
        let all_indices = (0..schedule.dispatches().len()).collect::<Vec<_>>();
        let full = schedule
            .derive_candidate(&all_indices, limits)
            .expect("derive full-retention candidate");
        assert_eq!(full.version(), FORCED_SCHEDULE_CANDIDATE_SCHEMA_VERSION);
        assert_eq!(full.source_version(), FORCED_SCHEDULE_SCHEMA_VERSION);
        assert_eq!(full.seed(), schedule.seed());
        assert_eq!(full.config_hash(), schedule.config_hash());
        assert_eq!(
            full.source_terminal_schedule_hash(),
            schedule.terminal_schedule_hash()
        );
        assert_eq!(full.source_dispatch_count(), schedule.dispatches().len());
        assert_eq!(
            full.dispatches()
                .iter()
                .map(ForcedScheduleCandidateDispatch::source_index)
                .collect::<Vec<_>>(),
            all_indices
        );

        let exact_observations = Arc::new(Mutex::new(Vec::new()));
        let mut exact_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&exact_observations));
        let exact_report = exact_replay
            .run_forced_schedule(&schedule, ForcedScheduleLimits::new(32, 128))
            .expect("complete source schedule must still replay exactly");

        let full_observations = Arc::new(Mutex::new(Vec::new()));
        let mut full_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&full_observations));
        let full_report = full_replay
            .run_forced_schedule_candidate(&full, limits)
            .expect("full candidate must execute without RNG fallback");
        assert_eq!(
            full_report.termination,
            ForcedScheduleCandidateTermination::Quiescent
        );
        assert_eq!(full_report.consumed_source_indices, all_indices);
        assert!(full_report.lab.quiescent);
        assert_eq!(full_report.lab.steps_total, schedule.terminal_steps());
        assert_eq!(full_report.lab.now_nanos, schedule.terminal_nanos());
        assert_eq!(
            full_report.lab.trace_certificate.schedule_hash,
            schedule.terminal_schedule_hash()
        );
        assert_eq!(full_report.lab.steps_total, exact_report.steps);
        assert_eq!(full_report.lab.now_nanos, exact_report.terminal_nanos);
        assert_eq!(
            full_report.lab.trace_certificate.schedule_hash,
            exact_report.schedule_hash
        );
        assert_eq!(full_report.lab.quiescent, exact_report.quiescent);
        assert_eq!(*full_observations.lock(), *source_observations.lock());
        assert_eq!(*full_observations.lock(), *exact_observations.lock());

        let retained = schedule
            .derive_candidate(&[1], limits)
            .expect("derive one-choice candidate");
        assert_eq!(retained.dispatches()[0].source_index(), 1);
        assert_eq!(
            retained.dispatches()[0].task(),
            schedule.dispatches()[1].task()
        );
        assert_eq!(
            retained.dispatches()[0].worker(),
            schedule.dispatches()[1].worker()
        );
        assert_eq!(
            retained.dispatches()[0].lane(),
            schedule.dispatches()[1].lane()
        );
        assert_eq!(
            retained.dispatches()[0].source_step(),
            schedule.dispatches()[1].at_step()
        );
        assert_eq!(
            retained.dispatches()[0].source_nanos(),
            schedule.dispatches()[1].at_nanos()
        );
        let retained_observations = Arc::new(Mutex::new(Vec::new()));
        let mut retained_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&retained_observations));
        let retained_report = retained_replay
            .run_forced_schedule_candidate(&retained, limits)
            .expect("retained source choice must execute directly");
        assert_eq!(
            retained_report.termination,
            ForcedScheduleCandidateTermination::Exhausted
        );
        assert_eq!(retained_report.consumed_source_indices, vec![1]);
        assert_eq!(retained_observations.lock().len(), 1);
        assert!(!retained_report.lab.quiescent);

        let empty = schedule
            .derive_candidate(&[], limits)
            .expect("derive empty deletion candidate");
        let empty_observations = Arc::new(Mutex::new(Vec::new()));
        let mut empty_replay = forced_schedule_fixture(config, Arc::clone(&empty_observations));
        let empty_report = empty_replay
            .run_forced_schedule_candidate(&empty, limits)
            .expect("empty candidate must report exhaustion without RNG polling");
        assert_eq!(
            empty_report.termination,
            ForcedScheduleCandidateTermination::Exhausted
        );
        assert!(empty_report.consumed_source_indices.is_empty());
        assert_eq!(empty_report.work_units, 0);
        assert!(empty_observations.lock().is_empty());
        crate::test_complete!("forced_schedule_candidate_executes_only_retained_source_choices");
    }

    #[test]
    fn forced_schedule_candidate_admission_is_bounded_and_source_derived() {
        init_test("forced_schedule_candidate_admission_is_bounded_and_source_derived");
        let config = LabConfig::new(0xCAAD_B0AD).worker_count(2).max_steps(128);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), source_observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start exact dispatch capture");
        assert!(source.run_until_quiescent_with_report().quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete exact dispatch projection");
        let source_len = schedule.dispatches().len();
        let limits = ForcedScheduleCandidateLimits::new(32, 32, 128);

        assert!(matches!(
            schedule.derive_candidate(&[], ForcedScheduleCandidateLimits::new(0, 32, 128)),
            Err(ForcedScheduleError::ZeroCandidateLimit {
                limit_name: "max_source_dispatches"
            })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[], ForcedScheduleCandidateLimits::new(32, 0, 128)),
            Err(ForcedScheduleError::ZeroCandidateLimit {
                limit_name: "max_candidate_dispatches"
            })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[], ForcedScheduleCandidateLimits::new(32, 32, 0)),
            Err(ForcedScheduleError::ZeroCandidateLimit {
                limit_name: "max_work_units"
            })
        ));
        assert!(matches!(
            schedule.derive_candidate(
                &[],
                ForcedScheduleCandidateLimits::new(source_len - 1, 32, 128)
            ),
            Err(ForcedScheduleError::CandidateSourceLimitExceeded { .. })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[0, 1], ForcedScheduleCandidateLimits::new(32, 1, 128)),
            Err(ForcedScheduleError::DispatchLimitExceeded { .. })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[0, 0], limits),
            Err(ForcedScheduleError::CandidateIndexOrder { .. })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[1, 0], limits),
            Err(ForcedScheduleError::CandidateIndexOrder { .. })
        ));
        assert!(matches!(
            schedule.derive_candidate(&[source_len], limits),
            Err(ForcedScheduleError::CandidateIndexOutOfRange { .. })
        ));

        let all_indices = (0..source_len).collect::<Vec<_>>();
        let full = schedule
            .derive_candidate(&all_indices, limits)
            .expect("derive valid full candidate");
        let work_limited_observations = Arc::new(Mutex::new(Vec::new()));
        let mut work_limited =
            forced_schedule_fixture(config.clone(), Arc::clone(&work_limited_observations));
        assert!(matches!(
            work_limited.run_forced_schedule_candidate(
                &full,
                ForcedScheduleCandidateLimits::new(32, 32, 1)
            ),
            Err(ForcedScheduleError::CandidateWorkLimitExceeded { .. })
        ));
        assert!(
            work_limited_observations.lock().is_empty(),
            "minimum work refusal polled a task"
        );

        let mut wrong_task = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_task.dispatches[0].dispatch.task.0 ^= 1;
        let wrong_task_observations = Arc::new(Mutex::new(Vec::new()));
        let mut wrong_task_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&wrong_task_observations));
        assert!(matches!(
            wrong_task_replay.run_forced_schedule_candidate(&wrong_task, limits),
            Err(ForcedScheduleError::TaskUnavailable { index: 0, .. })
        ));
        assert!(wrong_task_observations.lock().is_empty());

        let mut wrong_config = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_config.config_hash ^= 1;
        let wrong_config_observations = Arc::new(Mutex::new(Vec::new()));
        let mut wrong_config_replay =
            forced_schedule_fixture(config.clone(), Arc::clone(&wrong_config_observations));
        assert!(matches!(
            wrong_config_replay.run_forced_schedule_candidate(&wrong_config, limits),
            Err(ForcedScheduleError::ConfigMismatch { .. })
        ));
        assert!(wrong_config_observations.lock().is_empty());

        let mut wrong_candidate_version = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_candidate_version.version += 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_candidate_version, limits),
            Err(ForcedScheduleError::CandidateSchemaMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_source_version = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_source_version.source_version += 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_source_version, limits),
            Err(ForcedScheduleError::SchemaMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_seed = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_seed.seed ^= 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_seed, limits),
            Err(ForcedScheduleError::SeedMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_order = schedule
            .derive_candidate(&[0, 1], limits)
            .expect("derive source-owned candidate");
        wrong_order.dispatches.swap(0, 1);
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_order, limits),
            Err(ForcedScheduleError::CandidateIndexOrder { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_worker = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_worker.dispatches[0].dispatch.worker ^= 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_worker, limits),
            Err(ForcedScheduleError::WorkerMismatch { index: 0, .. })
                | Err(ForcedScheduleError::LaneMismatch { index: 0, .. })
        ));
        assert!(observations.lock().is_empty());

        let mut wrong_lane = schedule
            .derive_candidate(&[0], limits)
            .expect("derive source-owned candidate");
        wrong_lane.dispatches[0].dispatch.lane = match wrong_lane.dispatches[0].dispatch.lane {
            DispatchLane::Cancel => DispatchLane::Ready,
            DispatchLane::Timed | DispatchLane::Ready | DispatchLane::Stolen => {
                DispatchLane::Cancel
            }
        };
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config, Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule_candidate(&wrong_lane, limits),
            Err(ForcedScheduleError::LaneMismatch { index: 0, .. })
                | Err(ForcedScheduleError::WorkerMismatch { index: 0, .. })
        ));
        assert!(observations.lock().is_empty());
        crate::test_complete!("forced_schedule_candidate_admission_is_bounded_and_source_derived");
    }

    #[test]
    fn forced_schedule_mutations_refuse_before_the_wrong_poll() {
        init_test("forced_schedule_mutations_refuse_before_the_wrong_poll");
        let config = LabConfig::new(0xF0CE_D5CE).worker_count(2).max_steps(128);
        let source_observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), source_observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start exact dispatch capture");
        assert!(source.run_until_quiescent_with_report().quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete exact dispatch projection");

        let mut wrong_tick = schedule.clone();
        for dispatch in &mut wrong_tick.dispatches {
            dispatch.at_step += 1;
        }
        wrong_tick.terminal_steps += 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_tick, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::EarlyRunnable { .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "tick mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "tick refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);

        let mut wrong_time = schedule.clone();
        for dispatch in &mut wrong_time.dispatches {
            dispatch.at_nanos += 1;
        }
        wrong_time.terminal_nanos += 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_time, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::TimeMismatch { index: 0, .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "time mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "time refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);

        let mut wrong_task = schedule.clone();
        wrong_task.dispatches[0].task.0 ^= 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_task, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::TaskUnavailable { index: 0, .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "generation mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "task refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);

        let mut wrong_worker = schedule.clone();
        wrong_worker.dispatches[0].worker ^= 1;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_worker, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::WorkerMismatch { index: 0, .. })
                | Err(ForcedScheduleError::LaneMismatch { index: 0, .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "worker mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "worker refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);

        let mut wrong_lane = schedule.clone();
        wrong_lane.dispatches[0].lane = match wrong_lane.dispatches[0].lane {
            DispatchLane::Cancel => DispatchLane::Ready,
            DispatchLane::Timed | DispatchLane::Ready | DispatchLane::Stolen => {
                DispatchLane::Cancel
            }
        };
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_lane, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::LaneMismatch { index: 0, .. })
                | Err(ForcedScheduleError::WorkerMismatch { index: 0, .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "lane mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "lane refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);

        let mut wrong_order = schedule.clone();
        wrong_order.dispatches.swap(0, 1);
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config, Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&wrong_order, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::StepOrder { .. })
        ));
        assert!(
            observations.lock().is_empty(),
            "order mismatch polled a task"
        );
        assert!(
            replay.run_until_quiescent_with_report().quiescent,
            "order refusal corrupted runnable work"
        );
        assert_eq!(observations.lock().len(), 6);
        crate::test_complete!("forced_schedule_mutations_refuse_before_the_wrong_poll");
    }

    #[test]
    fn forced_schedule_partial_and_resource_limited_receipts_fail_closed() {
        init_test("forced_schedule_partial_and_resource_limited_receipts_fail_closed");
        let config = LabConfig::new(0xF0CE_D5CE).max_steps(128);

        let mut source = LabRuntime::new(config.clone());
        source
            .start_forced_schedule_recording(1)
            .expect("start empty terminal-time capture");
        source.advance_time_to(Time::from_nanos(17));
        let terminal_time_only = source
            .finish_forced_schedule_recording()
            .expect("finish empty terminal-time capture");
        assert!(terminal_time_only.dispatches().is_empty());
        let mut replay = LabRuntime::new(config.clone());
        assert!(matches!(
            replay.run_forced_schedule(&terminal_time_only, ForcedScheduleLimits::new(1, 1)),
            Err(ForcedScheduleError::TerminalMismatch {
                expected_nanos: 17,
                actual_nanos: 0,
                ..
            })
        ));

        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start deliberately partial capture");
        let partial = source
            .finish_forced_schedule_recording()
            .expect("partial source is represented, not silently promoted");
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert_eq!(
            replay.run_forced_schedule(&partial, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::PartialSource)
        );
        assert!(observations.lock().is_empty());

        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), observations);
        source
            .start_forced_schedule_recording(1)
            .expect("start deliberately bounded capture");
        assert!(source.run_until_quiescent_with_report().quiescent);
        assert!(matches!(
            source.finish_forced_schedule_recording(),
            Err(ForcedScheduleError::RecordingLimitExceeded { max_dispatches: 1 })
        ));

        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut source = forced_schedule_fixture(config.clone(), observations);
        source
            .start_forced_schedule_recording(32)
            .expect("start exact dispatch capture");
        assert!(source.run_until_quiescent_with_report().quiescent);
        let schedule = source
            .finish_forced_schedule_recording()
            .expect("complete exact dispatch projection");

        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), observations);
        assert!(matches!(
            replay.run_forced_schedule(&schedule, ForcedScheduleLimits::new(1, 128)),
            Err(ForcedScheduleError::DispatchLimitExceeded { .. })
        ));

        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config.clone(), Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&schedule, ForcedScheduleLimits::new(32, 1)),
            Err(ForcedScheduleError::WorkLimitExceeded { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut mismatched_config = config.clone();
        mismatched_config.enable_cancellation_oracle = !config.enable_cancellation_oracle;
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(mismatched_config, Arc::clone(&observations));
        assert!(matches!(
            replay.run_forced_schedule(&schedule, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::ConfigMismatch { .. })
        ));
        assert!(observations.lock().is_empty());

        let mut truncated = schedule.clone();
        truncated.dispatches.pop();
        let observations = Arc::new(Mutex::new(Vec::new()));
        let mut replay = forced_schedule_fixture(config, observations);
        assert!(matches!(
            replay.run_forced_schedule(&truncated, ForcedScheduleLimits::new(32, 128)),
            Err(ForcedScheduleError::ScheduleExhausted { .. })
                | Err(ForcedScheduleError::CertificateMismatch { .. })
        ));
        crate::test_complete!("forced_schedule_partial_and_resource_limited_receipts_fail_closed");
    }

    /// Regression test: replay recorder must capture the actual completion
    /// severity from the finalized task record, not always `Severity::Ok`.
    ///
    /// `create_task` wraps futures to always return `Outcome::Ok(())` — the
    /// real severity is determined by the cancel protocol state machine. This
    /// test puts a task through the cancel protocol and verifies the replay
    /// trace records the correct `Cancelled` severity.
    #[test]
    fn replay_records_correct_severity_for_cancelled_task() {
        init_test("replay_records_correct_severity_for_cancelled_task");

        let config = LabConfig::new(42)
            .panic_on_leak(false)
            .with_default_replay_recording();
        let mut runtime = LabRuntime::new(config);
        let root = runtime
            .state
            .create_root_region(crate::types::Budget::INFINITE);

        // Create a task that yields once then completes with Ok.
        // The yield allows us to cancel the task before it finishes.
        let (task_id, _) = runtime
            .state
            .create_task(root, crate::types::Budget::INFINITE, async {
                crate::runtime::yield_now::yield_now().await;
            })
            .expect("create task");
        runtime.scheduler.lock().schedule(task_id, 0);

        // Step once: task yields (Pending)
        runtime.step();

        // Put the task through cancel protocol: CancelRequested → Cancelling
        let cancel_effects = runtime
            .state
            .update_task(task_id, |record| {
                let effects =
                    record.request_cancel(crate::types::CancelReason::user("test-cancel"));
                let _ = record.acknowledge_cancel();
                // Task is now in Cancelling state
                assert!(
                    matches!(
                        record.state,
                        crate::record::task::TaskState::Cancelling { .. }
                    ),
                    "task should be in Cancelling state"
                );
                effects
            })
            .unwrap();

        // Reschedule and run to completion: the cancel protocol will
        // complete it as Cancelled when the wrapped future returns Ok.
        runtime.scheduler.lock().schedule_cancel(task_id, 0);
        let (_, cancel_wakes) = cancel_effects.into_parts();
        cancel_wakes.dispatch();
        runtime.run_until_quiescent();

        // Verify the task completed as Cancelled
        if let Some(record) = runtime.state.task(task_id) {
            assert!(
                matches!(
                    record.state,
                    crate::record::task::TaskState::Completed(crate::types::Outcome::Cancelled(_))
                ),
                "task should be Completed(Cancelled), got {:?}",
                record.state
            );
        }

        // Check the replay trace for the TaskCompleted event
        let replay = runtime
            .replay_recorder()
            .snapshot()
            .expect("replay recording enabled");
        let completed_events: Vec<_> = replay
            .events
            .iter()
            .filter(|e| matches!(e, crate::trace::replay::ReplayEvent::TaskCompleted { .. }))
            .collect();

        assert!(
            !completed_events.is_empty(),
            "should have at least one TaskCompleted event"
        );

        // The severity should be Cancelled (2), not Ok (0)
        for event in &completed_events {
            if let crate::trace::replay::ReplayEvent::TaskCompleted { outcome, .. } = event {
                let expected = crate::types::Severity::Cancelled.as_u8();
                crate::assert_with_log!(
                    *outcome == expected,
                    "severity should be Cancelled (2)",
                    expected,
                    *outcome
                );
            }
        }

        crate::test_complete!("replay_records_correct_severity_for_cancelled_task");
    }

    #[test]
    fn replay_recording_metadata_is_stable_for_same_seed() {
        init_test("replay_recording_metadata_is_stable_for_same_seed");

        let mut first = LabRuntime::new(LabConfig::new(42).with_default_replay_recording());
        let mut second = LabRuntime::new(LabConfig::new(42).with_default_replay_recording());

        let first_trace = first
            .finish_replay_trace()
            .expect("first replay recording enabled");
        let second_trace = second
            .finish_replay_trace()
            .expect("second replay recording enabled");

        crate::assert_with_log!(
            first_trace.metadata == second_trace.metadata,
            "replay metadata should match for identical seeds",
            &first_trace.metadata,
            &second_trace.metadata
        );
        crate::assert_with_log!(
            first_trace.events == second_trace.events,
            "replay events should match for identical seeds",
            &first_trace.events,
            &second_trace.events
        );
        crate::assert_with_log!(
            first_trace.metadata.recorded_at == 0,
            "recorded_at defaults to deterministic zero stamp",
            0u64,
            first_trace.metadata.recorded_at
        );

        crate::test_complete!("replay_recording_metadata_is_stable_for_same_seed");
    }

    // =========================================================================
    // Pure data-type tests (wave 40 – CyanBarn)
    // =========================================================================

    #[test]
    fn lab_trace_certificate_summary_debug_clone_copy_eq() {
        let summary = LabTraceCertificateSummary {
            event_hash: 123,
            event_count: 456,
            schedule_hash: 789,
        };
        let copied = summary;
        let cloned = summary;
        assert_eq!(copied, cloned);
        assert_ne!(
            summary,
            LabTraceCertificateSummary {
                event_hash: 0,
                event_count: 456,
                schedule_hash: 789,
            }
        );
        let dbg = format!("{summary:?}");
        assert!(dbg.contains("LabTraceCertificateSummary"));
    }

    #[test]
    fn virtual_time_report_debug_clone_copy_eq() {
        let report = VirtualTimeReport {
            steps: 100,
            auto_advances: 5,
            total_wakeups: 10,
            time_start: Time::ZERO,
            time_end: Time::from_millis(500),
            virtual_elapsed_nanos: 500_000_000,
            termination: AutoAdvanceTermination::Quiescent,
        };
        let copied = report;
        assert_eq!(copied, report);
        assert_eq!(report.virtual_elapsed_ms(), 500);
        assert_eq!(report.virtual_elapsed_secs(), 0);
        let dbg = format!("{report:?}");
        assert!(dbg.contains("VirtualTimeReport"));
    }

    // =========================================================================
    // AutoAdvanceTermination tests (bead 56c785)
    // =========================================================================

    #[asupersync::lab_test(seeds = 42..43)]
    fn auto_advance_quiescent_termination(lab: &mut LabRuntime) {
        // No tasks enqueued → immediately quiescent
        let report = lab.run_with_auto_advance();
        assert_eq!(
            report.termination,
            AutoAdvanceTermination::Quiescent,
            "empty runtime should terminate as quiescent"
        );
    }

    #[test]
    fn auto_advance_step_limit_termination() {
        init_test("auto_advance_step_limit_termination");
        let mut lab = LabRuntime::new(LabConfig::new(42).max_steps(0));
        let report = lab.run_with_auto_advance();
        assert_eq!(
            report.termination,
            AutoAdvanceTermination::StepLimitReached,
            "zero max_steps should terminate as step-limit-reached"
        );
        crate::test_complete!("auto_advance_step_limit_termination");
    }

    #[test]
    fn auto_advance_stuck_bailout_termination() {
        init_test("auto_advance_stuck_bailout_termination");
        let config = LabConfig::new(42)
            .with_auto_advance()
            .no_step_limit()
            .futurelock_max_idle_steps(0);
        let mut lab = LabRuntime::new(config);
        let root = lab.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = lab
            .state
            .create_task(root, Budget::INFINITE, async {
                std::future::pending::<()>().await;
            })
            .expect("create pending task");
        lab.scheduler.lock().schedule(task_id, 0);

        let report = lab.run_with_auto_advance();
        assert_eq!(
            report.termination,
            AutoAdvanceTermination::StuckBailout,
            "pending task without deadlines should terminate via stuck bailout"
        );
        assert!(
            !lab.is_quiescent(),
            "stuck bailout should preserve non-quiescent state for diagnosis"
        );
        assert_eq!(
            report.auto_advances, 0,
            "stuck bailout path should not auto-advance virtual time without deadlines"
        );
        crate::test_complete!("auto_advance_stuck_bailout_termination");
    }

    #[test]
    fn auto_advance_termination_display() {
        assert_eq!(
            format!("{}", AutoAdvanceTermination::Quiescent),
            "quiescent"
        );
        assert_eq!(
            format!("{}", AutoAdvanceTermination::StepLimitReached),
            "step-limit-reached"
        );
        assert_eq!(
            format!("{}", AutoAdvanceTermination::StuckBailout),
            "stuck-bailout"
        );
    }

    #[test]
    fn auto_advance_termination_debug_clone_copy_eq_hash() {
        use std::collections::HashSet;
        let variants = [
            AutoAdvanceTermination::Quiescent,
            AutoAdvanceTermination::StepLimitReached,
            AutoAdvanceTermination::StuckBailout,
        ];
        // Copy + Clone + Eq
        for &v in &variants {
            let copied = v;
            let cloned = v;
            assert_eq!(copied, cloned);
        }
        // Hash uniqueness
        let mut set = HashSet::new();
        for &v in &variants {
            assert!(set.insert(v));
        }
        assert_eq!(set.len(), 3);
        // Debug contains type name
        let dbg = format!("{:?}", AutoAdvanceTermination::StuckBailout);
        assert!(dbg.contains("StuckBailout"));
    }

    #[test]
    fn harness_attachment_kind_debug_clone_copy_eq_hash_ord_display() {
        use std::collections::HashSet;
        let kinds = [
            HarnessAttachmentKind::CrashPack,
            HarnessAttachmentKind::ReplayTrace,
            HarnessAttachmentKind::Trace,
            HarnessAttachmentKind::Other,
        ];
        // Display
        assert_eq!(format!("{}", kinds[0]), "crashpack");
        assert_eq!(format!("{}", kinds[1]), "replay_trace");
        assert_eq!(format!("{}", kinds[2]), "trace");
        assert_eq!(format!("{}", kinds[3]), "other");
        // Copy/Clone/Eq
        for &k in &kinds {
            let copied = k;
            let cloned = k;
            assert_eq!(copied, cloned);
        }
        // Hash
        let mut set = HashSet::new();
        for &k in &kinds {
            set.insert(k);
        }
        assert_eq!(set.len(), 4);
        // Ord (derive ordering: CrashPack < ReplayTrace < Trace < Other)
        assert!(HarnessAttachmentKind::CrashPack < HarnessAttachmentKind::ReplayTrace);
        assert!(HarnessAttachmentKind::ReplayTrace < HarnessAttachmentKind::Trace);
        assert!(HarnessAttachmentKind::Trace < HarnessAttachmentKind::Other);
        let mut sorted = [kinds[3], kinds[0], kinds[2], kinds[1]];
        sorted.sort();
        assert_eq!(sorted, kinds);
    }

    #[test]
    fn harness_attachment_ref_debug_clone_eq_hash() {
        use std::collections::HashSet;
        let ref1 = HarnessAttachmentRef::crashpack("crash.bin");
        let ref2 = HarnessAttachmentRef::replay_trace("replay.bin");
        let ref3 = HarnessAttachmentRef::trace("trace.ndjson");
        assert_eq!(ref1.kind, HarnessAttachmentKind::CrashPack);
        assert_eq!(ref2.kind, HarnessAttachmentKind::ReplayTrace);
        assert_eq!(ref3.kind, HarnessAttachmentKind::Trace);
        let cloned = ref1.clone();
        assert_eq!(cloned, ref1);
        assert_ne!(ref1, ref2);
        let dbg = format!("{ref1:?}");
        assert!(dbg.contains("HarnessAttachmentRef"));
        let mut set = HashSet::new();
        set.insert(ref1.clone());
        set.insert(ref2);
        set.insert(ref1); // duplicate
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn chaos_config_summary_debug_clone_copy_partial_eq() {
        let summary = ChaosConfigSummary {
            seed: 42,
            cancel_probability: 0.1,
            delay_probability: 0.2,
            io_error_probability: 0.05,
            wakeup_storm_probability: 0.01,
            budget_exhaust_probability: 0.03,
        };
        let copied = summary;
        let cloned = summary;
        assert_eq!(copied, cloned);
        let dbg = format!("{summary:?}");
        assert!(dbg.contains("ChaosConfigSummary"));
    }

    #[test]
    fn obligation_leak_debug_clone_eq_display() {
        let leak = ObligationLeak {
            obligation: ObligationId::new_for_test(1, 0),
            kind: ObligationKind::SendPermit,
            holder: TaskId::from_arena(crate::util::ArenaIndex::new(1, 0)),
            region: RegionId::new_for_test(0, 0),
        };
        let cloned = leak.clone();
        assert_eq!(cloned, leak);
        let dbg = format!("{leak:?}");
        assert!(dbg.contains("ObligationLeak"));
        let display = format!("{leak}");
        assert!(display.contains("obligation="));
        assert!(display.contains("kind=SendPermit"));
        assert!(display.contains("holder="));
        assert!(display.contains("region="));
    }

    // ================================================================
    // CONFORMANCE TESTS: LabRuntime Deterministic Seed Reproduction
    // ================================================================
    //
    // Golden tests verifying the non-negotiable determinism invariants:
    // (1) Same seed produces byte-identical execution trace
    // (2) Virtual-time advances in same order across replays
    // (3) Scheduler lottery with same seed picks same tasks
    // (4) Chaos injection with same seed identical
    // (5) Cross-thread panic semantics preserved
    //
    // These conformance tests ensure LabRuntime provides reproducible
    // execution for debugging, testing, and formal verification.

    /// CONFORMANCE: Same seed produces byte-identical execution trace.
    ///
    /// Verifies that identical configuration and program produce identical
    /// trace fingerprints, event counts, and schedule certificates.
    #[test]
    fn conformance_identical_seed_identical_trace() {
        init_test("conformance_identical_seed_identical_trace");

        let seed = 42_u64;
        let config = LabConfig::new(seed).worker_count(2).max_steps(1000);

        // Run same program with same seed twice
        let mut reports = Vec::new();
        for run_id in 0..2 {
            let mut runtime = LabRuntime::new(config.clone());
            let root = runtime.state.create_root_region(Budget::INFINITE);

            // Create deterministic workload with multiple tasks
            for i in 0..5 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        // Simulate work with deterministic operations
                        for j in 0..10 {
                            futures_lite::future::yield_now().await;
                            if (i + j) % 3 == 0 {
                                let now =
                                    crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                                crate::time::sleep(now, Duration::from_millis(1)).await;
                            }
                        }
                        i * 100 + run_id
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            let report = runtime.run_until_quiescent_with_report();
            reports.push(report);
        }

        // Verify identical traces
        let report1 = &reports[0];
        let report2 = &reports[1];

        crate::assert_with_log!(
            report1.seed == report2.seed,
            "seeds should be identical",
            report1.seed,
            report2.seed
        );

        crate::assert_with_log!(
            report1.trace_fingerprint == report2.trace_fingerprint,
            "trace fingerprints should be identical",
            report1.trace_fingerprint,
            report2.trace_fingerprint
        );

        crate::assert_with_log!(
            report1.trace_certificate.event_hash == report2.trace_certificate.event_hash,
            "event hashes should be identical",
            report1.trace_certificate.event_hash,
            report2.trace_certificate.event_hash
        );

        crate::assert_with_log!(
            report1.trace_certificate.event_count == report2.trace_certificate.event_count,
            "event counts should be identical",
            report1.trace_certificate.event_count,
            report2.trace_certificate.event_count
        );

        crate::assert_with_log!(
            report1.trace_certificate.schedule_hash == report2.trace_certificate.schedule_hash,
            "schedule hashes should be identical",
            report1.trace_certificate.schedule_hash,
            report2.trace_certificate.schedule_hash
        );

        crate::test_complete!("conformance_identical_seed_identical_trace");
    }

    /// CONFORMANCE: Virtual-time advances in same order across replays.
    ///
    /// Verifies that virtual time progression and auto-advancement
    /// behavior is deterministic across runs with the same seed.
    #[test]
    fn conformance_virtual_time_deterministic_advancement() {
        init_test("conformance_virtual_time_deterministic_advancement");

        let config = LabConfig::new(123).worker_count(1);

        crate::lab::assert_deterministic(config, |runtime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);
            let initial_time = runtime.now();

            // Create tasks that sleep for different durations to test time advancement
            let durations = [
                Duration::from_millis(10),
                Duration::from_millis(5),
                Duration::from_millis(15),
                Duration::from_millis(1),
            ];

            for (i, duration) in durations.iter().enumerate() {
                let dur = *duration;
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        let now = crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                        crate::time::sleep(now, dur).await;
                        i
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            // Use auto-advance to let virtual time progress deterministically
            let vtime_report = runtime.run_with_auto_advance();

            // Verify time advanced
            crate::assert_with_log!(
                vtime_report.time_end > initial_time,
                "virtual time should have advanced",
                vtime_report.time_end,
                initial_time
            );

            crate::assert_with_log!(
                vtime_report.auto_advances > 0,
                "should have auto-advanced virtual time",
                vtime_report.auto_advances,
                0
            );

            crate::assert_with_log!(
                vtime_report.termination == AutoAdvanceTermination::Quiescent,
                "should reach quiescence",
                vtime_report.termination,
                AutoAdvanceTermination::Quiescent
            );
        });

        crate::test_complete!("conformance_virtual_time_deterministic_advancement");
    }

    /// CONFORMANCE: Scheduler lottery with same seed picks same tasks.
    ///
    /// Verifies that scheduler decisions (task selection, worker assignment)
    /// are deterministic given the same random seed.
    #[test]
    fn conformance_scheduler_deterministic_lottery() {
        init_test("conformance_scheduler_deterministic_lottery");

        let config = LabConfig::new(456).worker_count(4);

        let mut schedule_sequences = Vec::new();

        // Run same workload multiple times to capture scheduler decisions
        for run in 0..2 {
            let mut runtime = LabRuntime::new(config.clone());
            let root = runtime.state.create_root_region(Budget::INFINITE);
            let mut task_order = Vec::new();

            // Create many competing tasks to stress scheduler lottery
            for task_idx in 0..20 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        // Add some yield points to allow preemption
                        for _ in 0..3 {
                            futures_lite::future::yield_now().await;
                        }
                        task_idx
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            // Execute and capture schedule certificate
            runtime.run_until_quiescent();
            let cert = runtime.certificate();
            task_order.push((run, cert.decisions(), cert.hash()));
            schedule_sequences.push(task_order);
        }

        // Verify scheduler made same decisions across runs
        let seq1 = &schedule_sequences[0];
        let seq2 = &schedule_sequences[1];

        crate::assert_with_log!(
            seq1.len() == seq2.len(),
            "should have same number of scheduling decision points",
            seq1.len(),
            seq2.len()
        );

        for (i, ((_run1, count1, hash1), (_run2, count2, hash2))) in
            seq1.iter().zip(seq2.iter()).enumerate()
        {
            crate::assert_with_log!(
                count1 == count2,
                &format!("decision count should be identical at point {}", i),
                count1,
                count2
            );

            crate::assert_with_log!(
                hash1 == hash2,
                &format!("schedule hash should be identical at point {}", i),
                hash1,
                hash2
            );
        }

        crate::test_complete!("conformance_scheduler_deterministic_lottery");
    }

    /// CONFORMANCE: Chaos injection with same seed produces identical outcomes.
    ///
    /// Verifies that chaos injection (cancellation, delays, errors) is
    /// deterministically reproducible with the same chaos seed.
    #[test]
    fn conformance_chaos_injection_deterministic() {
        init_test("conformance_chaos_injection_deterministic");

        let chaos_config = crate::lab::chaos::ChaosConfig::new(789)
            .with_cancel_probability(0.1)
            .with_delay_probability(0.05)
            .with_io_error_probability(0.02);
        let config = LabConfig::new(999).with_chaos(chaos_config);

        crate::lab::assert_deterministic(config, |runtime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);

            // Create workload susceptible to chaos injection
            for i in 0..10 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        // Multiple poll points where chaos can be injected
                        for j in 0..20 {
                            futures_lite::future::yield_now().await;
                            if j % 5 == 0 {
                                let now =
                                    crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                                crate::time::sleep(now, Duration::from_millis(1)).await;
                            }
                        }
                        i
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            runtime.run_until_quiescent();

            // Verify chaos was actually applied
            let chaos_stats = runtime.chaos_stats();
            let total_decisions = chaos_stats.decision_points;

            crate::assert_with_log!(
                total_decisions > 0,
                "chaos should have made some decisions",
                total_decisions,
                0
            );
        });

        crate::test_complete!("conformance_chaos_injection_deterministic");
    }

    /// CONFORMANCE: Cross-thread panic semantics are preserved deterministically.
    ///
    /// Verifies that panic propagation and cleanup across workers/regions
    /// follows the same deterministic pattern with identical seeds.
    #[test]
    fn conformance_panic_semantics_deterministic() {
        init_test("conformance_panic_semantics_deterministic");

        let config = LabConfig::new(333)
            .worker_count(3)
            .panic_on_leak(false)
            .max_steps(10_000); // Fail diagnostically instead of hanging if panic cleanup regresses

        crate::lab::assert_deterministic(config, |runtime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);

            // Create tasks where one will panic
            for i in 0..5 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        // Task 2 will deterministically panic
                        assert!(i != 2, "deterministic panic in task {}", i);

                        // Other tasks continue working
                        for _j in 0..10 {
                            futures_lite::future::yield_now().await;
                        }
                        i * 10
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            // The lab trace no longer exposes a dedicated `TaskPanicked` data
            // variant. Drive the panic-bearing run to quiescence once and
            // inspect that same run's report rather than a second already-idle
            // pass.
            let report = runtime.run_until_quiescent_with_report();
            let trace_events = runtime.trace().snapshot();
            let complete_events = trace_events
                .iter()
                .filter(|event| event.kind == TraceEventKind::Complete)
                .count();

            crate::assert_with_log!(
                complete_events > 0,
                "should have recorded task completion activity",
                complete_events,
                0
            );

            // Verify deterministic cleanup occurred
            crate::assert_with_log!(
                report.quiescent,
                "runtime should reach quiescence despite panic",
                report.quiescent,
                false
            );
        });

        crate::test_complete!("conformance_panic_semantics_deterministic");
    }

    /// CONFORMANCE: Comprehensive multi-run determinism verification.
    ///
    /// Combines all previous conformance aspects into a stress test
    /// that verifies determinism across many execution runs.
    #[test]
    fn conformance_comprehensive_determinism_stress() {
        init_test("conformance_comprehensive_determinism_stress");

        let chaos_config = crate::lab::chaos::ChaosConfig::new(555)
            .with_cancel_probability(0.05)
            .with_delay_probability(0.03);
        let config = LabConfig::new(777)
            .worker_count(4)
            .with_chaos(chaos_config)
            .max_steps(5000);

        // Use assert_deterministic_multi for extra confidence
        crate::lab::assert_deterministic_multi(&config, 3, |runtime| {
            let root = runtime.state.create_root_region(Budget::INFINITE);

            // Complex workload mixing all runtime features
            for i in 0..15 {
                let (task_id, _handle) = runtime
                    .state
                    .create_task(root, Budget::INFINITE, async move {
                        // Mix of operations: yields, sleeps, work
                        for j in 0..30 {
                            match (i + j) % 4 {
                                0 => futures_lite::future::yield_now().await,
                                1 => {
                                    let now =
                                        crate::cx::Cx::current().map_or(Time::ZERO, |cx| cx.now());
                                    crate::time::sleep(now, Duration::from_millis(j as u64 % 5))
                                        .await;
                                }
                                2 => {
                                    // Simulate CPU work
                                    let mut sum = 0_u64;
                                    for k in 0..100 {
                                        sum = sum.wrapping_add(k);
                                    }
                                    let _ = sum;
                                }
                                _ => futures_lite::future::yield_now().await,
                            }
                        }
                        i * 1000 + 42
                    })
                    .expect("create task");
                runtime.scheduler.lock().schedule(task_id, 0);
            }

            // Use auto-advance for time progression
            let vtime_report = runtime.run_with_auto_advance();

            crate::assert_with_log!(
                vtime_report.termination == AutoAdvanceTermination::Quiescent,
                "comprehensive workload should reach quiescence",
                vtime_report.termination,
                AutoAdvanceTermination::Quiescent
            );
        });

        crate::test_complete!("conformance_comprehensive_determinism_stress");
    }

    #[test]
    #[allow(clippy::literal_string_with_formatting_args)]
    fn non_test_lab_runtime_paths_do_not_use_stray_stdout_debug_prints() {
        let source =
            std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(file!()))
                .expect("lab runtime source must be readable");

        for message in [
            "LabScheduler already scheduled {task:?}",
            "LabScheduler scheduling {task:?}",
            "Executing {:?} at step {}",
            "rng_value = {}, worker_hint = {}",
        ] {
            let stdout_call = format!("print{}!(\"{message}\"", "ln");
            assert!(
                !source.contains(&stdout_call),
                "non-test LabRuntime debug print regressed: {message}"
            );
        }
    }
}