asupersync 0.3.0

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
//! Global runtime state.
//!
//! The runtime state Σ contains all live entities:
//! - Regions (ownership tree)
//! - Tasks (units of execution)
//! - Obligations (resources to be resolved)
//! - Current time

use super::region_table::RegionCreateError;
use crate::cancel::protocol_state_machines::{
    CancelProtocolValidator, ObligationContext, ObligationEvent, RegionContext, RegionEvent,
    TaskContext, TaskEvent, TransitionResult, ValidationLevel as CancelValidationLevel,
};
use crate::cx::cx::ObservabilityState;
use crate::cx::scope::{CatchUnwind, payload_to_string};
use crate::epoch::EpochId;
use crate::error::{Error, ErrorKind};
use crate::observability::metrics::{MetricsProvider, NoOpMetrics, OutcomeKind};
use crate::observability::{LogCollector, ObservabilityConfig};
use crate::record::{
    AdmissionError, ObligationAbortReason, ObligationKind, ObligationRecord, ObligationState,
    RegionLimits, RegionRecord, SourceLocation, TaskRecord,
    finalizer::{FINALIZER_TIME_BUDGET_NANOS, Finalizer, finalizer_budget},
    region::RegionState,
    task::TaskState,
};
use crate::runtime::config::{LeakEscalation, ObligationLeakResponse};
use crate::runtime::io_driver::{IoDriver, IoDriverHandle};
use crate::runtime::reactor::Reactor;
use crate::runtime::resource_monitor::{
    DegradationLevel, DegradationStatsSnapshot, MonitorConfig, RegionPriority, ResourceMonitor,
};
use crate::runtime::stored_task::StoredTask;
use crate::runtime::task_handle::JoinError;
use crate::runtime::{BlockingPoolHandle, ObligationTable, RegionTable, TaskTable};
use crate::time::TimerDriverHandle;
use crate::trace::distributed::{LogicalClockMode, LogicalTime};
use crate::trace::event::{TraceData, TraceEventKind};
use crate::trace::{TraceBufferHandle, TraceEvent};
use crate::tracing_compat::{debug, debug_span, trace, trace_span};
use crate::types::policy::PolicyAction;
use crate::types::task_context::{CxInner, MAX_MASK_DEPTH};
use crate::types::{
    Budget, CancelAttributionConfig, CancelKind, CancelReason, ObligationId, Outcome, Policy,
    RegionId, TaskId, Time,
};
use crate::util::{Arena, ArenaIndex, EntropySource, OsEntropy};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::backtrace::Backtrace;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::Poll;
use std::time::Duration;

static NEXT_RUNTIME_INSTANCE_ID: AtomicU64 = AtomicU64::new(1);

type BoxedAsyncFinalizer = std::pin::Pin<Box<dyn Future<Output = ()> + Send>>;

fn log_cancel_protocol_violation(operation: &'static str, validation_result: &TransitionResult) {
    let _ = operation;
    let _ = validation_result;
    crate::tracing_compat::error!(
        operation,
        validation_result = ?validation_result,
        "cancel protocol violation"
    );
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FinalizerHistoryEvent {
    Registered {
        id: u64,
        region: RegionId,
        time: Time,
    },
    Ran {
        id: u64,
        time: Time,
    },
    RegionClosed {
        region: RegionId,
        time: Time,
    },
}

/// Errors that can occur when spawning a task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpawnError {
    /// The runtime backing a weak handle has already been dropped.
    RuntimeUnavailable,
    /// The target region does not exist.
    RegionNotFound(RegionId),
    /// The target region is closed or draining and cannot accept new tasks.
    RegionClosed(RegionId),
    /// Local spawn attempted without an active worker-local scheduler.
    LocalSchedulerUnavailable,
    /// Named service registration failed during spawn.
    NameRegistrationFailed {
        /// The attempted service name.
        name: String,
        /// Deterministic failure reason.
        reason: String,
    },
    /// The target region has reached its admission limit.
    RegionAtCapacity {
        /// The region that rejected the spawn.
        region: RegionId,
        /// The configured admission limit.
        limit: usize,
        /// The number of live tasks at the time of rejection.
        live: usize,
    },
}

impl std::fmt::Display for SpawnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RuntimeUnavailable => write!(f, "runtime is no longer available"),
            Self::RegionNotFound(id) => write!(f, "region not found: {id:?}"),
            Self::RegionClosed(id) => write!(f, "region closed: {id:?}"),
            Self::LocalSchedulerUnavailable => {
                write!(f, "local spawn requires an active worker scheduler")
            }
            Self::NameRegistrationFailed { name, reason } => {
                write!(f, "name registration failed: name={name} reason={reason}")
            }
            Self::RegionAtCapacity {
                region,
                limit,
                live,
            } => write!(
                f,
                "region admission limit reached: region={region:?} limit={limit} live={live}"
            ),
        }
    }
}

impl std::error::Error for SpawnError {}

#[derive(Debug, Clone, Copy)]
enum TaskCompletionKind {
    Ok,
    Err,
    Cancelled,
    Panicked,
    Unknown,
}

impl TaskCompletionKind {
    fn from_state(state: &TaskState) -> Self {
        match state {
            TaskState::Completed(Outcome::Ok(())) => Self::Ok,
            TaskState::Completed(Outcome::Err(_)) => Self::Err,
            TaskState::Completed(Outcome::Cancelled(_)) => Self::Cancelled,
            TaskState::Completed(Outcome::Panicked(_)) => Self::Panicked,
            _ => Self::Unknown,
        }
    }

    const fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Err => "err",
            Self::Cancelled => "cancelled",
            Self::Panicked => "panicked",
            Self::Unknown => "unknown",
        }
    }
}

struct MaskedFinalizer {
    inner: BoxedAsyncFinalizer,
    cx_inner: Arc<parking_lot::RwLock<CxInner>>,
    entered: bool,
}

impl MaskedFinalizer {
    fn new(inner: BoxedAsyncFinalizer, cx_inner: Arc<parking_lot::RwLock<CxInner>>) -> Self {
        Self {
            inner,
            cx_inner,
            entered: false,
        }
    }

    fn enter_mask(&mut self) {
        if self.entered {
            return;
        }
        let mut guard = self.cx_inner.write();
        debug_assert!(
            guard.mask_depth < MAX_MASK_DEPTH,
            "mask depth exceeded MAX_MASK_DEPTH ({MAX_MASK_DEPTH}): this violates INV-MASK-BOUNDED \
             and prevents cancellation from ever being observed. \
             Reduce nesting of masked sections.",
        );
        if guard.mask_depth >= MAX_MASK_DEPTH {
            crate::tracing_compat::error!(
                depth = guard.mask_depth,
                max = MAX_MASK_DEPTH,
                "INV-MASK-BOUNDED violated: mask depth saturated, cancellation may be unobservable"
            );
            return;
        }
        guard.mask_depth += 1;
        drop(guard);
        self.entered = true;
    }

    fn exit_mask(&mut self) {
        if !self.entered {
            return;
        }
        let mut guard = self.cx_inner.write();
        guard.mask_depth = guard.mask_depth.saturating_sub(1);
        drop(guard);
        self.entered = false;
    }
}

impl Future for MaskedFinalizer {
    type Output = ();

    fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<()> {
        self.enter_mask();
        let poll = self.inner.as_mut().poll(cx);
        if poll.is_ready() {
            self.exit_mask();
        }
        poll
    }
}

impl Drop for MaskedFinalizer {
    fn drop(&mut self) {
        self.exit_mask();
    }
}

impl Unpin for MaskedFinalizer {}

#[derive(Debug, Clone)]
struct LeakedObligationInfo {
    id: ObligationId,
    kind: ObligationKind,
    holder: TaskId,
    region: RegionId,
    acquired_at: SourceLocation,
    held_duration_ns: u64,
    description: Option<String>,
    /// Backtrace captured at obligation acquisition time, used for diagnostics
    /// in `mark_obligation_leaked` via `ObligationLeakInfo`.
    #[allow(dead_code)]
    // populated for diagnostic completeness; read via ObligationLeakInfo path
    acquire_backtrace: Option<Arc<Backtrace>>,
}

impl fmt::Display for LeakedObligationInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:?} {:?} holder={:?} region={:?} acquired_at={} held_ns={}",
            self.id, self.kind, self.holder, self.region, self.acquired_at, self.held_duration_ns
        )?;
        if let Some(desc) = &self.description {
            write!(f, " desc={desc}")?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
struct ObligationLeakError {
    task_id: Option<TaskId>,
    region_id: RegionId,
    completion: Option<TaskCompletionKind>,
    leaks: Vec<LeakedObligationInfo>,
}

impl fmt::Display for ObligationLeakError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let completion = self
            .completion
            .map_or("unknown", TaskCompletionKind::as_str);
        write!(
            f,
            "obligation leak: task={:?} region={:?} completion={} leaked={}",
            self.task_id,
            self.region_id,
            completion,
            self.leaks.len()
        )?;
        for leak in &self.leaks {
            write!(f, "\n  - {leak}")?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
struct CancelRegionNode {
    id: RegionId,
    parent: Option<RegionId>,
    depth: usize,
}

#[derive(Debug, Clone)]
struct RuntimeObservability {
    config: ObservabilityConfig,
    collector: LogCollector,
}

impl RuntimeObservability {
    fn new(config: ObservabilityConfig) -> Self {
        let collector = config.create_collector();
        Self { config, collector }
    }

    fn for_task(&self, region: RegionId, task: TaskId) -> ObservabilityState {
        ObservabilityState::new_with_config(
            region,
            task,
            &self.config,
            Some(self.collector.clone()),
        )
    }
}

/// The global runtime state.
///
/// This is the "Σ" from the formal semantics:
/// `Σ = ⟨R, T, O, τ_now⟩`
pub struct RuntimeState {
    /// Stable identity for this runtime state instance.
    instance_id: u64,
    /// All region records.
    pub regions: RegionTable,
    /// Task table for hot-path task state + stored futures.
    pub tasks: TaskTable,
    /// All obligation records.
    pub obligations: ObligationTable,
    /// Current logical time.
    pub now: Time,
    /// The root region.
    pub root_region: Option<RegionId>,
    /// Trace buffer for events.
    pub trace: TraceBufferHandle,
    /// Metrics provider for runtime instrumentation.
    pub metrics: Arc<dyn MetricsProvider>,
    /// I/O driver for reactor integration.
    ///
    /// When present, the runtime can wait on I/O events via the reactor.
    /// When `None`, the runtime operates in pure Lab mode without real I/O.
    io_driver: Option<IoDriverHandle>,
    /// Timer driver for sleep/timeout operations.
    ///
    /// When present, timers use the driver's timing wheel for efficient
    /// multiplexed wakeups. When `None`, timers fall back to thread-based sleeps.
    timer_driver: Option<TimerDriverHandle>,
    /// Logical clock mode used for task contexts.
    logical_clock_mode: LogicalClockMode,
    /// Cancel attribution configuration (cause-chain limits, memory caps).
    cancel_attribution: CancelAttributionConfig,
    /// Entropy source for capability-based randomness.
    entropy_source: Arc<dyn EntropySource>,
    /// Optional observability configuration for runtime contexts.
    observability: Option<RuntimeObservability>,
    /// Blocking pool handle for offloading synchronous work.
    blocking_pool: Option<BlockingPoolHandle>,
    /// Response policy when obligation leaks are detected.
    obligation_leak_response: ObligationLeakResponse,
    /// Optional escalation policy for obligation leaks.
    leak_escalation: Option<LeakEscalation>,
    /// Cumulative count of obligation leaks (for escalation threshold).
    leak_count: u64,
    /// Leak-handling recursion depth for diagnostics.
    ///
    /// Distinct leak batches may be processed reentrantly (for example when a
    /// child region closes and advances an ancestor into `Finalizing`), so we
    /// cannot use a coarse boolean guard here without suppressing legitimate
    /// nested leak handling. Track the depth for observability and pair it with
    /// `in_flight_leak_ids` to deduplicate only the exact obligations already
    /// being processed by an outer frame.
    handling_leaks: usize,
    /// Obligation ids currently being processed by `handle_obligation_leaks`.
    ///
    /// This prevents recursive `mark_obligation_leaked` /
    /// `abort_obligation` / `advance_region_state` paths from rediscovering the
    /// same leak batch and inflating `leak_count`, while still allowing
    /// different regions' leaks to be handled during the same unwind.
    in_flight_leak_ids: HashSet<ObligationId>,
    /// Regions currently in `Finalizing` state.
    ///
    /// Allows `drain_ready_async_finalizers` to skip a full region-arena scan
    /// on every poll.
    finalizing_regions: Vec<RegionId>,
    /// Recently closed region ids that have been removed from the arena.
    ///
    /// External handles such as `AppHandle` may legitimately outlive the
    /// underlying region record because `advance_region_state` removes closed
    /// regions eagerly. Keep a bounded tombstone set so those handles can still
    /// distinguish "closed and cleaned up" from "never existed in this state".
    recently_closed_regions: HashSet<RegionId>,
    recently_closed_region_order: VecDeque<RegionId>,
    /// Finalizer ids pending per region, mirroring the runtime's LIFO stack.
    pending_finalizer_ids: HashMap<RegionId, Vec<u64>>,
    /// Async finalizer tasks mapped back to the logical finalizer they are running.
    async_finalizer_tasks: HashMap<TaskId, u64>,
    /// Regions currently blocked on an in-flight async finalizer barrier.
    ///
    /// While a region is present here, lower finalizers in its stack must not
    /// run yet. This preserves the per-region async barrier: at most one async
    /// finalizer task may be active for a region at a time, and lower LIFO
    /// finalizers must wait until it completes.
    active_async_finalizers: HashMap<RegionId, TaskId>,
    /// Append-only finalizer lifecycle history for post-run oracle hydration.
    finalizer_history: Vec<FinalizerHistoryEvent>,
    /// Monotonic id source for finalizer registrations.
    next_finalizer_id: u64,
    /// Per-module epoch cursors feeding the runtime epoch tracker.
    region_table_epoch: EpochId,
    task_table_epoch: EpochId,
    obligation_table_epoch: EpochId,
    /// Epoch consistency tracker for runtime state transitions.
    epoch_tracker: super::epoch_tracker::EpochConsistencyTracker,
    /// State machine transition verifier for runtime entities.
    state_verifier: Arc<super::state_verifier::StateTransitionVerifier>,
    /// Cancel protocol state machine validator for runtime cancellation compliance.
    cancel_protocol_validator: Arc<parking_lot::Mutex<CancelProtocolValidator>>,
    /// Cancellation debt accumulation monitor.
    debt_monitor: Arc<crate::observability::CancellationDebtMonitor>,
    /// Resource monitor for graceful degradation.
    ///
    /// Tracks memory, file descriptors, CPU load, and network connections,
    /// and triggers degradation policies when thresholds are exceeded.
    resource_monitor: Arc<ResourceMonitor>,
}

impl std::fmt::Debug for RuntimeState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RuntimeState")
            .field("regions", &self.regions)
            .field("tasks", &self.tasks)
            .field("obligations", &self.obligations)
            .field("now", &self.now)
            .field("instance_id", &self.instance_id)
            .field("root_region", &self.root_region)
            .field("trace", &self.trace)
            .field("metrics", &"<dyn MetricsProvider>")
            .field("io_driver", &self.io_driver)
            .field("timer_driver", &self.timer_driver)
            .field("logical_clock_mode", &self.logical_clock_mode)
            .field("cancel_attribution", &self.cancel_attribution)
            .field("entropy_source", &"<dyn EntropySource>")
            .field("observability", &self.observability.is_some())
            .field("blocking_pool", &self.blocking_pool.is_some())
            .field("obligation_leak_response", &self.obligation_leak_response)
            .field("leak_escalation", &self.leak_escalation)
            .field("leak_count", &self.leak_count)
            .field("handling_leaks", &self.handling_leaks)
            .field("in_flight_leak_ids", &self.in_flight_leak_ids.len())
            .field("finalizing_region_count", &self.finalizing_regions.len())
            .field(
                "recently_closed_region_count",
                &self.recently_closed_regions.len(),
            )
            .field(
                "recently_closed_region_order_count",
                &self.recently_closed_region_order.len(),
            )
            .field(
                "pending_finalizer_regions",
                &self.pending_finalizer_ids.len(),
            )
            .field("async_finalizer_tasks", &self.async_finalizer_tasks.len())
            .field(
                "active_async_finalizers",
                &self.active_async_finalizers.len(),
            )
            .field("finalizer_history_len", &self.finalizer_history.len())
            .field("next_finalizer_id", &self.next_finalizer_id)
            .field("region_table_epoch", &self.region_table_epoch)
            .field("task_table_epoch", &self.task_table_epoch)
            .field("obligation_table_epoch", &self.obligation_table_epoch)
            .field("state_verifier", &"<StateTransitionVerifier>")
            .field("cancel_protocol_validator", &"<CancelProtocolValidator>")
            .field("debt_monitor", &"<CancellationDebtMonitor>")
            .finish()
    }
}

impl RuntimeState {
    const RECENTLY_CLOSED_REGION_CAPACITY: usize = 4096;

    /// Creates a new empty runtime state without a reactor.
    ///
    /// This is equivalent to [`without_reactor()`](Self::without_reactor) and creates
    /// a runtime suitable for Lab mode or pure computation without I/O.
    #[must_use]
    pub fn new() -> Self {
        Self::new_with_metrics(Arc::new(NoOpMetrics))
    }

    /// Creates a new runtime state with an explicit metrics provider.
    #[must_use]
    pub fn new_with_metrics(metrics: Arc<dyn MetricsProvider>) -> Self {
        Self {
            instance_id: NEXT_RUNTIME_INSTANCE_ID.fetch_add(1, Ordering::Relaxed),
            regions: RegionTable::new(),
            tasks: TaskTable::new(),
            obligations: ObligationTable::new(),
            now: Time::ZERO,
            root_region: None,
            trace: TraceBufferHandle::new(4096),
            metrics,
            io_driver: None,
            timer_driver: None,
            logical_clock_mode: LogicalClockMode::Lamport,
            cancel_attribution: CancelAttributionConfig::default(),
            entropy_source: Arc::new(OsEntropy),
            observability: None,
            blocking_pool: None,
            obligation_leak_response: ObligationLeakResponse::Log,
            leak_escalation: None,
            leak_count: 0,
            handling_leaks: 0,
            in_flight_leak_ids: HashSet::new(),
            finalizing_regions: Vec::new(),
            recently_closed_regions: HashSet::new(),
            recently_closed_region_order: VecDeque::new(),
            pending_finalizer_ids: HashMap::new(),
            async_finalizer_tasks: HashMap::new(),
            active_async_finalizers: HashMap::new(),
            finalizer_history: Vec::new(),
            next_finalizer_id: 0,
            region_table_epoch: EpochId::GENESIS,
            task_table_epoch: EpochId::GENESIS,
            obligation_table_epoch: EpochId::GENESIS,
            epoch_tracker: super::epoch_tracker::EpochConsistencyTracker::new(),
            state_verifier: Arc::new(super::state_verifier::StateTransitionVerifier::new(
                super::state_verifier::StateVerifierConfig::default(),
            )),
            cancel_protocol_validator: Arc::new(parking_lot::Mutex::new(
                CancelProtocolValidator::new(CancelValidationLevel::Basic),
            )),
            debt_monitor: Arc::new(crate::observability::CancellationDebtMonitor::default()),
            resource_monitor: Arc::new(ResourceMonitor::new(MonitorConfig::default())),
        }
    }

    /// Creates a runtime state with a real reactor and metrics provider.
    ///
    /// The provided reactor will be wrapped in an [`IoDriver`] to handle
    /// waker dispatch. Use this constructor when you need real I/O support
    /// and want to preserve the runtime's metrics configuration.
    ///
    /// # Arguments
    ///
    /// * `reactor` - The platform-specific reactor (e.g., `EpollReactor` on Linux)
    /// * `metrics` - Metrics provider to attach to the runtime state
    ///
    /// # Example
    ///
    /// ```ignore
    /// use asupersync::runtime::{RuntimeState, EpollReactor};
    /// use std::sync::Arc;
    ///
    /// let reactor = Arc::new(EpollReactor::new()?);
    /// let state = RuntimeState::with_reactor_and_metrics(reactor, Arc::new(NoOpMetrics));
    /// ```
    #[must_use]
    pub fn with_reactor_and_metrics(
        reactor: Arc<dyn Reactor>,
        metrics: Arc<dyn MetricsProvider>,
    ) -> Self {
        let mut state = Self::new_with_metrics(metrics);
        state.io_driver = Some(IoDriverHandle::new(reactor));
        state.timer_driver = Some(TimerDriverHandle::with_wall_clock());
        state.logical_clock_mode = LogicalClockMode::Hybrid;
        state
    }

    /// Creates a runtime state with a real reactor for production use.
    ///
    /// This uses a [`NoOpMetrics`] provider by default. Prefer
    /// [`with_reactor_and_metrics`](Self::with_reactor_and_metrics) if you
    /// need custom metrics.
    #[must_use]
    pub fn with_reactor(reactor: Arc<dyn Reactor>) -> Self {
        Self::with_reactor_and_metrics(reactor, Arc::new(NoOpMetrics))
    }

    /// Creates a runtime state without a reactor (Lab mode).
    ///
    /// Use this for deterministic testing or pure computation without I/O.
    /// This is equivalent to [`new()`](Self::new).
    #[must_use]
    pub fn without_reactor() -> Self {
        Self::new()
    }

    /// Returns a reference to the I/O driver handle, if present.
    ///
    /// Returns `None` if the runtime was created without a reactor.
    #[inline]
    #[must_use]
    pub fn io_driver(&self) -> Option<&IoDriverHandle> {
        self.io_driver.as_ref()
    }

    /// Returns a locked guard to the I/O driver, if present.
    ///
    /// Returns `None` if the runtime was created without a reactor.
    pub fn io_driver_mut(&self) -> Option<parking_lot::MutexGuard<'_, IoDriver>> {
        self.io_driver.as_ref().map(IoDriverHandle::lock)
    }

    /// Returns a cloned handle to the I/O driver, if present.
    ///
    /// Returns `None` if the runtime was created without a reactor.
    #[inline]
    #[must_use]
    pub fn io_driver_handle(&self) -> Option<IoDriverHandle> {
        self.io_driver.clone()
    }

    /// Sets the I/O driver for this runtime.
    pub fn set_io_driver(&mut self, driver: IoDriverHandle) {
        self.io_driver = Some(driver);
    }

    /// Returns a reference to the timer driver handle, if present.
    ///
    /// Returns `None` if the runtime was created without a timer driver.
    #[inline]
    #[must_use]
    pub fn timer_driver(&self) -> Option<&TimerDriverHandle> {
        self.timer_driver.as_ref()
    }

    /// Returns a cloned handle to the timer driver, if present.
    ///
    /// Returns `None` if the runtime was created without a timer driver.
    #[inline]
    #[must_use]
    pub fn timer_driver_handle(&self) -> Option<TimerDriverHandle> {
        self.timer_driver.clone()
    }

    #[inline]
    fn current_runtime_time(&self) -> Time {
        self.timer_driver
            .as_ref()
            .map_or(self.now, TimerDriverHandle::now)
    }

    /// Returns a cloned handle to the blocking pool, if present.
    #[inline]
    #[must_use]
    pub fn blocking_pool_handle(&self) -> Option<BlockingPoolHandle> {
        self.blocking_pool.clone()
    }

    /// Gets a reference to the state transition verifier.
    #[inline]
    #[must_use]
    pub fn state_verifier(&self) -> &Arc<super::state_verifier::StateTransitionVerifier> {
        &self.state_verifier
    }

    /// Gets the state verifier statistics snapshot.
    #[must_use]
    pub fn state_verifier_stats(&self) -> super::state_verifier::StateVerifierStatsSnapshot {
        self.state_verifier.stats()
    }

    /// Gets a reference to the cancel protocol validator.
    #[inline]
    #[must_use]
    pub fn cancel_protocol_validator(&self) -> &Arc<parking_lot::Mutex<CancelProtocolValidator>> {
        &self.cancel_protocol_validator
    }

    /// Validates a region state transition using the cancel protocol validator.
    fn validate_region_protocol_transition(
        &self,
        region_id: RegionId,
        event: RegionEvent,
        context: &RegionContext,
    ) -> TransitionResult {
        let mut validator = self.cancel_protocol_validator.lock();
        validator.validate_region_transition(region_id, event, context)
    }

    /// Validates a task state transition using the cancel protocol validator.
    fn validate_task_protocol_transition(
        &self,
        task_id: TaskId,
        event: TaskEvent,
        context: &TaskContext,
    ) -> TransitionResult {
        let mut validator = self.cancel_protocol_validator.lock();
        validator.validate_task_transition(task_id, event, context)
    }

    /// Validates an obligation state transition using the cancel protocol validator.
    fn validate_obligation_protocol_transition(
        &self,
        obligation_id: ObligationId,
        event: ObligationEvent,
        context: &ObligationContext,
    ) -> TransitionResult {
        let mut validator = self.cancel_protocol_validator.lock();
        validator.validate_obligation_transition(obligation_id, event, context)
    }

    /// Sets the blocking pool handle for this runtime.
    pub fn set_blocking_pool(&mut self, handle: BlockingPoolHandle) {
        self.blocking_pool = Some(handle);
    }

    /// Sets the timer driver for this runtime.
    pub fn set_timer_driver(&mut self, driver: TimerDriverHandle) {
        self.timer_driver = Some(driver);
    }

    /// Returns the logical clock mode for new task contexts.
    #[must_use]
    pub fn logical_clock_mode(&self) -> &LogicalClockMode {
        &self.logical_clock_mode
    }

    /// Sets the logical clock mode for new task contexts.
    pub fn set_logical_clock_mode(&mut self, mode: LogicalClockMode) {
        self.logical_clock_mode = mode;
    }

    /// Returns the cancel attribution configuration for this runtime.
    #[must_use]
    pub fn cancel_attribution_config(&self) -> CancelAttributionConfig {
        self.cancel_attribution
    }

    /// Sets the cancel attribution configuration for this runtime.
    pub fn set_cancel_attribution_config(&mut self, config: CancelAttributionConfig) {
        self.cancel_attribution = config;
    }

    /// Returns the entropy source for this runtime.
    #[inline]
    #[must_use]
    pub fn entropy_source(&self) -> Arc<dyn EntropySource> {
        self.entropy_source.clone()
    }

    /// Sets the entropy source for this runtime.
    pub fn set_entropy_source(&mut self, source: Arc<dyn EntropySource>) {
        self.entropy_source = source;
    }

    /// Configures runtime observability for new tasks.
    pub fn set_observability_config(&mut self, config: ObservabilityConfig) {
        self.observability = Some(RuntimeObservability::new(config));
    }

    /// Clears runtime observability configuration.
    pub fn clear_observability_config(&mut self) {
        self.observability = None;
    }

    /// Builds the observability state for a new task-like execution context.
    #[must_use]
    pub(crate) fn observability_for_task(
        &self,
        region: RegionId,
        task: TaskId,
    ) -> Option<ObservabilityState> {
        self.observability
            .as_ref()
            .map(|obs| obs.for_task(region, task))
    }

    /// Sets the response policy when obligation leaks are detected.
    pub fn set_obligation_leak_response(&mut self, response: ObligationLeakResponse) {
        self.obligation_leak_response = response;
    }

    /// Sets the escalation policy for obligation leaks.
    pub fn set_leak_escalation(&mut self, escalation: Option<LeakEscalation>) {
        self.leak_escalation = escalation;
    }

    /// Returns the cumulative count of obligation leaks.
    #[must_use]
    pub fn leak_count(&self) -> u64 {
        self.leak_count
    }

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

    /// Returns the stable identity of this runtime state instance.
    #[inline]
    #[must_use]
    pub fn instance_id(&self) -> u64 {
        self.instance_id
    }

    /// Returns the metrics provider for this runtime.
    #[inline]
    #[must_use]
    pub fn metrics_provider(&self) -> Arc<dyn MetricsProvider> {
        self.metrics.clone()
    }

    /// Sets the metrics provider for this runtime.
    pub fn set_metrics_provider(&mut self, provider: Arc<dyn MetricsProvider>) {
        self.metrics = provider;
    }

    /// Returns the cancellation debt monitor for this runtime.
    #[inline]
    #[must_use]
    pub fn debt_monitor(&self) -> Arc<crate::observability::CancellationDebtMonitor> {
        self.debt_monitor.clone()
    }

    /// Returns a shared reference to a task record by ID.
    #[inline]
    #[must_use]
    pub fn task(&self, task_id: TaskId) -> Option<&TaskRecord> {
        self.tasks.task(task_id)
    }

    /// Returns a mutable reference to a task record by ID.
    #[inline]
    pub fn task_mut(&mut self, task_id: TaskId) -> Option<&mut TaskRecord> {
        self.tasks.task_mut(task_id)
    }

    /// Inserts a new task record into the arena.
    ///
    /// Returns the assigned arena index.
    #[inline]
    pub fn insert_task(&mut self, record: TaskRecord) -> ArenaIndex {
        self.tasks.insert_task(record)
    }

    /// Inserts a new task record produced by `f` into the arena.
    ///
    /// The closure receives the assigned `ArenaIndex`.
    #[inline]
    pub fn insert_task_with<F>(&mut self, f: F) -> ArenaIndex
    where
        F: FnOnce(ArenaIndex) -> TaskRecord,
    {
        self.tasks.insert_task_with(f)
    }

    /// Removes a task record from the arena.
    ///
    /// Returns the removed record if it existed.
    #[inline]
    pub fn remove_task(&mut self, task_id: TaskId) -> Option<TaskRecord> {
        let removed = self.tasks.remove_task(task_id);
        if removed.is_some() {
            self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::TaskTable);
        }
        removed
    }

    /// Returns an iterator over all task records.
    pub fn tasks_iter(&self) -> impl Iterator<Item = (ArenaIndex, &TaskRecord)> {
        self.tasks.tasks_arena().iter()
    }

    /// Returns `true` if the task arena is empty.
    #[must_use]
    pub fn tasks_is_empty(&self) -> bool {
        self.tasks.tasks_arena().is_empty()
    }

    /// Provides direct access to the tasks arena.
    ///
    /// Used by intrusive data structures (LocalQueue) that operate on the arena.
    #[inline]
    #[must_use]
    pub fn tasks_arena(&self) -> &Arena<TaskRecord> {
        self.tasks.tasks_arena()
    }

    /// Provides mutable access to the tasks arena.
    ///
    /// Used by intrusive data structures (LocalQueue) that operate on the arena.
    #[inline]
    pub fn tasks_arena_mut(&mut self) -> &mut Arena<TaskRecord> {
        self.tasks.tasks_arena_mut()
    }

    /// Returns a shared reference to a region record by ID.
    #[inline]
    #[must_use]
    pub fn region(&self, region_id: RegionId) -> Option<&RegionRecord> {
        self.regions.get(region_id.arena_index())
    }

    /// Returns `true` if the region has already completed close and been
    /// removed from the live region table.
    #[inline]
    #[must_use]
    pub fn region_was_closed(&self, region_id: RegionId) -> bool {
        self.recently_closed_regions.contains(&region_id)
    }

    /// Returns a mutable reference to a region record by ID.
    #[inline]
    pub fn region_mut(&mut self, region_id: RegionId) -> Option<&mut RegionRecord> {
        self.regions.get_mut(region_id.arena_index())
    }

    /// Returns an iterator over all region records.
    pub fn regions_iter(&self) -> impl Iterator<Item = (ArenaIndex, &RegionRecord)> {
        self.regions.iter()
    }

    /// Returns the number of regions in the table.
    #[must_use]
    pub fn regions_len(&self) -> usize {
        self.regions.len()
    }

    /// Returns `true` if there are no regions.
    #[must_use]
    pub fn regions_is_empty(&self) -> bool {
        self.regions.is_empty()
    }

    /// Returns a shared reference to an obligation record by ID.
    #[must_use]
    pub fn obligation(&self, obligation_id: ObligationId) -> Option<&ObligationRecord> {
        self.obligations.get(obligation_id.arena_index())
    }

    /// Returns a mutable reference to an obligation record by ID.
    #[inline]
    pub fn obligation_mut(&mut self, obligation_id: ObligationId) -> Option<&mut ObligationRecord> {
        self.obligations.get_mut(obligation_id.arena_index())
    }

    /// Returns an iterator over all obligation records.
    pub fn obligations_iter(&self) -> impl Iterator<Item = (ArenaIndex, &ObligationRecord)> {
        self.obligations.iter()
    }

    /// Returns the number of obligations in the table.
    #[must_use]
    pub fn obligations_len(&self) -> usize {
        self.obligations.len()
    }

    /// Returns `true` if there are no obligations.
    #[must_use]
    pub fn obligations_is_empty(&self) -> bool {
        self.obligations.is_empty()
    }

    /// Returns `true` if this runtime has an I/O driver.
    #[inline]
    #[must_use]
    pub fn has_io_driver(&self) -> bool {
        self.io_driver.is_some()
    }

    /// Takes a point-in-time snapshot of the runtime state for debugging or visualization.
    ///
    /// The snapshot captures a consistent view of regions, tasks, obligations, and
    /// recent trace events. It is designed to be lightweight and serializable.
    #[must_use]
    pub fn snapshot(&self) -> RuntimeSnapshot {
        let now = self.current_runtime_time();
        let mut obligations_by_task: HashMap<TaskId, Vec<ObligationId>> =
            HashMap::with_capacity(self.obligations_len());
        let obligations: Vec<ObligationSnapshot> = self
            .obligations_iter()
            .map(|(_, record)| {
                obligations_by_task
                    .entry(record.holder)
                    .or_default()
                    .push(record.id);
                ObligationSnapshot::from_record(record)
            })
            .collect();

        let regions: Vec<RegionSnapshot> = self
            .regions_iter()
            .map(|(_, record)| RegionSnapshot::from_record(record))
            .collect();

        let tasks: Vec<TaskSnapshot> = self
            .tasks_iter()
            .map(|(_, record)| {
                let task_obligations = obligations_by_task
                    .get(&record.id)
                    .cloned()
                    .unwrap_or_default();
                TaskSnapshot::from_record(record, task_obligations)
            })
            .collect();

        let recent_events: Vec<EventSnapshot> = self
            .trace
            .snapshot()
            .iter()
            .map(EventSnapshot::from_event)
            .collect();

        RuntimeSnapshot {
            timestamp: now.as_nanos(),
            regions,
            tasks,
            obligations,
            recent_events,
        }
    }

    /// Creates a root region and returns its ID.
    ///
    /// # Panics
    ///
    /// Panics in debug builds if a root region already exists (double-init guard).
    pub fn create_root_region(&mut self, budget: Budget) -> RegionId {
        debug_assert!(
            self.root_region.is_none(),
            "create_root_region called twice; previous root: {:?}",
            self.root_region
        );
        let now = self.current_runtime_time();
        let id = self.regions.create_root(budget, now);

        // Register region with cancel protocol validator
        {
            let mut validator = self.cancel_protocol_validator.lock();
            validator.register_region(id);
        }

        self.root_region = Some(id);
        self.record_trace_event(|seq| TraceEvent::region_created(seq, now, id, None));
        self.metrics.region_created(id, None);

        // Notify epoch tracker of region creation
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::RegionTable);

        id
    }

    /// Creates a child region under the given parent and returns its ID.
    ///
    /// The child's effective budget is the meet (tightest constraints) of the
    /// parent budget and the provided budget.
    ///
    /// This method includes graceful degradation checks - if resource pressure
    /// is high, the region creation may be rejected to preserve system stability.
    pub fn create_child_region(
        &mut self,
        parent: RegionId,
        budget: Budget,
    ) -> Result<RegionId, RegionCreateError> {
        // Check resource pressure before creating the region
        // Use Normal priority as the default for backward compatibility
        self.check_resource_pressure_for_region(RegionPriority::Normal)?;

        let now = self.current_runtime_time();
        let id = self.regions.create_child(parent, budget, now)?;

        self.record_trace_event(|seq| TraceEvent::region_created(seq, now, id, Some(parent)));
        self.metrics.region_created(id, Some(parent));

        // Notify epoch tracker of region creation
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::RegionTable);

        Ok(id)
    }

    /// Updates admission limits for a region.
    ///
    /// Returns `false` if the region does not exist.
    pub fn set_region_limits(&mut self, region: RegionId, limits: RegionLimits) -> bool {
        self.regions.set_limits(region, limits)
    }

    /// Returns the current admission limits for a region.
    #[must_use]
    pub fn region_limits(&self, region: RegionId) -> Option<RegionLimits> {
        self.regions.limits(region)
    }

    /// Creates the infrastructure for a task (record, context, channel) without storing the future.
    ///
    /// This helper allows `create_task` and `spawn_local` to share the same setup logic
    /// while storing the future in different places (global vs thread-local).
    #[allow(clippy::type_complexity)]
    pub(crate) fn create_task_infrastructure<T>(
        &mut self,
        region: RegionId,
        budget: Budget,
        cleanup_task: bool,
    ) -> Result<
        (
            TaskId,
            crate::runtime::TaskHandle<T>,
            crate::cx::Cx,
            crate::channel::oneshot::Sender<Result<T, crate::runtime::task_handle::JoinError>>,
        ),
        SpawnError,
    >
    where
        T: Send + 'static,
    {
        use crate::channel::oneshot;

        // Create oneshot channel for the result
        let (result_tx, result_rx) =
            oneshot::channel::<Result<T, crate::runtime::task_handle::JoinError>>();

        // Create the TaskRecord
        let now = self.current_runtime_time();
        let idx = self.tasks.insert_task_with(|idx| {
            TaskRecord::new_with_time(TaskId::from_arena(idx), region, budget, now)
        });
        let task_id = TaskId::from_arena(idx);

        // Register task with cancel protocol validator
        {
            let mut validator = self.cancel_protocol_validator.lock();
            validator.register_task(task_id, region);
        }

        // Validate task creation protocol transition
        let context = TaskContext {
            task_id,
            region_id: region,
            spawned_at: now,
            validation_level: CancelValidationLevel::Basic,
        };
        let validation_result = self.validate_task_protocol_transition(
            task_id,
            TaskEvent::Start, // Use Start event for task creation
            &context,
        );
        if matches!(
            validation_result,
            TransitionResult::Invalid { .. } | TransitionResult::InvariantViolation { .. }
        ) {
            log_cancel_protocol_violation("task creation", &validation_result);
            // Continue with creation but log violation
        }

        // Add task to the region's task list
        if let Some(region_record) = self.regions.get(region.arena_index()) {
            let admission = if cleanup_task {
                region_record.add_cleanup_task(task_id)
            } else {
                region_record.add_task(task_id)
            };
            if let Err(err) = admission {
                // Rollback task creation
                let _ = self.remove_task(task_id);
                return Err(match err {
                    AdmissionError::Closed => SpawnError::RegionClosed(region),
                    AdmissionError::LimitReached { limit, live, .. } => {
                        SpawnError::RegionAtCapacity {
                            region,
                            limit,
                            live,
                        }
                    }
                });
            }
        } else {
            // Rollback task creation
            let _ = self.remove_task(task_id);
            return Err(SpawnError::RegionNotFound(region));
        }

        // Create the task's capability context
        let entropy = self.entropy_source.fork(task_id);
        let observability = self
            .observability
            .as_ref()
            .map(|obs| obs.for_task(region, task_id));
        let logical_clock = self
            .logical_clock_mode
            .build_handle(self.timer_driver_handle());
        let cx = crate::cx::Cx::new_with_drivers(
            region,
            task_id,
            budget,
            observability,
            self.io_driver_handle(),
            None,
            self.timer_driver_handle(),
            Some(entropy),
        )
        .with_blocking_pool_handle(self.blocking_pool_handle())
        .with_logical_clock(logical_clock);
        cx.set_trace_buffer(self.trace_handle());
        let cx_weak = std::sync::Arc::downgrade(&cx.inner);

        // Link the shared state to the TaskRecord
        if let Some(record) = self.task_mut(task_id) {
            record.set_cx_inner(cx.inner.clone());
            record.set_cx(cx.clone());
        }

        self.record_task_spawn(task_id, region);

        // Trace task creation
        debug!(
            task_id = ?task_id,
            region_id = ?region,
            initial_state = "Created",
            poll_quota = budget.poll_quota,
            "task created via RuntimeState"
        );

        // Create the TaskHandle
        let handle = crate::runtime::TaskHandle::new(task_id, result_rx, cx_weak);

        Ok((task_id, handle, cx, result_tx))
    }

    /// Creates a task and stores its future for polling.
    ///
    /// This is the core spawn primitive. It:
    /// 1. Creates a TaskRecord in the specified region
    /// 2. Wraps the future to send its result through a oneshot channel
    /// 3. Stores the wrapped future for the executor to poll
    /// 4. Returns a TaskHandle for awaiting the result
    ///
    /// # Arguments
    /// * `region` - The region that will own this task
    /// * `budget` - The budget for this task
    /// * `future` - The future to execute
    ///
    /// # Returns
    /// A Result containing `(TaskId, TaskHandle)` on success, or `SpawnError` on failure.
    ///
    /// # Example
    /// ```ignore
    /// let (task_id, handle) = state.create_task(region, budget, async { 42 })?;
    /// // Later: scheduler.schedule(task_id);
    /// // Even later: let result = handle.join(cx)?;
    /// ```
    pub fn create_task<F, T>(
        &mut self,
        region: RegionId,
        budget: Budget,
        future: F,
    ) -> Result<(TaskId, crate::runtime::TaskHandle<T>), SpawnError>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        use crate::runtime::task_handle::JoinError;

        let (task_id, handle, cx, result_tx) =
            self.create_task_infrastructure(region, budget, false)?;

        // Wrap the future to send the result through the channel. Panics must
        // surface as `JoinError::Panicked` rather than silently closing the
        // channel and looking like cancellation to the join handle.
        let wrapped_future = async move {
            match (CatchUnwind { inner: future }).await {
                Ok(result) => {
                    let _ = result_tx.send(&cx, Ok::<_, JoinError>(result));
                    crate::types::Outcome::Ok(())
                }
                Err(payload) => {
                    let panic_payload =
                        crate::types::outcome::PanicPayload::new(payload_to_string(&payload));
                    let _ = result_tx.send(
                        &cx,
                        Err::<T, JoinError>(JoinError::Panicked(panic_payload.clone())),
                    );
                    crate::types::Outcome::Panicked(panic_payload)
                }
            }
        };

        // Store the wrapped future with task_id for poll tracing
        self.tasks
            .store_spawned_task(task_id, StoredTask::new_with_id(wrapped_future, task_id));

        // Notify epoch tracker of task creation
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::TaskTable);

        Ok((task_id, handle))
    }

    fn logical_time_for_task(&self, task_id: TaskId) -> Option<LogicalTime> {
        let record = self.task(task_id)?;
        let cx = record.cx.as_ref()?;
        Some(cx.logical_tick())
    }

    pub(crate) fn record_trace_event<F>(&self, build: F)
    where
        F: FnOnce(u64) -> TraceEvent,
    {
        self.trace.record_event(build);
    }

    pub(crate) fn notify_runtime_epoch_advance(&mut self, module: super::epoch_tracker::ModuleId) {
        let now = self.current_runtime_time();
        let cursor = match module {
            super::epoch_tracker::ModuleId::RegionTable => &mut self.region_table_epoch,
            super::epoch_tracker::ModuleId::TaskTable => &mut self.task_table_epoch,
            super::epoch_tracker::ModuleId::ObligationTable => &mut self.obligation_table_epoch,
            _ => return,
        };
        let from_epoch = *cursor;
        let to_epoch = from_epoch.next();
        *cursor = to_epoch;
        self.epoch_tracker
            .notify_epoch_transition(module, from_epoch, to_epoch, now);
    }

    fn record_task_trace_event<F>(&self, task_id: TaskId, build: F)
    where
        F: FnOnce(u64) -> TraceEvent,
    {
        let logical_time = self.logical_time_for_task(task_id);
        self.trace.record_event(move |seq| {
            let event = build(seq);
            if let Some(logical_time) = logical_time {
                event.with_logical_time(logical_time)
            } else {
                event
            }
        });
    }

    pub(crate) fn record_task_spawn(&self, task_id: TaskId, region: RegionId) {
        let now = self.current_runtime_time();
        self.record_task_trace_event(task_id, |seq| TraceEvent::spawn(seq, now, task_id, region));
        self.metrics.task_spawned(region, task_id);
    }

    fn record_task_complete(&self, task: &TaskRecord) {
        let now = self.current_runtime_time();
        self.record_task_trace_event(task.id, |seq| {
            TraceEvent::complete(seq, now, task.id, task.owner)
        });

        let duration = Duration::from_nanos(now.duration_since(task.created_at()));
        let outcome_kind = match &task.state {
            TaskState::Completed(outcome) => OutcomeKind::from(outcome),
            _ => OutcomeKind::Err,
        };
        self.metrics.task_completed(task.id, outcome_kind, duration);
    }

    fn capture_obligation_backtrace() -> Option<Arc<Backtrace>> {
        if cfg!(debug_assertions) {
            Some(Arc::new(Backtrace::capture()))
        } else {
            None
        }
    }

    fn collect_obligation_leaks<F>(&self, mut predicate: F) -> Vec<LeakedObligationInfo>
    where
        F: FnMut(&ObligationRecord) -> bool,
    {
        let now = self.current_runtime_time();
        self.obligations
            .iter()
            .filter_map(|(_, record)| {
                if !record.is_pending() || !predicate(record) {
                    return None;
                }

                let held_duration_ns = now.duration_since(record.reserved_at);
                Some(LeakedObligationInfo {
                    id: record.id,
                    kind: record.kind,
                    holder: record.holder,
                    region: record.region,
                    acquired_at: record.acquired_at,
                    held_duration_ns,
                    description: record.description.clone(),
                    acquire_backtrace: record.acquire_backtrace.clone(),
                })
            })
            .collect()
    }

    /// Collect obligation leaks for a specific task holder using the secondary index.
    fn collect_obligation_leaks_for_holder(&self, task_id: TaskId) -> Vec<LeakedObligationInfo> {
        let now = self.current_runtime_time();
        self.obligations
            .ids_for_holder(task_id)
            .iter()
            .filter_map(|id| {
                let record = self.obligations.get(id.arena_index())?;
                if !record.is_pending() {
                    return None;
                }
                let held_duration_ns = now.duration_since(record.reserved_at);
                Some(LeakedObligationInfo {
                    id: record.id,
                    kind: record.kind,
                    holder: record.holder,
                    region: record.region,
                    acquired_at: record.acquired_at,
                    held_duration_ns,
                    description: record.description.clone(),
                    acquire_backtrace: record.acquire_backtrace.clone(),
                })
            })
            .collect()
    }

    #[allow(clippy::needless_pass_by_value)]
    fn handle_obligation_leaks(&mut self, error: ObligationLeakError) {
        if error.leaks.is_empty() {
            return;
        }

        let new_leaks: Vec<LeakedObligationInfo> = error
            .leaks
            .iter()
            .filter(|leak| {
                self.obligations
                    .get(leak.id.arena_index())
                    .is_some_and(ObligationRecord::is_pending)
                    && !self.in_flight_leak_ids.contains(&leak.id)
            })
            .cloned()
            .collect();

        if new_leaks.is_empty() {
            return;
        }

        let leak_ids: Vec<ObligationId> = new_leaks.iter().map(|leak| leak.id).collect();
        self.in_flight_leak_ids.extend(leak_ids.iter().copied());
        self.handling_leaks = self.handling_leaks.saturating_add(1);

        // Track cumulative leaks for escalation.
        self.leak_count = self.leak_count.saturating_add(leak_ids.len() as u64);

        // Determine the effective response: check escalation threshold first.
        let mut response = if let Some(ref esc) = self.leak_escalation {
            if self.leak_count >= esc.threshold {
                esc.escalate_to
            } else {
                self.obligation_leak_response
            }
        } else {
            self.obligation_leak_response
        };

        // PREVENT DOUBLE PANIC: If we are already panicking, we must not panic again.
        if matches!(response, ObligationLeakResponse::Panic) && std::thread::panicking() {
            crate::tracing_compat::error!(
                task_id = ?error.task_id,
                "obligation leaks detected during panic; downgrading Panic policy to Log to prevent double-panic abort"
            );
            response = ObligationLeakResponse::Log;
        }

        match response {
            ObligationLeakResponse::Panic => {
                // Mark leaked first so trace/metrics capture the event before panicking.
                for &id in &leak_ids {
                    let _ = self.mark_obligation_leaked(id);
                }
                let msg = error.to_string();
                // This is a runtime invariant violation. We fail-fast to surface the bug, but we
                // avoid the `panic!` macro so UBS doesn't treat this as a library panic surface.
                crate::tracing_compat::error!(
                    task_id = ?error.task_id,
                    region_id = ?error.region_id,
                    completion = %error
                        .completion
                        .map_or("unknown", TaskCompletionKind::as_str),
                    leak_count = leak_ids.len(),
                    cumulative_leaks = self.leak_count,
                    details = %error,
                    "obligation leaks detected (fail-fast)"
                );
                self.handling_leaks = self.handling_leaks.saturating_sub(1);
                for id in leak_ids {
                    self.in_flight_leak_ids.remove(&id);
                }
                std::panic::panic_any(msg);
            }
            ObligationLeakResponse::Log => {
                for &id in &leak_ids {
                    let _ = self.mark_obligation_leaked(id);
                }
                crate::tracing_compat::error!(
                    task_id = ?error.task_id,
                    region_id = ?error.region_id,
                    completion = %error
                        .completion
                        .map_or("unknown", TaskCompletionKind::as_str),
                    leak_count = leak_ids.len(),
                    cumulative_leaks = self.leak_count,
                    details = %error,
                    "obligation leaks detected"
                );
            }
            ObligationLeakResponse::Silent => {
                for &id in &leak_ids {
                    let _ = self.mark_obligation_leaked(id);
                }
            }
            ObligationLeakResponse::Recover => {
                for &id in &leak_ids {
                    // Abort instead of marking leaked — performs resource cleanup.
                    let _ = self.abort_obligation(id, ObligationAbortReason::Error);
                }
                crate::tracing_compat::warn!(
                    task_id = ?error.task_id,
                    region_id = ?error.region_id,
                    completion = %error
                        .completion
                        .map_or("unknown", TaskCompletionKind::as_str),
                    leak_count = leak_ids.len(),
                    cumulative_leaks = self.leak_count,
                    details = %error,
                    "obligation leaks recovered via auto-abort"
                );
            }
        }

        self.handling_leaks = self.handling_leaks.saturating_sub(1);
        for id in leak_ids {
            self.in_flight_leak_ids.remove(&id);
        }
    }

    /// Creates and registers an obligation for the given task and region.
    ///
    /// This records the obligation in the registry and emits a trace event.
    /// Returns an error if the region is closed or admission limits are reached.
    #[allow(clippy::result_large_err)]
    #[track_caller]
    pub fn create_obligation(
        &mut self,
        kind: ObligationKind,
        holder: TaskId,
        region: RegionId,
        description: Option<String>,
    ) -> Result<ObligationId, Error> {
        {
            let Some(region_record) = self.regions.get(region.arena_index()) else {
                return Err(Error::new(ErrorKind::RegionClosed).with_message("region not found"));
            };

            let Some(task_record) = self.task(holder) else {
                return Err(Error::new(ErrorKind::TaskNotOwned)
                    .with_message(format!("holder task {holder:?} not found")));
            };

            if task_record.owner != region {
                return Err(Error::new(ErrorKind::TaskNotOwned).with_message(format!(
                    "holder task {holder:?} is owned by region {:?}, not {region:?}",
                    task_record.owner
                )));
            }

            if let Err(err) = region_record.try_reserve_obligation() {
                return Err(match err {
                    AdmissionError::Closed => {
                        Error::new(ErrorKind::RegionClosed).with_message("region closed")
                    }
                    AdmissionError::LimitReached { limit, live, .. } => {
                        Error::new(ErrorKind::AdmissionDenied).with_message(format!(
                            "region {region:?} obligation limit {limit} reached (live {live})"
                        ))
                    }
                });
            }
        }

        let acquired_at = SourceLocation::from_panic_location(std::panic::Location::caller());
        let acquire_backtrace = Self::capture_obligation_backtrace();
        let now = self.current_runtime_time();

        // Create the obligation first to get the ID
        let obligation_id =
            self.obligations
                .create(super::obligation_table::ObligationCreateArgs {
                    kind,
                    holder,
                    region,
                    now,
                    description,
                    acquired_at,
                    acquire_backtrace,
                });

        // Register obligation with cancel protocol validator
        {
            let mut validator = self.cancel_protocol_validator.lock();
            validator.register_obligation(obligation_id);
        }

        // Validate obligation creation protocol transition
        let context = ObligationContext {
            obligation_id,
            region_id: region,
            created_at: now,
            validation_level: CancelValidationLevel::Basic,
        };
        let validation_result = self.validate_obligation_protocol_transition(
            obligation_id,
            ObligationEvent::Reserve {
                token: obligation_id.arena_index().index() as u64,
            },
            &context,
        );
        if matches!(
            validation_result,
            TransitionResult::Invalid { .. } | TransitionResult::InvariantViolation { .. }
        ) {
            log_cancel_protocol_violation("obligation creation", &validation_result);
            // Continue with creation but log violation
        }

        let _guard = crate::tracing_compat::debug_span!(
            "obligation_reserve",
            obligation_id = ?obligation_id,
            kind = ?kind,
            holder_task = ?holder,
            region_id = ?region
        )
        .entered();
        crate::tracing_compat::debug!(
            obligation_id = ?obligation_id,
            kind = ?kind,
            holder_task = ?holder,
            region_id = ?region,
            "obligation reserved"
        );

        self.record_task_trace_event(holder, |seq| {
            TraceEvent::obligation_reserve(seq, now, obligation_id, holder, region, kind)
        });
        self.metrics.obligation_created(region);

        // Notify epoch tracker of obligation creation
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::ObligationTable);

        Ok(obligation_id)
    }

    /// Marks an obligation as committed and emits a trace event.
    ///
    /// Returns the duration the obligation was held (nanoseconds).
    #[allow(clippy::result_large_err)]
    pub fn commit_obligation(&mut self, obligation: ObligationId) -> Result<u64, Error> {
        let now = self.current_runtime_time();
        // Validate obligation commit protocol transition
        if let Some(record) = self.obligations.get(obligation.arena_index()) {
            let context = ObligationContext {
                obligation_id: obligation,
                region_id: record.region,
                created_at: record.reserved_at,
                validation_level: CancelValidationLevel::Basic,
            };
            let validation_result = self.validate_obligation_protocol_transition(
                obligation,
                ObligationEvent::Commit,
                &context,
            );
            if matches!(
                validation_result,
                TransitionResult::Invalid { .. } | TransitionResult::InvariantViolation { .. }
            ) {
                log_cancel_protocol_violation("obligation commit", &validation_result);
                // Continue with commit but log violation
            }
        }

        let info = self.obligations.commit(obligation, now)?;

        let span = crate::tracing_compat::debug_span!(
            "obligation_commit",
            obligation_id = ?info.id,
            kind = ?info.kind,
            holder_task = ?info.holder,
            region_id = ?info.region,
            duration_ns = info.duration
        );
        let _span_guard = span.enter();
        crate::tracing_compat::debug!(
            obligation_id = ?info.id,
            kind = ?info.kind,
            holder_task = ?info.holder,
            region_id = ?info.region,
            duration_ns = info.duration,
            "obligation committed"
        );

        self.record_task_trace_event(info.holder, |seq| {
            TraceEvent::obligation_commit(
                seq,
                now,
                info.id,
                info.holder,
                info.region,
                info.kind,
                info.duration,
            )
        });
        self.metrics.obligation_discharged(info.region);

        // Notify epoch tracker of obligation commit
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::ObligationTable);

        if let Some(region_record) = self.regions.get(info.region.arena_index()) {
            region_record.resolve_obligation();
        }

        self.advance_region_state(info.region);

        Ok(info.duration)
    }

    /// Marks an obligation as aborted and emits a trace event.
    ///
    /// Returns the duration the obligation was held (nanoseconds).
    #[allow(clippy::result_large_err)]
    pub fn abort_obligation(
        &mut self,
        obligation: ObligationId,
        reason: ObligationAbortReason,
    ) -> Result<u64, Error> {
        let now = self.current_runtime_time();
        // Validate obligation abort protocol transition
        if let Some(record) = self.obligations.get(obligation.arena_index()) {
            let context = ObligationContext {
                obligation_id: obligation,
                region_id: record.region,
                created_at: record.reserved_at,
                validation_level: CancelValidationLevel::Basic,
            };
            let validation_result = self.validate_obligation_protocol_transition(
                obligation,
                ObligationEvent::Abort {
                    reason: format!("{reason:?}"),
                },
                &context,
            );
            if matches!(
                validation_result,
                TransitionResult::Invalid { .. } | TransitionResult::InvariantViolation { .. }
            ) {
                log_cancel_protocol_violation("obligation abort", &validation_result);
                // Continue with abort but log violation
            }
        }

        let info = self.obligations.abort(obligation, now, reason)?;

        let span = crate::tracing_compat::debug_span!(
            "obligation_abort",
            obligation_id = ?info.id,
            kind = ?info.kind,
            holder_task = ?info.holder,
            region_id = ?info.region,
            duration_ns = info.duration,
            abort_reason = %info.reason
        );
        let _span_guard = span.enter();
        crate::tracing_compat::debug!(
            obligation_id = ?info.id,
            kind = ?info.kind,
            holder_task = ?info.holder,
            region_id = ?info.region,
            duration_ns = info.duration,
            abort_reason = %info.reason,
            "obligation aborted"
        );

        self.record_task_trace_event(info.holder, |seq| {
            TraceEvent::obligation_abort(
                seq,
                now,
                info.id,
                info.holder,
                info.region,
                info.kind,
                info.duration,
                info.reason,
            )
        });
        self.metrics.obligation_discharged(info.region);

        // Track obligation settlement work in debt monitor
        let cancel_reason = CancelReason::new(CancelKind::User);
        self.debt_monitor.queue_work(
            crate::observability::WorkType::ObligationSettlement,
            format!("obligation_{}_{}", info.id, info.holder),
            1, // Low priority for aborts
            1, // Low cost estimate
            &cancel_reason,
            CancelKind::Shutdown,
            Vec::new(),
        );

        // Notify epoch tracker of obligation abort
        self.notify_runtime_epoch_advance(super::epoch_tracker::ModuleId::ObligationTable);

        if let Some(region_record) = self.regions.get(info.region.arena_index()) {
            region_record.resolve_obligation();
        }

        self.advance_region_state(info.region);

        Ok(info.duration)
    }

    /// Marks an obligation as leaked and emits a trace + error event.
    ///
    /// Returns the duration the obligation was held (nanoseconds).
    #[allow(clippy::result_large_err)]
    pub fn mark_obligation_leaked(&mut self, obligation: ObligationId) -> Result<u64, Error> {
        let now = self.current_runtime_time();
        let info = self.obligations.mark_leaked(obligation, now)?;

        self.record_task_trace_event(info.holder, |seq| {
            TraceEvent::obligation_leak(
                seq,
                now,
                info.id,
                info.holder,
                info.region,
                info.kind,
                info.duration,
            )
        });
        self.metrics.obligation_leaked(info.region);
        if self.obligation_leak_response != ObligationLeakResponse::Silent {
            let span = crate::tracing_compat::error_span!(
                "obligation_leak",
                obligation_id = ?info.id,
                kind = ?info.kind,
                holder_task = ?info.holder,
                region_id = ?info.region,
                duration_ns = info.duration,
                acquired_at = %info.acquired_at
            );
            let _span_guard = span.enter();
            #[allow(clippy::single_match, unused_variables)]
            match info.acquire_backtrace.as_ref() {
                Some(backtrace) => {
                    crate::tracing_compat::error!(
                        obligation_id = ?info.id,
                        kind = ?info.kind,
                        holder_task = ?info.holder,
                        region_id = ?info.region,
                        duration_ns = info.duration,
                        acquired_at = %info.acquired_at,
                        acquire_backtrace = ?backtrace,
                        "obligation leaked"
                    );
                }
                None => {
                    crate::tracing_compat::error!(
                        obligation_id = ?info.id,
                        kind = ?info.kind,
                        holder_task = ?info.holder,
                        region_id = ?info.region,
                        duration_ns = info.duration,
                        acquired_at = %info.acquired_at,
                        "obligation leaked"
                    );
                }
            }
        }

        if let Some(region_record) = self.regions.get(info.region.arena_index()) {
            region_record.resolve_obligation();
        }

        self.advance_region_state(info.region);

        Ok(info.duration)
    }

    /// Gets a mutable reference to a stored future for polling.
    ///
    /// Returns `None` if no future is stored for this task.
    #[inline]
    pub fn get_stored_future(&mut self, task_id: TaskId) -> Option<&mut StoredTask> {
        self.tasks.get_stored_future(task_id)
    }

    /// Removes and returns a stored future.
    ///
    /// Called when a task completes to clean up the future storage.
    #[inline]
    pub fn remove_stored_future(&mut self, task_id: TaskId) -> Option<StoredTask> {
        self.tasks.remove_stored_future(task_id)
    }

    /// Stores a spawned task's future for execution.
    ///
    /// This is called after `Scope::spawn` to register the `StoredTask` with
    /// the runtime. The task must already have a `TaskRecord` created via spawn.
    ///
    /// # Arguments
    /// * `task_id` - The ID of the task (from the TaskHandle)
    /// * `stored` - The StoredTask containing the wrapped future
    ///
    /// # Example
    /// ```ignore
    /// let (handle, stored) = scope.spawn(&mut state, &cx, |_| async { 42 })?;
    /// state.store_spawned_task(handle.task_id(), stored);
    /// // Now the executor can poll the task
    /// ```
    #[inline]
    pub fn store_spawned_task(&mut self, task_id: TaskId, stored: StoredTask) {
        self.tasks.store_spawned_task(task_id, stored);
    }

    /// Counts live tasks.
    #[must_use]
    pub fn live_task_count(&self) -> usize {
        self.tasks_iter()
            .filter(|(_, t)| !t.state.is_terminal())
            .count()
    }

    /// Counts live regions.
    #[must_use]
    pub fn live_region_count(&self) -> usize {
        self.regions_iter()
            .filter(|(_, r)| !r.state().is_terminal())
            .count()
    }

    /// Counts pending obligations.
    ///
    /// O(1) — delegates to `ObligationTable::pending_count()` which maintains
    /// an incremental counter.
    #[inline]
    #[must_use]
    pub fn pending_obligation_count(&self) -> usize {
        self.obligations.pending_count()
    }

    /// Returns true if the runtime is quiescent (no live work).
    ///
    /// A runtime is quiescent when:
    /// - No live tasks are running
    /// - No pending obligations exist
    /// - No I/O sources are registered (if I/O driver is present)
    #[must_use]
    pub fn is_quiescent(&self) -> bool {
        // Short-circuit: each check is progressively more expensive, so bail
        // early if any preceding condition is already false.
        self.live_task_count() == 0
            && self.pending_obligation_count() == 0
            && self.io_driver.as_ref().is_none_or(IoDriverHandle::is_empty)
            && self.regions.iter().all(|(_, r)| r.finalizers_empty())
    }

    /// Applies the region policy when a child reaches a terminal outcome.
    ///
    /// This is the core hook for fail-fast behavior: the policy decides whether
    /// siblings should be cancelled.
    ///
    /// Returns the policy action taken and a list of tasks that need to be
    /// moved to the cancel lane in the scheduler.
    pub fn apply_policy_on_child_outcome<P: Policy<Error = crate::error::Error>>(
        &mut self,
        region: RegionId,
        child: TaskId,
        outcome: &Outcome<(), crate::error::Error>,
        policy: &P,
    ) -> (PolicyAction, SmallVec<[(TaskId, u8); 4]>) {
        let action = policy.on_child_outcome(child, outcome);
        let tasks_to_schedule = if let PolicyAction::CancelSiblings(reason) = &action {
            self.cancel_sibling_tasks(region, child, reason)
        } else {
            SmallVec::new()
        };
        (action, tasks_to_schedule)
    }

    /// Implements `inv.cancel.propagates_down` (#6, SEM-INV-003):
    /// cancel(region) -> cancel all non-Completed children.
    fn cancel_sibling_tasks(
        &mut self,
        region: RegionId,
        child: TaskId,
        reason: &CancelReason,
    ) -> SmallVec<[(TaskId, u8); 4]> {
        let Some(region_record) = self.regions.get(region.arena_index()) else {
            return SmallVec::new();
        };
        let sibling_candidates = region_record.task_ids_small();
        let mut tasks_to_cancel =
            SmallVec::with_capacity(sibling_candidates.len().saturating_sub(1));
        let now = self.current_runtime_time();

        for &task_id in &sibling_candidates {
            if task_id == child {
                continue;
            }
            let budget = reason.cleanup_budget();
            let (newly_cancelled, is_cancelling) = {
                let Some(task_record) = self.task_mut(task_id) else {
                    continue;
                };
                let newly_cancelled =
                    task_record.request_cancel_with_budget(reason.clone(), budget);
                let is_cancelling = task_record.state.is_cancelling();
                (newly_cancelled, is_cancelling)
            };
            if newly_cancelled {
                self.record_task_trace_event(task_id, |seq| {
                    TraceEvent::cancel_request(seq, now, task_id, region, reason.clone())
                });
            }
            if newly_cancelled || is_cancelling {
                tasks_to_cancel.push((task_id, budget.priority));
            }
        }
        tasks_to_cancel
    }

    /// Requests cancellation for a region and all its descendants.
    ///
    /// This implements the CANCEL-REQUEST transition from the formal semantics.
    /// Cancellation propagates down the region tree:
    /// - The target region's cancel_reason is set/strengthened
    /// - All descendant regions are marked with `ParentCancelled`
    /// - All tasks in affected regions are moved to `CancelRequested` state
    ///
    /// Returns a list of (TaskId, priority) pairs for tasks that should be
    /// moved to the cancel lane. The caller is responsible for updating the
    /// scheduler.
    ///
    /// # Arguments
    /// * `region_id` - The region to cancel
    /// * `reason` - The reason for cancellation
    /// * `source_task` - The task that initiated cancellation, if known
    ///
    /// # Example
    /// ```ignore
    /// let tasks_to_schedule = state.cancel_request(region, &CancelReason::timeout(), None);
    /// for (task_id, priority) in tasks_to_schedule {
    ///     scheduler.move_to_cancel_lane(task_id, priority);
    /// }
    /// ```
    #[allow(clippy::too_many_lines)]
    pub fn cancel_request(
        &mut self,
        region_id: RegionId,
        reason: &CancelReason,
        source_task: Option<TaskId>,
    ) -> Vec<(TaskId, u8)> {
        // Use a modest initial capacity instead of scanning the entire task
        // arena for live_task_count(). The Vec will grow if needed, but avoids
        // the O(arena_capacity) scan just for a size hint.
        let mut tasks_to_cancel = Vec::with_capacity(32);
        let cleanup_budget = reason.cleanup_budget();
        #[cfg(not(feature = "tracing-integration"))]
        let _ = (source_task, cleanup_budget);
        let root_span = debug_span!(
            "cancel_request",
            target_region = ?region_id,
            cancel_kind = ?reason.kind,
            cancel_message = ?reason.message,
            cleanup_poll_quota = cleanup_budget.poll_quota,
            cleanup_priority = cleanup_budget.priority,
            source_task = ?source_task
        );
        let _root_guard = root_span.enter();

        debug!(
            target_region = ?region_id,
            cancel_kind = ?reason.kind,
            cancel_message = ?reason.message,
            cleanup_poll_quota = cleanup_budget.poll_quota,
            cleanup_priority = cleanup_budget.priority,
            source_task = ?source_task,
            "cancel request initiated"
        );
        let now = self.current_runtime_time();

        // Collect all regions to cancel (target + descendants) with depth information
        let mut regions_to_cancel = self.collect_region_and_descendants_with_depth(region_id);

        // Sort by depth (ascending) to ensure parents are processed before children.
        // This is required for building proper cause chains.
        regions_to_cancel.sort_by_key(|node| node.depth);

        // Build a map of region -> cancel reason for cause chain construction.
        // Each child region's reason chains to its parent's reason.
        let mut region_reasons: HashMap<RegionId, CancelReason> =
            HashMap::with_capacity(regions_to_cancel.len());

        // First pass: mark regions with cancellation reason and transition to Closing
        for node in &regions_to_cancel {
            let rid = node.id;

            // Build the cancel reason with proper cause chain:
            // - Root region gets the original reason
            // - Descendants get ParentCancelled chained to their parent's reason
            let region_reason = if rid == region_id {
                reason.clone()
            } else if let Some(parent_id) = node.parent {
                // Look up parent's reason from the map (guaranteed to exist since we process by depth)
                let parent_reason = region_reasons
                    .get(&parent_id)
                    .cloned()
                    .unwrap_or_else(|| reason.clone());

                CancelReason::parent_cancelled()
                    .with_region(parent_id)
                    .with_timestamp(reason.timestamp)
                    .with_cause_limited(parent_reason, &self.cancel_attribution)
            } else {
                // Fallback: no parent but not root (shouldn't happen)
                CancelReason::parent_cancelled()
                    .with_timestamp(reason.timestamp)
                    .with_cause_limited(reason.clone(), &self.cancel_attribution)
            };

            // Store this region's reason for child chain building
            region_reasons.insert(rid, region_reason.clone());

            self.record_trace_event(|seq| {
                TraceEvent::region_cancelled(seq, now, rid, region_reason.clone())
            });
            self.metrics.cancellation_requested(rid, region_reason.kind);

            if let Some(parent) = node.parent {
                #[cfg(not(feature = "tracing-integration"))]
                let _ = parent;
                let span = trace_span!(
                    "cancel_propagate_region",
                    from_region = ?parent,
                    to_region = ?rid,
                    depth = node.depth,
                    cancel_kind = ?region_reason.kind,
                    chain_depth = region_reason.chain_depth()
                );
                span.follows_from(&root_span);
                let _guard = span.enter();
                trace!(
                    from_region = ?parent,
                    to_region = ?rid,
                    depth = node.depth,
                    cancel_kind = ?region_reason.kind,
                    chain_depth = region_reason.chain_depth(),
                    root_cause = ?region_reason.root_cause().kind,
                    "cancel propagated to region with cause chain"
                );
            } else {
                trace!(
                    target_region = ?rid,
                    depth = node.depth,
                    cancel_kind = ?region_reason.kind,
                    "cancel target region"
                );
            }

            if let Some(region) = self.regions.get(rid.arena_index()) {
                // Use the properly chained reason.
                // Try to transition to Closing with the reason.
                // If already Closing/Draining/etc., strengthen the reason instead.
                if region.begin_close(Some(region_reason.clone())) {
                    self.record_trace_event(|seq| {
                        TraceEvent::new(
                            seq,
                            now,
                            TraceEventKind::RegionCloseBegin,
                            TraceData::Region {
                                region: rid,
                                parent: node.parent,
                            },
                        )
                    });
                } else if region.state() != crate::record::region::RegionState::Closed {
                    region.strengthen_cancel_reason(region_reason);
                }
            }
        }

        // Second pass: mark tasks for cancellation.
        // Reuse a single buffer across iterations to avoid per-region allocation.
        let mut task_id_buf = Vec::new();
        for node in &regions_to_cancel {
            let rid = node.id;
            // Need to get tasks list first to avoid borrow conflict
            task_id_buf.clear();
            if let Some(region) = self.regions.get(rid.arena_index()) {
                region.copy_task_ids_into(&mut task_id_buf);
            }

            // Get the region's cancel reason with proper cause chain
            let task_reason = region_reasons
                .get(&rid)
                .cloned()
                .unwrap_or_else(|| reason.clone());

            for &task_id in &task_id_buf {
                if let Some(task) = self.task_mut(task_id) {
                    let task_budget = task_reason.cleanup_budget();
                    let newly_cancelled =
                        task.request_cancel_with_budget(task_reason.clone(), task_budget);
                    let already_cancelling = task.state.is_cancelling();
                    let cancel_kind = task.cancel_reason().map(|r| r.kind);
                    #[cfg(not(feature = "tracing-integration"))]
                    let _ = cancel_kind;
                    if newly_cancelled {
                        self.record_task_trace_event(task_id, |seq| {
                            TraceEvent::cancel_request(seq, now, task_id, rid, task_reason.clone())
                        });
                    }
                    let span = trace_span!(
                        "cancel_propagate_task",
                        from_region = ?rid,
                        to_task = ?task_id,
                        depth = node.depth,
                        cancel_kind = ?cancel_kind,
                        chain_depth = task_reason.chain_depth()
                    );
                    span.follows_from(&root_span);
                    let _guard = span.enter();
                    trace!(
                        from_region = ?rid,
                        to_task = ?task_id,
                        depth = node.depth,
                        newly_cancelled,
                        already_cancelling,
                        cleanup_poll_quota = task_budget.poll_quota,
                        cleanup_priority = task_budget.priority,
                        chain_depth = task_reason.chain_depth(),
                        root_cause = ?task_reason.root_cause().kind,
                        "cancel propagated to task with cause chain"
                    );

                    if newly_cancelled {
                        // Task was newly cancelled, add to list
                        tasks_to_cancel.push((task_id, task_budget.priority));
                    } else if already_cancelling {
                        // Task already cancelling, but still needs scheduling priority
                        tasks_to_cancel.push((task_id, task_budget.priority));
                    }
                }
            }
        }

        // Ensure regions with pending finalizers and no live work can advance into
        // Finalizing immediately so finalizers are scheduled without waiting for
        // task completion.
        for node in &regions_to_cancel {
            let Some(region) = self.regions.get(node.id.arena_index()) else {
                continue;
            };
            let no_children = region.child_count() == 0;
            let no_tasks = region.task_count() == 0;
            if no_children && no_tasks {
                self.advance_region_state(node.id);
            }
        }

        tasks_to_cancel
    }

    /// Collects a region and all its descendants (recursive).
    ///
    /// Returns a Vec containing the region and all nested child regions.
    fn collect_region_and_descendants_with_depth(
        &self,
        region_id: RegionId,
    ) -> Vec<CancelRegionNode> {
        let mut result = Vec::new();
        let mut stack = Vec::new();
        let mut child_buf = Vec::new();
        stack.push((region_id, None, 0usize));

        while let Some((rid, parent, depth)) = stack.pop() {
            result.push(CancelRegionNode {
                id: rid,
                parent,
                depth,
            });

            if let Some(region) = self.regions.get(rid.arena_index()) {
                child_buf.clear();
                region.copy_child_ids_into(&mut child_buf);
                for &child_id in &child_buf {
                    stack.push((child_id, Some(rid), depth + 1));
                }
            }
        }

        result
    }

    /// Checks if a region can transition to finalization.
    ///
    /// A region can finalize when all its tasks and child regions have completed.
    /// Returns `true` if the region has no live work remaining.
    #[must_use]
    pub fn can_region_finalize(&self, region_id: RegionId) -> bool {
        let Some(region) = self.regions.get(region_id.arena_index()) else {
            return false;
        };

        // Check all tasks are terminal
        let all_tasks_done = region
            .task_ids()
            .iter()
            .all(|&task_id| self.task(task_id).is_none_or(|t| t.state.is_terminal()));

        // Check all child regions are closed
        let all_children_closed = region.child_ids().iter().all(|&child_id| {
            self.regions
                .get(child_id.arena_index())
                .is_none_or(|r| r.state().is_terminal())
        });

        all_tasks_done && all_children_closed
    }

    /// Notifies that a task has completed.
    ///
    /// This checks if the owning region can advance its state.
    /// Returns the task's waiters that should be woken.
    pub fn task_completed(&mut self, task_id: TaskId) -> SmallVec<[TaskId; 4]> {
        let (owner, completion, outcome_kind) = {
            let Some(task) = self.task(task_id) else {
                trace!(
                    task_id = ?task_id,
                    "task_completed called for unknown task"
                );
                return SmallVec::new();
            };

            // Validate task completion protocol transition
            let context = TaskContext {
                task_id,
                region_id: task.owner,
                spawned_at: task.created_at,
                validation_level: CancelValidationLevel::Basic,
            };
            let validation_result =
                self.validate_task_protocol_transition(task_id, TaskEvent::Complete, &context);
            if matches!(
                validation_result,
                TransitionResult::Invalid { .. } | TransitionResult::InvariantViolation { .. }
            ) {
                log_cancel_protocol_violation("task completion", &validation_result);
                // Continue with completion but log violation
            }
            if let Some(inner) = task.cx_inner.as_ref() {
                // Read-first: skip the write lock when cancel_waker is already
                // None (the common case — waker was cached back into the record).
                if inner.read().cancel_waker.is_some() {
                    inner.write().cancel_waker = None;
                }
            }

            self.record_task_complete(task);

            let outcome_kind = match &task.state {
                crate::record::task::TaskState::Completed(outcome) => match outcome {
                    Outcome::Ok(()) => "Ok",
                    Outcome::Err(_) => "Err",
                    Outcome::Cancelled(_) => "Cancelled",
                    Outcome::Panicked(_) => "Panicked",
                },
                _ => "Unknown",
            };
            let owner = task.owner;
            let completion = TaskCompletionKind::from_state(&task.state);
            (owner, completion, outcome_kind)
        };
        // Take waiters by value (avoiding clone) since the task is about to be removed.
        let waiters = self
            .task_mut(task_id)
            .map(|task| std::mem::take(&mut task.waiters))
            .unwrap_or_default();
        let waiter_count = waiters.len();
        #[cfg(not(feature = "tracing-integration"))]
        let _ = (outcome_kind, waiter_count);

        if !matches!(completion, TaskCompletionKind::Cancelled) {
            let leaks = self.collect_obligation_leaks_for_holder(task_id);
            if !leaks.is_empty() {
                self.handle_obligation_leaks(ObligationLeakError {
                    task_id: Some(task_id),
                    region_id: owner,
                    completion: Some(completion),
                    leaks,
                });
            }
        }

        if let Some(finalizer_id) = self.async_finalizer_tasks.remove(&task_id) {
            let should_clear_barrier = self
                .active_async_finalizers
                .get(&owner)
                .is_some_and(|active_task| *active_task == task_id);
            if should_clear_barrier {
                self.active_async_finalizers.remove(&owner);
            }
            self.record_finalizer_run(finalizer_id);
        }

        // Trace task completion
        debug!(
            task_id = ?task_id,
            region_id = ?owner,
            outcome_kind = outcome_kind,
            waiter_count = waiter_count,
            "task cleanup from runtime state"
        );

        // Abort any pending obligations held by this task to prevent
        // orphaned obligations from blocking region close (deadlock).
        // Uses the holder secondary index for O(obligations_per_task) instead of O(arena_capacity).
        let orphaned = self.obligations.sorted_pending_ids_for_holder(task_id);
        for ob_id in orphaned {
            let _ = self.abort_obligation(ob_id, ObligationAbortReason::Cancel);
        }

        // Remove the task record to prevent memory leaks
        let _ = self.remove_task(task_id);

        // Remove task from owning region to prevent memory leak
        if let Some(region) = self.regions.get(owner.arena_index()) {
            region.remove_task(task_id);
        }

        // Advance region state if possible (e.g. if this was the last task)
        self.advance_region_state(owner);

        // Return the waiters for the completed task
        waiters
    }

    // =========================================================================
    // Async Finalizer Scheduling
    // =========================================================================

    /// Drains async finalizers for regions that are ready to run them.
    ///
    /// This runs sync finalizers inline and schedules at most one async
    /// finalizer per region (respecting the async barrier).
    pub fn drain_ready_async_finalizers(&mut self) -> SmallVec<[(TaskId, u8); 2]> {
        if self.finalizing_regions.is_empty() {
            return SmallVec::new();
        }
        let mut scheduled = SmallVec::new();
        let mut regions_to_process = SmallVec::<[RegionId; 8]>::new();

        for &region_id in &self.finalizing_regions {
            if self.active_async_finalizers.contains_key(&region_id) {
                continue;
            }
            if let Some(region) = self.regions.get(region_id.arena_index()) {
                if !region.finalizers_empty() {
                    regions_to_process.push(region_id);
                }
            }
        }

        for region_id in regions_to_process {
            let Some((finalizer_id, finalizer)) = self.run_sync_finalizers_tracked(region_id)
            else {
                continue;
            };
            let Finalizer::Async(future) = finalizer else {
                continue;
            };
            match self.spawn_finalizer_task(region_id, finalizer_id, future) {
                Ok((task_id, priority)) => scheduled.push((task_id, priority)),
                Err(future) => {
                    // Preserve the async barrier when task admission fails so
                    // the region cannot close with cleanup silently dropped.
                    if let Some(region) = self.regions.get(region_id.arena_index()) {
                        region.add_finalizer(Finalizer::Async(future));
                    }
                    self.pending_finalizer_ids
                        .entry(region_id)
                        .or_default()
                        .push(finalizer_id);
                }
            }
        }

        scheduled
    }

    fn spawn_finalizer_task(
        &mut self,
        region_id: RegionId,
        finalizer_id: u64,
        future: BoxedAsyncFinalizer,
    ) -> Result<(TaskId, u8), BoxedAsyncFinalizer> {
        let deadline = self
            .current_runtime_time()
            .saturating_add_nanos(FINALIZER_TIME_BUDGET_NANOS);
        let budget = finalizer_budget().with_deadline(deadline);

        let Ok((task_id, _handle, cx, result_tx)) =
            self.create_task_infrastructure::<()>(region_id, budget, true)
        else {
            return Err(future);
        };
        let cx_inner = Arc::clone(&cx.inner);
        let masked = MaskedFinalizer::new(future, cx_inner);

        let wrapped_future = async move {
            match (CatchUnwind { inner: masked }).await {
                Ok(()) => {
                    let _ = result_tx.send(&cx, Ok::<_, JoinError>(()));
                    Outcome::Ok(())
                }
                Err(payload) => {
                    let panic_payload =
                        crate::types::outcome::PanicPayload::new(payload_to_string(&payload));
                    let _ = result_tx.send(
                        &cx,
                        Err::<(), JoinError>(JoinError::Panicked(panic_payload.clone())),
                    );
                    Outcome::Panicked(panic_payload)
                }
            }
        };

        self.tasks
            .store_spawned_task(task_id, StoredTask::new_with_id(wrapped_future, task_id));

        // Mark the task as notified since it will be immediately injected into
        // the ready queue by the caller (drain_ready_async_finalizers).
        if let Some(record) = self.task(task_id) {
            record.wake_state.notify();
        }

        self.async_finalizer_tasks.insert(task_id, finalizer_id);
        let previous = self.active_async_finalizers.insert(region_id, task_id);
        debug_assert!(
            previous.is_none(),
            "region {:?} already had an active async finalizer barrier: {:?}",
            region_id,
            previous
        );
        Ok((task_id, budget.priority))
    }

    // =========================================================================
    // Finalizer Registration
    // =========================================================================

    /// Registers a synchronous finalizer for a region.
    ///
    /// Finalizers are stored in LIFO order and run when the region transitions
    /// to the Finalizing state, after all children have completed.
    ///
    /// # Arguments
    /// * `region_id` - The region to register the finalizer with
    /// * `f` - The synchronous cleanup function
    ///
    /// # Returns
    /// `true` if the finalizer was registered, `false` if the region doesn't exist
    /// or is not in a state that accepts finalizers.
    pub fn register_sync_finalizer<F>(&mut self, region_id: RegionId, f: F) -> bool
    where
        F: FnOnce() + Send + 'static,
    {
        let accepts_finalizers = self
            .regions
            .get(region_id.arena_index())
            .is_some_and(|region| !region.state().is_closing() && !region.state().is_terminal());
        if !accepts_finalizers {
            return false;
        }

        let finalizer_id = self.allocate_finalizer_id();
        {
            let Some(region) = self.regions.get(region_id.arena_index()) else {
                return false;
            };
            region.add_finalizer(Finalizer::Sync(Box::new(f)));
        }
        self.record_finalizer_registration(finalizer_id, region_id);

        // Track finalizer work in debt monitor
        let cancel_reason = CancelReason::user("sync_finalizer_registration");
        self.debt_monitor.queue_work(
            crate::observability::WorkType::RegionCleanup,
            format!("sync_finalizer_{finalizer_id}_{region_id}"),
            5, // Medium priority for cleanup
            2, // Medium cost estimate
            &cancel_reason,
            CancelKind::Shutdown,
            Vec::new(),
        );

        true
    }

    /// Registers an asynchronous finalizer for a region.
    ///
    /// Async finalizers run under a cancel mask to prevent interruption.
    /// They are driven to completion with a bounded budget.
    ///
    /// # Arguments
    /// * `region_id` - The region to register the finalizer with
    /// * `future` - The async cleanup future
    ///
    /// # Returns
    /// `true` if the finalizer was registered, `false` if the region doesn't exist
    /// or is not in a state that accepts finalizers.
    pub fn register_async_finalizer<F>(&mut self, region_id: RegionId, future: F) -> bool
    where
        F: Future<Output = ()> + Send + 'static,
    {
        let accepts_finalizers = self
            .regions
            .get(region_id.arena_index())
            .is_some_and(|region| !region.state().is_closing() && !region.state().is_terminal());
        if !accepts_finalizers {
            return false;
        }

        let finalizer_id = self.allocate_finalizer_id();
        {
            let Some(region) = self.regions.get(region_id.arena_index()) else {
                return false;
            };
            region.add_finalizer(Finalizer::Async(Box::pin(future)));
        }
        self.record_finalizer_registration(finalizer_id, region_id);

        // Track async finalizer work in debt monitor
        let cancel_reason = CancelReason::user("async_finalizer_registration");
        self.debt_monitor.queue_work(
            crate::observability::WorkType::RegionCleanup,
            format!("async_finalizer_{finalizer_id}_{region_id}"),
            6, // Medium-high priority for async cleanup
            3, // Higher cost estimate for async work
            &cancel_reason,
            CancelKind::Shutdown,
            Vec::new(),
        );

        true
    }

    fn allocate_finalizer_id(&mut self) -> u64 {
        let id = self.next_finalizer_id;
        self.next_finalizer_id = self
            .next_finalizer_id
            .checked_add(1)
            .expect("finalizer ID overflow");
        id
    }

    fn record_finalizer_registration(&mut self, id: u64, region: RegionId) {
        let now = self.current_runtime_time();
        self.pending_finalizer_ids
            .entry(region)
            .or_default()
            .push(id);
        self.finalizer_history
            .push(FinalizerHistoryEvent::Registered {
                id,
                region,
                time: now,
            });
    }

    fn record_finalizer_run(&mut self, id: u64) {
        let now = self.current_runtime_time();
        self.finalizer_history
            .push(FinalizerHistoryEvent::Ran { id, time: now });
    }

    fn record_finalizer_close(&mut self, region: RegionId) {
        let now = self.current_runtime_time();
        self.pending_finalizer_ids.remove(&region);
        self.finalizer_history
            .push(FinalizerHistoryEvent::RegionClosed { region, time: now });
    }

    fn pop_tracked_finalizer(&mut self, region_id: RegionId) -> Option<(u64, Finalizer)> {
        let finalizer = {
            let region = self.regions.get(region_id.arena_index())?;
            region.pop_finalizer()?
        };
        let (id, empty_after_pop) = {
            let ids = self
                .pending_finalizer_ids
                .get_mut(&region_id)
                .expect("finalizer id tracking missing for region");
            let id = ids.pop().expect("finalizer id stack out of sync");
            (id, ids.is_empty())
        };
        if empty_after_pop {
            self.pending_finalizer_ids.remove(&region_id);
        }
        Some((id, finalizer))
    }

    /// Pops the next finalizer from a region's finalizer stack.
    ///
    /// This is called during the Finalizing phase to get the next cleanup
    /// handler to run. Finalizers are returned in LIFO order.
    ///
    /// # Returns
    /// The next finalizer to run, or `None` if all finalizers have been executed.
    pub fn pop_region_finalizer(&mut self, region_id: RegionId) -> Option<Finalizer> {
        self.pop_tracked_finalizer(region_id)
            .map(|(_, finalizer)| finalizer)
    }

    /// Returns the number of pending finalizers for a region.
    #[must_use]
    pub fn region_finalizer_count(&self, region_id: RegionId) -> usize {
        self.regions
            .get(region_id.arena_index())
            .map_or(0, RegionRecord::finalizer_count)
    }

    /// Returns true if a region has no pending finalizers.
    #[must_use]
    pub fn region_finalizers_empty(&self, region_id: RegionId) -> bool {
        self.regions
            .get(region_id.arena_index())
            .is_none_or(RegionRecord::finalizers_empty)
    }

    /// Runs synchronous finalizers for a region until an async finalizer is encountered or the stack is empty.
    ///
    /// This method pops and executes sync finalizers in LIFO order.
    /// If an async finalizer is encountered, it is returned immediately (and not executed).
    /// The caller must schedule/await the async finalizer before calling this method again
    /// to process remaining finalizers.
    ///
    /// # Returns
    /// An async finalizer that needs to be scheduled, or `None` if the stack is empty.
    pub fn run_sync_finalizers(&mut self, region_id: RegionId) -> Option<Finalizer> {
        self.run_sync_finalizers_tracked(region_id)
            .map(|(_, finalizer)| finalizer)
    }

    fn run_sync_finalizers_tracked(&mut self, region_id: RegionId) -> Option<(u64, Finalizer)> {
        loop {
            let (finalizer_id, finalizer) = self.pop_tracked_finalizer(region_id)?;

            match finalizer {
                Finalizer::Sync(f) => {
                    // Run synchronously, catching panics to ensure remaining
                    // finalizers still execute and the region is not permanently
                    // stuck in Finalizing state.
                    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() {
                        // Log but continue — a panicking finalizer must not
                        // block region close or skip sibling finalizers.
                    }
                    self.record_finalizer_run(finalizer_id);
                }
                Finalizer::Async(_) => {
                    // Stop and return the async barrier
                    return Some((finalizer_id, finalizer));
                }
            }
        }
    }

    /// Checks if a region can complete its close sequence.
    ///
    /// A region can complete close when:
    /// 1. It's in the Finalizing state
    /// 2. All finalizers have been executed
    /// 3. All tasks (including those spawned by finalizers) are terminal
    /// 4. All obligations are resolved
    ///
    /// # Returns
    /// `true` if the region can transition to Closed state.
    #[must_use]
    pub fn can_region_complete_close(&self, region_id: RegionId) -> bool {
        let Some(region) = self.regions.get(region_id.arena_index()) else {
            return false;
        };

        if region.state() == crate::record::region::RegionState::Closed {
            return true;
        }

        // Must be in Finalizing state
        if region.state() != crate::record::region::RegionState::Finalizing {
            return false;
        }

        // All finalizers must be done
        if !region.finalizers_empty() {
            return false;
        }

        // All tasks must be fully completed and cleaned up.
        // We cannot just check if they are terminal, because their `task_completed`
        // cleanup might not have run yet, and closing the region clears the heap prematurely.
        if region.task_count() > 0 {
            return false;
        }

        // All obligations must be resolved
        if region.pending_obligations() > 0 {
            return false;
        }

        // All children must be fully closed and removed
        if region.child_count() > 0 {
            return false;
        }

        true
    }

    /// Advances the region state machine if possible.
    ///
    /// This method checks if the region can transition to the next state in its
    /// lifecycle (Closing -> Draining -> Finalizing -> Closed). It drives the
    /// transitions automatically when prerequisites (no children, no tasks, etc.)
    /// are met.
    ///
    /// This should be called whenever a task completes, a child region closes,
    /// or an obligation is resolved.
    ///
    /// Uses an iterative loop instead of recursion to bound stack depth and
    /// enable future migration to `ShardGuard`-based locking (where recursive
    /// self-calls would deadlock on non-reentrant mutexes).
    #[allow(clippy::too_many_lines)]
    pub fn advance_region_state(&mut self, initial_region: RegionId) {
        let mut current = Some(initial_region);

        while let Some(region_id) = current.take() {
            // Get state and parent without holding a long borrow on self.regions
            let (state, parent) = {
                let Some(region) = self.regions.get(region_id.arena_index()) else {
                    break;
                };
                (region.state(), region.parent)
            };

            match state {
                crate::record::region::RegionState::Closing
                | crate::record::region::RegionState::Draining => {
                    // Transition to Finalizing only once child regions and tasks are gone.
                    let transition_to_finalizing = {
                        let Some(region) = self.regions.get(region_id.arena_index()) else {
                            break;
                        };
                        let no_children = region.child_count() == 0;
                        let no_tasks = region.task_count() == 0;
                        if no_children && no_tasks {
                            // Validate protocol transition to Finalizing
                            let context = RegionContext {
                                region_id,
                                parent_region: region.parent,
                                created_at: region.created_at,
                                validation_level: CancelValidationLevel::Basic,
                            };
                            let validation_result = self.validate_region_protocol_transition(
                                region_id,
                                RegionEvent::RequestClose, // Use RequestClose for finalization
                                &context,
                            );
                            if matches!(
                                validation_result,
                                TransitionResult::Invalid { .. }
                                    | TransitionResult::InvariantViolation { .. }
                            ) {
                                log_cancel_protocol_violation(
                                    "region finalize transition",
                                    &validation_result,
                                );
                                // Continue with transition but log violation
                            }

                            region.begin_finalize()
                        } else {
                            if !no_children
                                && region.state() == crate::record::region::RegionState::Closing
                            {
                                // Validate protocol transition to Draining
                                let context = RegionContext {
                                    region_id,
                                    parent_region: region.parent,
                                    created_at: region.created_at,
                                    validation_level: CancelValidationLevel::Basic,
                                };
                                let validation_result = self.validate_region_protocol_transition(
                                    region_id,
                                    RegionEvent::Cancel {
                                        reason: "draining children".to_string(),
                                    },
                                    &context,
                                );
                                if matches!(
                                    validation_result,
                                    TransitionResult::Invalid { .. }
                                        | TransitionResult::InvariantViolation { .. }
                                ) {
                                    log_cancel_protocol_violation(
                                        "region drain transition",
                                        &validation_result,
                                    );
                                    // Continue with transition but log violation
                                }

                                region.begin_drain();
                                self.notify_runtime_epoch_advance(
                                    super::epoch_tracker::ModuleId::RegionTable,
                                );
                            }
                            false
                        }
                    };

                    if transition_to_finalizing {
                        self.notify_runtime_epoch_advance(
                            super::epoch_tracker::ModuleId::RegionTable,
                        );
                        self.finalizing_regions.push(region_id);
                        // Re-process same region as Finalizing in next iteration
                        current = Some(region_id);
                    }
                }
                crate::record::region::RegionState::Finalizing => {
                    if self.active_async_finalizers.contains_key(&region_id) {
                        break;
                    }

                    // Run sync finalizers (requires mut self).
                    // If we hit an async finalizer, reinsert it and wait for a scheduler.
                    if let Some((finalizer_id, async_finalizer)) =
                        self.run_sync_finalizers_tracked(region_id)
                    {
                        if let Some(region) = self.regions.get(region_id.arena_index()) {
                            region.add_finalizer(async_finalizer);
                        }
                        self.pending_finalizer_ids
                            .entry(region_id)
                            .or_default()
                            .push(finalizer_id);
                        break; // Async finalizer pending; stop advancing
                    }

                    // If finalizing and obligations remain with no tracked tasks, mark leaks.
                    // Terminal task state is not enough here: `task_completed` still has to
                    // abort or leak-resolve orphaned obligations and unlink the task from the
                    // region. Finalizing leak detection must therefore wait for full task
                    // cleanup, not just a terminal outcome.
                    if let Some(region) = self.regions.get(region_id.arena_index()) {
                        if region.pending_obligations() > 0 {
                            if region.task_count() == 0 {
                                let leaks = self
                                    .collect_obligation_leaks(|record| record.region == region_id);
                                if !leaks.is_empty() {
                                    self.handle_obligation_leaks(ObligationLeakError {
                                        task_id: None,
                                        region_id,
                                        completion: None,
                                        leaks,
                                    });
                                }
                            }
                        }
                    }

                    // Check if we can complete close
                    if self.can_region_complete_close(region_id) {
                        // Validate protocol transition to Closed
                        let closed = {
                            let Some(region) = self.regions.get(region_id.arena_index()) else {
                                break;
                            };
                            let context = RegionContext {
                                region_id,
                                parent_region: region.parent,
                                created_at: region.created_at,
                                validation_level: CancelValidationLevel::Basic,
                            };
                            let validation_result = self.validate_region_protocol_transition(
                                region_id,
                                RegionEvent::FinalizerCompleted, // Use FinalizerCompleted for close
                                &context,
                            );
                            if matches!(
                                validation_result,
                                TransitionResult::Invalid { .. }
                                    | TransitionResult::InvariantViolation { .. }
                            ) {
                                log_cancel_protocol_violation(
                                    "region close completion",
                                    &validation_result,
                                );
                                // Continue with transition but log violation
                            }

                            region.complete_close()
                        };

                        if closed {
                            if let Some(pos) =
                                self.finalizing_regions.iter().position(|&r| r == region_id)
                            {
                                self.finalizing_regions.swap_remove(pos);
                            }
                            self.record_finalizer_close(region_id);

                            // Emit RegionCloseComplete trace event (pairs
                            // with RegionCloseBegin emitted in cancel_request).
                            let now = self.current_runtime_time();
                            self.record_trace_event(|seq| {
                                TraceEvent::new(
                                    seq,
                                    now,
                                    TraceEventKind::RegionCloseComplete,
                                    TraceData::Region {
                                        region: region_id,
                                        parent,
                                    },
                                )
                            });

                            // Emit region_closed metric with lifetime.
                            if let Some(region) = self.regions.get(region_id.arena_index()) {
                                let lifetime =
                                    Duration::from_nanos(now.duration_since(region.created_at()));
                                self.metrics.region_closed(region_id, lifetime);
                            }

                            if let Some(parent_id) = parent {
                                // Remove from parent
                                if let Some(parent_record) =
                                    self.regions.get(parent_id.arena_index())
                                {
                                    parent_record.remove_child(region_id);
                                }
                                // Advance parent in next iteration
                                current = Some(parent_id);
                            }

                            self.remember_closed_region(region_id);
                            // Cleanup: Remove the closed region from the arena to prevent memory leaks
                            self.regions.remove(region_id.arena_index());
                            self.notify_runtime_epoch_advance(
                                super::epoch_tracker::ModuleId::RegionTable,
                            );
                        }
                    }
                }
                _ => {}
            }
        }
    }

    fn remember_closed_region(&mut self, region_id: RegionId) {
        if !self.recently_closed_regions.insert(region_id) {
            return;
        }

        self.recently_closed_region_order.push_back(region_id);
        while self.recently_closed_region_order.len() > Self::RECENTLY_CLOSED_REGION_CAPACITY {
            if let Some(evicted) = self.recently_closed_region_order.pop_front() {
                self.recently_closed_regions.remove(&evicted);
            }
        }
    }

    pub(crate) fn finalizer_history(&self) -> &[FinalizerHistoryEvent] {
        &self.finalizer_history
    }

    #[cfg(test)]
    pub(crate) fn record_finalizer_close_for_test(&mut self, region: RegionId) {
        self.record_finalizer_close(region);
    }

    /// Returns a reference to the resource monitor for graceful degradation.
    ///
    /// The resource monitor tracks memory, file descriptors, CPU load, and network
    /// connections, and triggers degradation policies when thresholds are exceeded.
    pub fn resource_monitor(&self) -> Arc<ResourceMonitor> {
        Arc::clone(&self.resource_monitor)
    }

    /// Sets the priority for a region in the graceful degradation system.
    ///
    /// Higher priority regions (Critical, High) are preserved during resource
    /// pressure, while lower priority regions (Low, BestEffort) are shed first.
    ///
    /// # Arguments
    /// * `region_id` - The region to set the priority for
    /// * `priority` - The new priority level for the region
    ///
    /// # Returns
    /// * `true` if the region exists and priority was set
    /// * `false` if the region does not exist
    pub fn set_region_priority(&mut self, region_id: RegionId, priority: RegionPriority) -> bool {
        if self.regions.get(region_id.arena_index()).is_none() {
            return false;
        }
        self.resource_monitor
            .engine()
            .set_region_priority(region_id, priority);
        true
    }

    /// Checks if the runtime should accept new work based on resource pressure.
    ///
    /// Returns `true` if resource pressure is acceptable for new regions/tasks,
    /// or `false` if the runtime should apply backpressure.
    pub fn should_accept_new_work(&self) -> bool {
        let composite_level = self
            .resource_monitor
            .pressure()
            .composite_degradation_level();
        matches!(
            composite_level,
            DegradationLevel::None | DegradationLevel::Light
        )
    }

    /// Gets the current degradation level and statistics.
    ///
    /// This provides visibility into the current resource pressure state
    /// for monitoring and debugging purposes.
    pub fn degradation_stats(&self) -> DegradationStatsSnapshot {
        self.resource_monitor.engine().stats()
    }

    /// Applies resource-based work shedding decisions during region creation.
    ///
    /// This integrates the graceful degradation system with region creation
    /// by rejecting new regions when resource pressure is high and the
    /// requested region priority is below the shedding threshold.
    ///
    /// # Arguments
    /// * `priority` - Priority of the region being created
    ///
    /// # Returns
    /// * `Ok(())` if the region should be allowed
    /// * `Err(RegionCreateError)` if the region should be rejected due to resource pressure
    pub fn check_resource_pressure_for_region(
        &self,
        priority: RegionPriority,
    ) -> Result<(), RegionCreateError> {
        let composite_level = self
            .resource_monitor
            .pressure()
            .composite_degradation_level();

        // Apply shedding based on degradation level and region priority
        let should_shed = match (composite_level, priority) {
            // Critical/High regions are never shed
            (_, RegionPriority::Critical | RegionPriority::High) => false,
            // Normal regions are shed under Heavy or Emergency pressure
            (DegradationLevel::Heavy | DegradationLevel::Emergency, RegionPriority::Normal) => true,
            // Low/BestEffort regions are shed under Moderate+ pressure
            (
                DegradationLevel::Moderate | DegradationLevel::Heavy | DegradationLevel::Emergency,
                RegionPriority::Low | RegionPriority::BestEffort,
            ) => true,
            // Allow in all other cases
            _ => false,
        };

        if should_shed {
            Err(RegionCreateError::ResourcePressure {
                requested_priority: priority,
                reason: format!(
                    "Resource pressure level {:?} prevents region creation at priority {:?}",
                    composite_level, priority
                ),
            })
        } else {
            Ok(())
        }
    }
}

impl Default for RuntimeState {
    fn default() -> Self {
        Self::new()
    }
}

/// Serializable identifier snapshot.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct IdSnapshot {
    /// Arena index for the entity.
    pub index: u32,
    /// Generation counter for ABA safety.
    pub generation: u32,
}

impl From<RegionId> for IdSnapshot {
    fn from(id: RegionId) -> Self {
        let arena = id.arena_index();
        Self {
            index: arena.index(),
            generation: arena.generation(),
        }
    }
}

impl From<TaskId> for IdSnapshot {
    fn from(id: TaskId) -> Self {
        let arena = id.arena_index();
        Self {
            index: arena.index(),
            generation: arena.generation(),
        }
    }
}

impl From<ObligationId> for IdSnapshot {
    fn from(id: ObligationId) -> Self {
        let arena = id.arena_index();
        Self {
            index: arena.index(),
            generation: arena.generation(),
        }
    }
}

/// Serializable budget snapshot.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct BudgetSnapshot {
    /// Deadline in nanoseconds, if any.
    pub deadline: Option<u64>,
    /// Poll quota for the budget.
    pub poll_quota: u32,
    /// Optional cost quota.
    pub cost_quota: Option<u64>,
    /// Scheduling priority (0-255).
    pub priority: u8,
}

impl From<Budget> for BudgetSnapshot {
    fn from(budget: Budget) -> Self {
        Self {
            deadline: budget.deadline.map(Time::as_nanos),
            poll_quota: budget.poll_quota,
            cost_quota: budget.cost_quota,
            priority: budget.priority,
        }
    }
}

/// Snapshot of the runtime state for debugging or visualization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeSnapshot {
    /// Snapshot timestamp in nanoseconds.
    pub timestamp: u64,
    /// Region snapshots.
    pub regions: Vec<RegionSnapshot>,
    /// Task snapshots.
    pub tasks: Vec<TaskSnapshot>,
    /// Obligation snapshots.
    pub obligations: Vec<ObligationSnapshot>,
    /// Recent trace events (if tracing is enabled).
    pub recent_events: Vec<EventSnapshot>,
}

/// Serializable region snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionSnapshot {
    /// Region identifier.
    pub id: IdSnapshot,
    /// Parent region identifier, if any.
    pub parent_id: Option<IdSnapshot>,
    /// Current region state.
    pub state: RegionStateSnapshot,
    /// Effective budget for the region.
    pub budget: BudgetSnapshot,
    /// Number of child regions.
    pub child_count: usize,
    /// Number of tasks owned by the region.
    pub task_count: usize,
    /// Optional human-friendly name.
    pub name: Option<String>,
}

impl RegionSnapshot {
    fn from_record(record: &RegionRecord) -> Self {
        let child_count = record.child_count();
        let task_count = record.task_count();
        Self {
            id: record.id.into(),
            parent_id: record.parent.map(IdSnapshot::from),
            state: RegionStateSnapshot::from(record.state()),
            budget: BudgetSnapshot::from(record.budget()),
            child_count,
            task_count,
            name: None,
        }
    }
}

/// Serializable region lifecycle state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RegionStateSnapshot {
    /// Region is open and accepting work.
    Open,
    /// Region has begun closing.
    Closing,
    /// Region is draining children.
    Draining,
    /// Region is running finalizers.
    Finalizing,
    /// Region is fully closed.
    Closed,
}

impl From<RegionState> for RegionStateSnapshot {
    fn from(state: RegionState) -> Self {
        match state {
            RegionState::Open => Self::Open,
            RegionState::Closing => Self::Closing,
            RegionState::Draining => Self::Draining,
            RegionState::Finalizing => Self::Finalizing,
            RegionState::Closed => Self::Closed,
        }
    }
}

/// Serializable task snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskSnapshot {
    /// Task identifier.
    pub id: IdSnapshot,
    /// Owning region identifier.
    pub region_id: IdSnapshot,
    /// Current task state.
    pub state: TaskStateSnapshot,
    /// Optional human-friendly name.
    pub name: Option<String>,
    /// Estimated poll count since creation.
    pub poll_count: u64,
    /// Task creation time in nanoseconds.
    pub created_at: u64,
    /// Obligations currently held by the task.
    pub obligations: Vec<IdSnapshot>,
}

impl TaskSnapshot {
    fn from_record(record: &TaskRecord, obligations: Vec<ObligationId>) -> Self {
        let poll_count = record
            .cx_inner
            .as_ref()
            .map(|inner| inner.read())
            .map(|inner| inner.budget_baseline.poll_quota)
            .map_or(0, |baseline| {
                u64::from(baseline.saturating_sub(record.polls_remaining))
            });

        let obligations = obligations.into_iter().map(IdSnapshot::from).collect();

        Self {
            id: record.id.into(),
            region_id: record.owner.into(),
            state: TaskStateSnapshot::from_state(&record.state),
            name: None,
            poll_count,
            created_at: record.created_at().as_nanos(),
            obligations,
        }
    }
}

/// Serializable task lifecycle state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TaskStateSnapshot {
    /// Task created but not yet running.
    Created,
    /// Task is running normally.
    Running,
    /// Cancellation requested.
    CancelRequested {
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Task acknowledged cancellation and is cleaning up.
    Cancelling {
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Task is running finalizers.
    Finalizing {
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Task completed with an outcome.
    Completed {
        /// Completion outcome.
        outcome: OutcomeSnapshot,
    },
}

impl TaskStateSnapshot {
    fn from_state(state: &TaskState) -> Self {
        match state {
            TaskState::Created => Self::Created,
            TaskState::Running => Self::Running,
            TaskState::CancelRequested { reason, .. } => Self::CancelRequested {
                reason: CancelReasonSnapshot::from(reason),
            },
            TaskState::Cancelling { reason, .. } => Self::Cancelling {
                reason: CancelReasonSnapshot::from(reason),
            },
            TaskState::Finalizing { reason, .. } => Self::Finalizing {
                reason: CancelReasonSnapshot::from(reason),
            },
            TaskState::Completed(outcome) => Self::Completed {
                outcome: OutcomeSnapshot::from_outcome(outcome),
            },
        }
    }
}

/// Serializable cancellation kind.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CancelKindSnapshot {
    /// Explicit user cancellation.
    User,
    /// Deadline or timeout cancellation.
    Timeout,
    /// Deadline budget exhaustion.
    Deadline,
    /// Poll quota exhaustion.
    PollQuota,
    /// Cost budget exhaustion.
    CostBudget,
    /// Fail-fast cancellation.
    FailFast,
    /// Race-loser cancellation.
    RaceLost,
    /// Parent region cancelled.
    ParentCancelled,
    /// Resource unavailability cancellation.
    ResourceUnavailable,
    /// Runtime shutdown cancellation.
    Shutdown,
    /// Linked task exit propagation (Spork).
    LinkedExit,
}

impl From<CancelKind> for CancelKindSnapshot {
    fn from(kind: CancelKind) -> Self {
        match kind {
            CancelKind::User => Self::User,
            CancelKind::Timeout => Self::Timeout,
            CancelKind::Deadline => Self::Deadline,
            CancelKind::PollQuota => Self::PollQuota,
            CancelKind::CostBudget => Self::CostBudget,
            CancelKind::FailFast => Self::FailFast,
            CancelKind::RaceLost => Self::RaceLost,
            CancelKind::ParentCancelled => Self::ParentCancelled,
            CancelKind::ResourceUnavailable => Self::ResourceUnavailable,
            CancelKind::Shutdown => Self::Shutdown,
            CancelKind::LinkedExit => Self::LinkedExit,
        }
    }
}

/// Serializable cancellation reason.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelReasonSnapshot {
    /// Cancellation kind.
    pub kind: CancelKindSnapshot,
    /// Originating region identifier.
    pub origin_region: IdSnapshot,
    /// Originating task identifier, if any.
    pub origin_task: Option<IdSnapshot>,
    /// Timestamp when cancellation was requested (nanoseconds).
    pub timestamp: u64,
    /// Optional static message.
    pub message: Option<String>,
    /// Optional parent cause.
    pub cause: Option<Box<Self>>,
}

impl From<&CancelReason> for CancelReasonSnapshot {
    fn from(reason: &CancelReason) -> Self {
        Self {
            kind: CancelKindSnapshot::from(reason.kind()),
            origin_region: reason.origin_region.into(),
            origin_task: reason.origin_task.map(IdSnapshot::from),
            timestamp: reason.timestamp.as_nanos(),
            message: reason.message.clone(),
            cause: reason
                .cause
                .as_deref()
                .map(|cause| Box::new(Self::from(cause))),
        }
    }
}

/// Serializable task outcome summary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OutcomeSnapshot {
    /// Task completed successfully.
    Ok,
    /// Task completed with an application error.
    Err {
        /// Optional error message.
        message: Option<String>,
    },
    /// Task completed due to cancellation.
    Cancelled {
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Task panicked.
    Panicked {
        /// Optional panic message.
        message: Option<String>,
    },
}

impl OutcomeSnapshot {
    fn from_outcome(outcome: &Outcome<(), crate::error::Error>) -> Self {
        match outcome {
            Outcome::Ok(()) => Self::Ok,
            Outcome::Err(err) => Self::Err {
                message: Some(err.to_string()),
            },
            Outcome::Cancelled(reason) => Self::Cancelled {
                reason: CancelReasonSnapshot::from(reason),
            },
            Outcome::Panicked(payload) => Self::Panicked {
                message: Some(payload.message().to_string()),
            },
        }
    }
}

/// Serializable down/exit reason.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DownReasonSnapshot {
    /// Process completed successfully.
    Normal,
    /// Process terminated with an application error.
    Error {
        /// Error message.
        message: String,
    },
    /// Process was cancelled.
    Cancelled {
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Process panicked.
    Panicked {
        /// Panic message.
        message: String,
    },
}

impl From<&crate::monitor::DownReason> for DownReasonSnapshot {
    fn from(reason: &crate::monitor::DownReason) -> Self {
        match reason {
            crate::monitor::DownReason::Normal => Self::Normal,
            crate::monitor::DownReason::Error(message) => Self::Error {
                message: message.clone(),
            },
            crate::monitor::DownReason::Cancelled(reason) => Self::Cancelled {
                reason: CancelReasonSnapshot::from(reason),
            },
            crate::monitor::DownReason::Panicked(payload) => Self::Panicked {
                message: payload.message().to_string(),
            },
        }
    }
}

/// Serializable obligation snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObligationSnapshot {
    /// Obligation identifier.
    pub id: IdSnapshot,
    /// Obligation kind.
    pub kind: ObligationKindSnapshot,
    /// Obligation state.
    pub state: ObligationStateSnapshot,
    /// Task holding the obligation.
    pub holder_task: IdSnapshot,
    /// Region owning the obligation.
    pub owning_region: IdSnapshot,
    /// Time when the obligation was created.
    pub created_at: u64,
}

impl ObligationSnapshot {
    fn from_record(record: &ObligationRecord) -> Self {
        Self {
            id: record.id.into(),
            kind: ObligationKindSnapshot::from(record.kind),
            state: ObligationStateSnapshot::from(record.state),
            holder_task: record.holder.into(),
            owning_region: record.region.into(),
            created_at: record.reserved_at.as_nanos(),
        }
    }
}

/// Serializable obligation kind.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ObligationKindSnapshot {
    /// Send permit.
    SendPermit,
    /// Acknowledgement.
    Ack,
    /// Lease.
    Lease,
    /// I/O operation.
    IoOp,
    /// Semaphore permit.
    SemaphorePermit,
}

impl From<ObligationKind> for ObligationKindSnapshot {
    fn from(kind: ObligationKind) -> Self {
        match kind {
            ObligationKind::SendPermit => Self::SendPermit,
            ObligationKind::Ack => Self::Ack,
            ObligationKind::Lease => Self::Lease,
            ObligationKind::IoOp => Self::IoOp,
            ObligationKind::SemaphorePermit => Self::SemaphorePermit,
        }
    }
}

/// Serializable obligation state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ObligationStateSnapshot {
    /// Reserved but not yet resolved.
    Reserved,
    /// Committed successfully.
    Committed,
    /// Aborted cleanly.
    Aborted,
    /// Leaked (error).
    Leaked,
}

impl From<ObligationState> for ObligationStateSnapshot {
    fn from(state: ObligationState) -> Self {
        match state {
            ObligationState::Reserved => Self::Reserved,
            ObligationState::Committed => Self::Committed,
            ObligationState::Aborted => Self::Aborted,
            ObligationState::Leaked => Self::Leaked,
        }
    }
}

/// Serializable obligation abort reason.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ObligationAbortReasonSnapshot {
    /// Aborted due to cancellation.
    Cancel,
    /// Aborted due to error.
    Error,
    /// Explicitly aborted.
    Explicit,
}

impl From<ObligationAbortReason> for ObligationAbortReasonSnapshot {
    fn from(reason: ObligationAbortReason) -> Self {
        match reason {
            ObligationAbortReason::Cancel => Self::Cancel,
            ObligationAbortReason::Error => Self::Error,
            ObligationAbortReason::Explicit => Self::Explicit,
        }
    }
}

/// Serializable trace event snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventSnapshot {
    /// Event schema version.
    pub version: u32,
    /// Sequence number.
    pub seq: u64,
    /// Event timestamp in nanoseconds.
    pub time: u64,
    /// Event kind.
    pub kind: EventKindSnapshot,
    /// Event data payload.
    pub data: EventDataSnapshot,
}

impl EventSnapshot {
    fn from_event(event: &TraceEvent) -> Self {
        Self {
            version: event.version,
            seq: event.seq,
            time: event.time.as_nanos(),
            kind: EventKindSnapshot::from(event.kind),
            data: EventDataSnapshot::from_trace_data(&event.data),
        }
    }
}

/// Serializable trace event kind.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventKindSnapshot {
    /// Task was spawned.
    Spawn,
    /// Task was scheduled.
    Schedule,
    /// Task yielded.
    Yield,
    /// Task was woken.
    Wake,
    /// Task was polled.
    Poll,
    /// Task completed.
    Complete,
    /// Cancellation requested.
    CancelRequest,
    /// Cancellation acknowledged.
    CancelAck,
    /// Worker-offload cancellation requested.
    WorkerCancelRequested,
    /// Worker-offload cancellation acknowledged.
    WorkerCancelAcknowledged,
    /// Worker-offload drain phase started.
    WorkerDrainStarted,
    /// Worker-offload drain phase completed.
    WorkerDrainCompleted,
    /// Worker-offload finalize phase completed.
    WorkerFinalizeCompleted,
    /// Region close started.
    RegionCloseBegin,
    /// Region close completed.
    RegionCloseComplete,
    /// Region created.
    RegionCreated,
    /// Region cancelled.
    RegionCancelled,
    /// Obligation reserved.
    ObligationReserve,
    /// Obligation committed.
    ObligationCommit,
    /// Obligation aborted.
    ObligationAbort,
    /// Obligation leaked.
    ObligationLeak,
    /// Time advanced.
    TimeAdvance,
    /// Timer scheduled.
    TimerScheduled,
    /// Timer fired.
    TimerFired,
    /// Timer cancelled.
    TimerCancelled,
    /// I/O interest requested.
    IoRequested,
    /// I/O ready.
    IoReady,
    /// I/O result.
    IoResult,
    /// I/O error.
    IoError,
    /// RNG seed.
    RngSeed,
    /// RNG value.
    RngValue,
    /// Replay checkpoint.
    Checkpoint,
    /// Futurelock detected.
    FuturelockDetected,
    /// Chaos injection occurred.
    ChaosInjection,
    /// User trace point.
    UserTrace,
    /// A monitor was established.
    MonitorCreated,
    /// A monitor was removed.
    MonitorDropped,
    /// A Down notification was delivered.
    DownDelivered,
    /// A link was established.
    LinkCreated,
    /// A link was removed.
    LinkDropped,
    /// An exit signal was delivered to a linked task.
    ExitDelivered,
}

impl From<TraceEventKind> for EventKindSnapshot {
    fn from(kind: TraceEventKind) -> Self {
        match kind {
            TraceEventKind::Spawn => Self::Spawn,
            TraceEventKind::Schedule => Self::Schedule,
            TraceEventKind::Yield => Self::Yield,
            TraceEventKind::Wake => Self::Wake,
            TraceEventKind::Poll => Self::Poll,
            TraceEventKind::Complete => Self::Complete,
            TraceEventKind::CancelRequest => Self::CancelRequest,
            TraceEventKind::CancelAck => Self::CancelAck,
            TraceEventKind::WorkerCancelRequested => Self::WorkerCancelRequested,
            TraceEventKind::WorkerCancelAcknowledged => Self::WorkerCancelAcknowledged,
            TraceEventKind::WorkerDrainStarted => Self::WorkerDrainStarted,
            TraceEventKind::WorkerDrainCompleted => Self::WorkerDrainCompleted,
            TraceEventKind::WorkerFinalizeCompleted => Self::WorkerFinalizeCompleted,
            TraceEventKind::RegionCloseBegin => Self::RegionCloseBegin,
            TraceEventKind::RegionCloseComplete => Self::RegionCloseComplete,
            TraceEventKind::RegionCreated => Self::RegionCreated,
            TraceEventKind::RegionCancelled => Self::RegionCancelled,
            TraceEventKind::ObligationReserve => Self::ObligationReserve,
            TraceEventKind::ObligationCommit => Self::ObligationCommit,
            TraceEventKind::ObligationAbort => Self::ObligationAbort,
            TraceEventKind::ObligationLeak => Self::ObligationLeak,
            TraceEventKind::TimeAdvance => Self::TimeAdvance,
            TraceEventKind::TimerScheduled => Self::TimerScheduled,
            TraceEventKind::TimerFired => Self::TimerFired,
            TraceEventKind::TimerCancelled => Self::TimerCancelled,
            TraceEventKind::IoRequested => Self::IoRequested,
            TraceEventKind::IoReady => Self::IoReady,
            TraceEventKind::IoResult => Self::IoResult,
            TraceEventKind::IoError => Self::IoError,
            TraceEventKind::RngSeed => Self::RngSeed,
            TraceEventKind::RngValue => Self::RngValue,
            TraceEventKind::Checkpoint => Self::Checkpoint,
            TraceEventKind::FuturelockDetected => Self::FuturelockDetected,
            TraceEventKind::ChaosInjection => Self::ChaosInjection,
            TraceEventKind::UserTrace => Self::UserTrace,
            TraceEventKind::MonitorCreated => Self::MonitorCreated,
            TraceEventKind::MonitorDropped => Self::MonitorDropped,
            TraceEventKind::DownDelivered => Self::DownDelivered,
            TraceEventKind::LinkCreated => Self::LinkCreated,
            TraceEventKind::LinkDropped => Self::LinkDropped,
            TraceEventKind::ExitDelivered => Self::ExitDelivered,
        }
    }
}

/// Serializable trace event payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventDataSnapshot {
    /// No additional data.
    None,
    /// Task-related event.
    Task {
        /// Task identifier.
        task: IdSnapshot,
        /// Region identifier.
        region: IdSnapshot,
    },
    /// Region-related event.
    Region {
        /// Region identifier.
        region: IdSnapshot,
        /// Parent region identifier.
        parent: Option<IdSnapshot>,
    },
    /// Obligation-related event.
    Obligation {
        /// Obligation identifier.
        obligation: IdSnapshot,
        /// Task holding the obligation.
        task: IdSnapshot,
        /// Owning region.
        region: IdSnapshot,
        /// Obligation kind.
        kind: ObligationKindSnapshot,
        /// Obligation state.
        state: ObligationStateSnapshot,
        /// Duration held in nanoseconds, if resolved.
        duration_ns: Option<u64>,
        /// Abort reason, if applicable.
        abort_reason: Option<ObligationAbortReasonSnapshot>,
    },
    /// Cancellation-related event.
    Cancel {
        /// Task identifier.
        task: IdSnapshot,
        /// Region identifier.
        region: IdSnapshot,
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Region cancellation event.
    RegionCancel {
        /// Region identifier.
        region: IdSnapshot,
        /// Cancellation reason.
        reason: CancelReasonSnapshot,
    },
    /// Time-related event.
    Time {
        /// Previous time in nanoseconds.
        old: u64,
        /// New time in nanoseconds.
        new: u64,
    },
    /// Timer event.
    Timer {
        /// Timer identifier.
        timer_id: u64,
        /// Deadline in nanoseconds, if applicable.
        deadline: Option<u64>,
    },
    /// I/O request event.
    IoRequested {
        /// I/O token.
        token: u64,
        /// Interest bitflags.
        interest: u8,
    },
    /// I/O ready event.
    IoReady {
        /// I/O token.
        token: u64,
        /// Readiness bitflags.
        readiness: u8,
    },
    /// I/O result event.
    IoResult {
        /// I/O token.
        token: u64,
        /// Bytes transferred.
        bytes: i64,
    },
    /// I/O error event.
    IoError {
        /// I/O token.
        token: u64,
        /// Error kind.
        kind: u8,
    },
    /// RNG seed event.
    RngSeed {
        /// Seed value.
        seed: u64,
    },
    /// RNG value event.
    RngValue {
        /// Generated value.
        value: u64,
    },
    /// Checkpoint event.
    Checkpoint {
        /// Monotonic sequence number.
        sequence: u64,
        /// Active task count.
        active_tasks: u32,
        /// Active region count.
        active_regions: u32,
    },
    /// Futurelock event data.
    Futurelock {
        /// Task identifier.
        task: IdSnapshot,
        /// Region identifier.
        region: IdSnapshot,
        /// Idle steps since last poll.
        idle_steps: u64,
        /// Obligations held at detection time.
        held: Vec<HeldObligationSnapshot>,
    },
    /// Monitor lifecycle event.
    Monitor {
        /// Monitor reference id.
        monitor_ref: u64,
        /// Watcher task id.
        watcher: IdSnapshot,
        /// Watcher region id.
        watcher_region: IdSnapshot,
        /// Monitored task id.
        monitored: IdSnapshot,
    },
    /// Down notification delivery.
    Down {
        /// Monitor reference id.
        monitor_ref: u64,
        /// Watcher task id.
        watcher: IdSnapshot,
        /// Monitored task id.
        monitored: IdSnapshot,
        /// Completion virtual time (nanoseconds).
        completion_vt: u64,
        /// Reason for termination.
        reason: DownReasonSnapshot,
    },
    /// Link lifecycle event.
    Link {
        /// Link reference id.
        link_ref: u64,
        /// One side task id.
        task_a: IdSnapshot,
        /// One side region id.
        region_a: IdSnapshot,
        /// Other side task id.
        task_b: IdSnapshot,
        /// Other side region id.
        region_b: IdSnapshot,
    },
    /// Exit signal delivery.
    Exit {
        /// Link reference id.
        link_ref: u64,
        /// Source task id.
        from: IdSnapshot,
        /// Target task id.
        to: IdSnapshot,
        /// Failure virtual time (nanoseconds).
        failure_vt: u64,
        /// Reason for termination.
        reason: DownReasonSnapshot,
    },
    /// User-defined message.
    Message(String),
    /// Chaos injection details.
    Chaos {
        /// Chaos kind.
        kind: String,
        /// Optional task identifier.
        task: Option<IdSnapshot>,
        /// Additional detail.
        detail: String,
    },
    /// Worker-offload lifecycle data.
    Worker {
        /// Worker runtime instance identifier.
        worker_id: String,
        /// Offloaded job identifier.
        job_id: u64,
        /// Deterministic decision sequence carried by the worker envelope.
        decision_seq: u64,
        /// Stable replay digest carried by the worker envelope.
        replay_hash: u64,
        /// Originating task identifier.
        task: IdSnapshot,
        /// Originating region identifier.
        region: IdSnapshot,
        /// Originating obligation identifier.
        obligation: IdSnapshot,
    },
}

impl EventDataSnapshot {
    #[allow(clippy::too_many_lines)]
    fn from_trace_data(data: &TraceData) -> Self {
        match data {
            TraceData::None => Self::None,
            TraceData::Task { task, region } => Self::Task {
                task: (*task).into(),
                region: (*region).into(),
            },
            TraceData::Region { region, parent } => Self::Region {
                region: (*region).into(),
                parent: parent.map(IdSnapshot::from),
            },
            TraceData::Obligation {
                obligation,
                task,
                region,
                kind,
                state,
                duration_ns,
                abort_reason,
            } => Self::Obligation {
                obligation: (*obligation).into(),
                task: (*task).into(),
                region: (*region).into(),
                kind: ObligationKindSnapshot::from(*kind),
                state: ObligationStateSnapshot::from(*state),
                duration_ns: *duration_ns,
                abort_reason: abort_reason.map(ObligationAbortReasonSnapshot::from),
            },
            TraceData::Cancel {
                task,
                region,
                reason,
            } => Self::Cancel {
                task: (*task).into(),
                region: (*region).into(),
                reason: CancelReasonSnapshot::from(reason),
            },
            TraceData::RegionCancel { region, reason } => Self::RegionCancel {
                region: (*region).into(),
                reason: CancelReasonSnapshot::from(reason),
            },
            TraceData::Time { old, new } => Self::Time {
                old: old.as_nanos(),
                new: new.as_nanos(),
            },
            TraceData::Timer { timer_id, deadline } => Self::Timer {
                timer_id: *timer_id,
                deadline: deadline.map(Time::as_nanos),
            },
            TraceData::IoRequested { token, interest } => Self::IoRequested {
                token: *token,
                interest: *interest,
            },
            TraceData::IoReady { token, readiness } => Self::IoReady {
                token: *token,
                readiness: *readiness,
            },
            TraceData::IoResult { token, bytes } => Self::IoResult {
                token: *token,
                bytes: *bytes,
            },
            TraceData::IoError { token, kind } => Self::IoError {
                token: *token,
                kind: *kind,
            },
            TraceData::RngSeed { seed } => Self::RngSeed { seed: *seed },
            TraceData::RngValue { value } => Self::RngValue { value: *value },
            TraceData::Checkpoint {
                sequence,
                active_tasks,
                active_regions,
            } => Self::Checkpoint {
                sequence: *sequence,
                active_tasks: *active_tasks,
                active_regions: *active_regions,
            },
            TraceData::Futurelock {
                task,
                region,
                idle_steps,
                held,
            } => Self::Futurelock {
                task: (*task).into(),
                region: (*region).into(),
                idle_steps: *idle_steps,
                held: held
                    .iter()
                    .map(|(obligation, kind)| HeldObligationSnapshot {
                        obligation: (*obligation).into(),
                        kind: ObligationKindSnapshot::from(*kind),
                    })
                    .collect(),
            },
            TraceData::Monitor {
                monitor_ref,
                watcher,
                watcher_region,
                monitored,
            } => Self::Monitor {
                monitor_ref: *monitor_ref,
                watcher: (*watcher).into(),
                watcher_region: (*watcher_region).into(),
                monitored: (*monitored).into(),
            },
            TraceData::Down {
                monitor_ref,
                watcher,
                monitored,
                completion_vt,
                reason,
            } => Self::Down {
                monitor_ref: *monitor_ref,
                watcher: (*watcher).into(),
                monitored: (*monitored).into(),
                completion_vt: completion_vt.as_nanos(),
                reason: DownReasonSnapshot::from(reason),
            },
            TraceData::Link {
                link_ref,
                task_a,
                region_a,
                task_b,
                region_b,
            } => Self::Link {
                link_ref: *link_ref,
                task_a: (*task_a).into(),
                region_a: (*region_a).into(),
                task_b: (*task_b).into(),
                region_b: (*region_b).into(),
            },
            TraceData::Exit {
                link_ref,
                from,
                to,
                failure_vt,
                reason,
            } => Self::Exit {
                link_ref: *link_ref,
                from: (*from).into(),
                to: (*to).into(),
                failure_vt: failure_vt.as_nanos(),
                reason: DownReasonSnapshot::from(reason),
            },
            TraceData::Message(message) => Self::Message(message.clone()),
            TraceData::Chaos { kind, task, detail } => Self::Chaos {
                kind: kind.clone(),
                task: task.map(IdSnapshot::from),
                detail: detail.clone(),
            },
            TraceData::Worker {
                worker_id,
                job_id,
                decision_seq,
                replay_hash,
                task,
                region,
                obligation,
            } => Self::Worker {
                worker_id: worker_id.clone(),
                job_id: *job_id,
                decision_seq: *decision_seq,
                replay_hash: *replay_hash,
                task: (*task).into(),
                region: (*region).into(),
                obligation: (*obligation).into(),
            },
        }
    }
}

/// Serializable representation of a held obligation at futurelock detection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeldObligationSnapshot {
    /// Obligation identifier.
    pub obligation: IdSnapshot,
    /// Obligation kind.
    pub kind: ObligationKindSnapshot,
}

#[cfg(test)]
#[allow(clippy::too_many_lines)]
mod tests {
    use super::*;
    use crate::observability::{LogEntry, ObservabilityConfig};
    use crate::record::task::TaskState;
    use crate::record::{ObligationKind, ObligationRecord, RegionLimits};
    use crate::runtime::ModuleId;
    use crate::runtime::reactor::LabReactor;
    use crate::test_utils::init_test_logging;
    use crate::time::{TimerDriverHandle, VirtualClock};
    use crate::trace::event::TRACE_EVENT_SCHEMA_VERSION;
    use crate::types::{CancelAttributionConfig, CancelKind};
    use crate::util::ArenaIndex;
    use parking_lot::Mutex;
    use serde_json::{Value, json};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::task::{Context, Poll, Waker};

    #[derive(Default)]
    struct TestMetrics {
        cancellations: AtomicUsize,
        completions: Mutex<Vec<OutcomeKind>>,
        spawns: AtomicUsize,
    }

    impl MetricsProvider for TestMetrics {
        fn task_spawned(&self, _: RegionId, _: TaskId) {
            self.spawns.fetch_add(1, Ordering::Relaxed);
        }

        fn task_completed(&self, _: TaskId, outcome: OutcomeKind, _: Duration) {
            self.completions.lock().push(outcome);
        }

        fn region_created(&self, _: RegionId, _: Option<RegionId>) {}

        fn region_closed(&self, _: RegionId, _: Duration) {}

        fn cancellation_requested(&self, _: RegionId, _: CancelKind) {
            self.cancellations.fetch_add(1, Ordering::Relaxed);
        }

        fn drain_completed(&self, _: RegionId, _: Duration) {}

        fn deadline_set(&self, _: RegionId, _: Duration) {}

        fn deadline_exceeded(&self, _: RegionId) {}

        fn deadline_warning(&self, _: &str, _: &'static str, _: Duration) {}

        fn deadline_violation(&self, _: &str, _: Duration) {}

        fn deadline_remaining(&self, _: &str, _: Duration) {}

        fn checkpoint_interval(&self, _: &str, _: Duration) {}

        fn task_stuck_detected(&self, _: &str) {}

        fn obligation_created(&self, _: RegionId) {}

        fn obligation_discharged(&self, _: RegionId) {}

        fn obligation_leaked(&self, _: RegionId) {}

        fn scheduler_tick(&self, _: usize, _: Duration) {}
    }

    struct TestWaker(AtomicBool);

    use std::task::Wake;
    impl Wake for TestWaker {
        fn wake(self: Arc<Self>) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    fn scrub_runtime_snapshot_for_snapshot_test(value: Value) -> Value {
        match value {
            Value::Object(map) => {
                if map.len() == 2
                    && map.get("index").is_some_and(Value::is_number)
                    && map.get("generation").is_some_and(Value::is_number)
                {
                    return Value::String("[id]".to_string());
                }

                Value::Object(
                    map.into_iter()
                        .map(|(key, value)| {
                            let scrubbed = match key.as_str() {
                                "timestamp" if value.is_number() => {
                                    Value::String("[timestamp]".to_string())
                                }
                                "created_at" if value.is_number() => {
                                    Value::String("[created_at]".to_string())
                                }
                                "time" if value.is_number() => {
                                    Value::String("[event_time]".to_string())
                                }
                                "deadline" if value.is_number() => {
                                    Value::String("[deadline]".to_string())
                                }
                                _ => scrub_runtime_snapshot_for_snapshot_test(value),
                            };
                            (key, scrubbed)
                        })
                        .collect(),
                )
            }
            Value::Array(items) => Value::Array(
                items
                    .into_iter()
                    .map(scrub_runtime_snapshot_for_snapshot_test)
                    .collect(),
            ),
            other => other,
        }
    }

    fn label_region_for_snapshot(
        region: RegionId,
        labels: &[(RegionId, &'static str)],
    ) -> &'static str {
        labels
            .iter()
            .find_map(|(id, label)| (*id == region).then_some(*label))
            .unwrap_or("[region]")
    }

    fn scrub_cancel_reason_chain_for_snapshot(
        reason: &CancelReason,
        labels: &[(RegionId, &'static str)],
    ) -> Value {
        json!({
            "kind": reason.kind.as_str(),
            "message": reason.message.clone(),
            "origin_region": label_region_for_snapshot(reason.origin_region, labels),
            "timestamp": "[timestamp]",
            "chain_depth": reason.chain_depth(),
            "root_cause_kind": reason.root_cause().kind.as_str(),
            "root_cause_message": reason.root_cause().message.clone(),
            "truncated": reason.is_truncated(),
            "truncated_at_depth": reason.truncated_at_depth(),
            "any_truncated": reason.any_truncated(),
            "chain": reason
                .chain()
                .enumerate()
                .map(|(level, entry)| {
                    json!({
                        "level": level,
                        "kind": entry.kind.as_str(),
                        "message": entry.message.clone(),
                        "origin_region": label_region_for_snapshot(entry.origin_region, labels),
                        "timestamp": "[timestamp]",
                        "truncated": entry.is_truncated(),
                        "truncated_at_depth": entry.truncated_at_depth(),
                    })
                })
                .collect::<Vec<_>>(),
        })
    }

    fn nested_region_cancel_cause_chain_dump(max_chain_depth: usize) -> Value {
        let mut state = RuntimeState::new();
        state.set_cancel_attribution_config(CancelAttributionConfig::new(
            max_chain_depth,
            CancelAttributionConfig::DEFAULT_MAX_MEMORY,
        ));

        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let grandchild = create_child_region(&mut state, child);
        let leaf = create_child_region(&mut state, grandchild);
        let _ = insert_task(&mut state, root);
        let _ = insert_task(&mut state, child);
        let _ = insert_task(&mut state, grandchild);
        let _ = insert_task(&mut state, leaf);
        let labels = [
            (root, "root"),
            (child, "child"),
            (grandchild, "grandchild"),
            (leaf, "leaf"),
        ];

        let reason = CancelReason::deadline()
            .with_message("budget exhausted")
            .with_timestamp(Time::from_millis(42));
        let _ = state.cancel_request(root, &reason, None);

        json!({
            "config": {
                "max_chain_depth": max_chain_depth,
                "max_chain_memory": CancelAttributionConfig::DEFAULT_MAX_MEMORY,
            },
            "regions": {
                "root": scrub_cancel_reason_chain_for_snapshot(
                    state
                        .regions
                        .get(root.arena_index())
                        .expect("root missing")
                        .cancel_reason()
                        .as_ref()
                        .expect("root cancel reason missing"),
                    &labels,
                ),
                "child": scrub_cancel_reason_chain_for_snapshot(
                    state
                        .regions
                        .get(child.arena_index())
                        .expect("child missing")
                        .cancel_reason()
                        .as_ref()
                        .expect("child cancel reason missing"),
                    &labels,
                ),
                "grandchild": scrub_cancel_reason_chain_for_snapshot(
                    state
                        .regions
                        .get(grandchild.arena_index())
                        .expect("grandchild missing")
                        .cancel_reason()
                        .as_ref()
                        .expect("grandchild cancel reason missing"),
                    &labels,
                ),
                "leaf": scrub_cancel_reason_chain_for_snapshot(
                    state
                        .regions
                        .get(leaf.arena_index())
                        .expect("leaf missing")
                        .cancel_reason()
                        .as_ref()
                        .expect("leaf cancel reason missing"),
                    &labels,
                ),
            },
        })
    }

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

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

        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let _child = state
            .create_child_region(root, Budget::INFINITE)
            .expect("create child region");
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let obligation_id = state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");
        let _ = state
            .commit_obligation(obligation_id)
            .expect("commit obligation");

        let stats = state.epoch_tracker.transition_statistics();
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(3) && s.transition_count == 3),
            "region-table transitions advance monotonically instead of replaying genesis",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(3) && s.transition_count == 3)
        );
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::TaskTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(1) && s.transition_count == 1),
            "task-table transitions advance monotonically",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::TaskTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(1) && s.transition_count == 1)
        );
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::ObligationTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2) && s.transition_count == 2),
            "obligation-table transitions advance monotonically",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::ObligationTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2) && s.transition_count == 2)
        );

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

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

        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");

        state
            .task_mut(task_id)
            .expect("task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task_id);

        let stats = state.epoch_tracker.transition_statistics();
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::TaskTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2) && s.transition_count == 2),
            "task-table epoch should advance for both task creation and cleanup",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::TaskTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2) && s.transition_count == 2)
        );

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

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

        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_millis(42)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock));

        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let obligation_id = state
            .create_obligation(ObligationKind::SendPermit, task_id, root, None)
            .expect("create obligation");

        let region = state.region(root).expect("root region");
        crate::assert_with_log!(
            region.created_at() == Time::from_millis(42),
            "root region uses timer-driver time",
            Time::from_millis(42),
            region.created_at()
        );

        let task = state.task(task_id).expect("task");
        crate::assert_with_log!(
            task.created_at() == Time::from_millis(42),
            "task uses timer-driver time",
            Time::from_millis(42),
            task.created_at()
        );

        let obligation = state.obligation(obligation_id).expect("obligation");
        crate::assert_with_log!(
            obligation.reserved_at == Time::from_millis(42),
            "obligation uses timer-driver time",
            Time::from_millis(42),
            obligation.reserved_at
        );

        let snapshot = state.snapshot();
        crate::assert_with_log!(
            snapshot.timestamp == Time::from_millis(42).as_nanos(),
            "snapshot timestamp uses timer-driver time",
            Time::from_millis(42).as_nanos(),
            snapshot.timestamp
        );

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

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

        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_millis(7)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock.clone()));

        let root = state.create_root_region(Budget::INFINITE);
        let stats = state.epoch_tracker.transition_statistics();
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.last_transition_time == Time::from_millis(7)),
            "region epoch transition uses initial timer-driver time",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.last_transition_time == Time::from_millis(7))
        );

        clock.advance(Time::from_millis(5).as_nanos());
        let _child = state
            .create_child_region(root, Budget::INFINITE)
            .expect("create child region");

        let stats = state.epoch_tracker.transition_statistics();
        crate::assert_with_log!(
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2)
                    && s.last_transition_time == Time::from_millis(12)),
            "region epoch transition tracks later timer-driver advances",
            true,
            stats
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .is_some_and(|s| s.current_epoch == EpochId::new(2)
                    && s.last_transition_time == Time::from_millis(12))
        );

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

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

        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_millis(7)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock.clone()));

        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");

        clock.advance(Time::from_millis(5).as_nanos());
        let expected_time = Time::from_millis(12);
        let _ = state.cancel_request(root, &CancelReason::timeout(), None);

        let events = state.trace.snapshot();
        let cancel_event = events
            .iter()
            .find(|event| {
                event.kind == TraceEventKind::CancelRequest
                    && matches!(
                        event.data,
                        TraceData::Cancel { task, region, .. }
                            if task == task_id && region == root
                    )
            })
            .expect("cancel request event");
        crate::assert_with_log!(
            cancel_event.time == expected_time,
            "cancel request trace uses timer-driver time",
            expected_time,
            cancel_event.time
        );

        let region_cancel_event = events
            .iter()
            .find(|event| {
                event.kind == TraceEventKind::RegionCancelled
                    && matches!(
                        event.data,
                        TraceData::RegionCancel { region, .. } if region == root
                    )
            })
            .expect("region cancelled event");
        crate::assert_with_log!(
            region_cancel_event.time == expected_time,
            "region cancelled trace uses timer-driver time",
            expected_time,
            region_cancel_event.time
        );

        let region_close_begin = events
            .iter()
            .find(|event| {
                event.kind == TraceEventKind::RegionCloseBegin
                    && matches!(
                        event.data,
                        TraceData::Region {
                            region,
                            parent: None,
                        } if region == root
                    )
            })
            .expect("region close begin event");
        crate::assert_with_log!(
            region_close_begin.time == expected_time,
            "region close begin trace uses timer-driver time",
            expected_time,
            region_close_begin.time
        );

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

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

        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_nanos(100)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock.clone()));

        let region = state.create_root_region(Budget::INFINITE);
        let registered = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(registered, "registered", true, registered);

        let region_record = state
            .regions
            .get_mut(region.arena_index())
            .expect("region missing");
        region_record.begin_close(None);
        region_record.begin_finalize();
        state.finalizing_regions.push(region);

        clock.advance(23);
        let scheduled = state.drain_ready_async_finalizers();
        crate::assert_with_log!(
            scheduled.len() == 1,
            "scheduled len",
            1usize,
            scheduled.len()
        );
        let task_id = scheduled[0].0;
        let expected_deadline =
            Time::from_nanos(123).saturating_add_nanos(FINALIZER_TIME_BUDGET_NANOS);
        let finalizer_deadline = state
            .task(task_id)
            .expect("async finalizer task missing")
            .cx_inner
            .as_ref()
            .expect("async finalizer cx missing")
            .read()
            .budget
            .deadline
            .expect("async finalizer deadline");
        crate::assert_with_log!(
            finalizer_deadline == expected_deadline,
            "async finalizer deadline uses timer-driver time",
            expected_deadline,
            finalizer_deadline
        );

        state
            .task_mut(task_id)
            .expect("async finalizer task missing")
            .complete(Outcome::Ok(()));
        clock.advance(14);
        let _ = state.task_completed(task_id);

        crate::assert_with_log!(
            state.finalizer_history()
                == [
                    FinalizerHistoryEvent::Registered {
                        id: 0,
                        region,
                        time: Time::from_nanos(100),
                    },
                    FinalizerHistoryEvent::Ran {
                        id: 0,
                        time: Time::from_nanos(137),
                    },
                    FinalizerHistoryEvent::RegionClosed {
                        region,
                        time: Time::from_nanos(137),
                    },
                ],
            "async finalizer history uses timer-driver time",
            "registered@100, ran@137, closed@137",
            format!("{:?}", state.finalizer_history())
        );

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

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

        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let before = state.epoch_tracker.transition_statistics();

        state.advance_region_state(root);

        let after = state.epoch_tracker.transition_statistics();
        crate::assert_with_log!(
            before
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .map(|s| (s.current_epoch, s.transition_count))
                == after
                    .per_module_stats
                    .get(&ModuleId::RegionTable)
                    .map(|s| (s.current_epoch, s.transition_count)),
            "no-op region scan must not fabricate epoch transitions",
            before
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .map(|s| (s.current_epoch, s.transition_count)),
            after
                .per_module_stats
                .get(&ModuleId::RegionTable)
                .map(|s| (s.current_epoch, s.transition_count))
        );

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

    fn insert_task(state: &mut RuntimeState, region: RegionId) -> TaskId {
        let idx = state.insert_task(TaskRecord::new(
            TaskId::from_arena(ArenaIndex::new(0, 0)),
            region,
            Budget::INFINITE,
        ));
        let id = TaskId::from_arena(idx);
        state.task_mut(id).expect("task missing").id = id;
        let added = state
            .regions
            .get_mut(region.arena_index())
            .expect("region missing")
            .add_task(id);
        crate::assert_with_log!(added.is_ok(), "task added to region", true, added.is_ok());
        id
    }

    #[test]
    fn cx_trace_emits_user_trace_event() {
        init_test("cx_trace_emits_user_trace_event");
        let metrics = Arc::new(TestMetrics::default());
        let mut state = RuntimeState::new_with_metrics(metrics);
        let root = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");
        let cx = state
            .task(task_id)
            .and_then(|record| record.cx.clone())
            .expect("cx missing");

        cx.trace("user trace");

        let saw_user_trace = state
            .trace
            .snapshot()
            .iter()
            .any(|event| event.kind == TraceEventKind::UserTrace);
        crate::assert_with_log!(saw_user_trace, "user trace recorded", true, saw_user_trace);
        crate::test_complete!("cx_trace_emits_user_trace_event");
    }

    #[test]
    fn cx_log_attaches_collector_and_timestamp() {
        init_test("cx_log_attaches_collector_and_timestamp");
        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_millis(5)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock));
        state.set_observability_config(ObservabilityConfig::testing().with_max_log_entries(8));
        let root = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");
        let cx = state
            .task(task_id)
            .and_then(|record| record.cx.clone())
            .expect("cx missing");

        cx.log(LogEntry::info("hello"));

        let collector = cx.log_collector().expect("collector missing");
        let entries = collector.peek();
        crate::assert_with_log!(entries.len() == 1, "log entry count", 1, entries.len());
        let entry = &entries[0];
        crate::assert_with_log!(
            entry.message() == "hello",
            "log entry message",
            "hello",
            entry.message()
        );
        crate::assert_with_log!(
            entry.timestamp() == Time::from_millis(5),
            "log entry timestamp",
            Time::from_millis(5),
            entry.timestamp()
        );
        let task_str = task_id.to_string();
        let region_str = root.to_string();
        crate::assert_with_log!(
            entry.get_field("task_id") == Some(task_str.as_str()),
            "log entry task id",
            task_str.as_str(),
            entry.get_field("task_id")
        );
        crate::assert_with_log!(
            entry.get_field("region_id") == Some(region_str.as_str()),
            "log entry region id",
            region_str.as_str(),
            entry.get_field("region_id")
        );
        crate::test_complete!("cx_log_attaches_collector_and_timestamp");
    }

    #[test]
    fn cx_log_respects_timestamp_toggle() {
        init_test("cx_log_respects_timestamp_toggle");
        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_millis(9)));
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(clock));
        let config = ObservabilityConfig::testing().with_include_timestamps(false);
        state.set_observability_config(config);
        let root = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");
        let cx = state
            .task(task_id)
            .and_then(|record| record.cx.clone())
            .expect("cx missing");

        cx.log(LogEntry::info("no timestamps"));

        let collector = cx.log_collector().expect("collector missing");
        let entries = collector.peek();
        crate::assert_with_log!(entries.len() == 1, "log entry count", 1, entries.len());
        let entry = &entries[0];
        crate::assert_with_log!(
            entry.timestamp() == Time::ZERO,
            "timestamps disabled",
            Time::ZERO,
            entry.timestamp()
        );
        crate::test_complete!("cx_log_respects_timestamp_toggle");
    }

    #[test]
    fn cancel_request_emits_trace_and_metrics() {
        init_test("cancel_request_emits_trace_and_metrics");
        let metrics = Arc::new(TestMetrics::default());
        let mut state = RuntimeState::new_with_metrics(metrics.clone());
        let root = state.create_root_region(Budget::INFINITE);

        let _ = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");
        let reason = CancelReason::timeout();
        let _ = state.cancel_request(root, &reason, None);

        let events = state.trace.snapshot();
        let saw_cancel = events
            .iter()
            .any(|event| event.kind == TraceEventKind::CancelRequest);
        crate::assert_with_log!(saw_cancel, "cancel trace recorded", true, saw_cancel);

        let cancellations = metrics.cancellations.load(Ordering::Relaxed);
        crate::assert_with_log!(
            cancellations == 1,
            "cancellation metrics",
            1usize,
            cancellations
        );
        crate::test_complete!("cancel_request_emits_trace_and_metrics");
    }

    #[test]
    fn spawn_trace_attaches_logical_time() {
        init_test("spawn_trace_attaches_logical_time");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);

        let _ = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");

        let events = state.trace.snapshot();
        let spawn_event = events
            .iter()
            .find(|event| event.kind == TraceEventKind::Spawn)
            .expect("spawn event");
        crate::assert_with_log!(
            spawn_event.logical_time.is_some(),
            "spawn logical time present",
            true,
            spawn_event.logical_time.is_some()
        );
        crate::test_complete!("spawn_trace_attaches_logical_time");
    }

    #[test]
    fn cancellation_outcome_metric_emitted() {
        init_test("cancellation_outcome_metric_emitted");
        let metrics = Arc::new(TestMetrics::default());
        let mut state = RuntimeState::new_with_metrics(metrics.clone());
        let root = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async { 1_u8 })
            .expect("task spawn");

        if let Some(record) = state.task_mut(task_id) {
            record.complete(Outcome::Cancelled(CancelReason::timeout()));
        }
        let _ = state.task_completed(task_id);

        let saw_cancelled = metrics.completions.lock().contains(&OutcomeKind::Cancelled);
        crate::assert_with_log!(
            saw_cancelled,
            "cancelled outcome metric",
            true,
            saw_cancelled
        );
        crate::test_complete!("cancellation_outcome_metric_emitted");
    }

    #[test]
    fn create_task_panic_reaches_join_handle() {
        init_test("create_task_panic_reaches_join_handle");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, mut handle) = state
            .create_task(root, Budget::INFINITE, async {
                panic!("state task boom");
                #[allow(unreachable_code)]
                1_u8
            })
            .expect("task create");

        let waker = Waker::from(Arc::new(TestWaker(AtomicBool::new(false))));
        let mut poll_cx = Context::from_waker(&waker);
        let stored = state.get_stored_future(task_id).expect("stored task");
        match stored.poll(&mut poll_cx) {
            Poll::Ready(Outcome::Panicked(payload)) => {
                crate::assert_with_log!(
                    payload.message() == "state task boom",
                    "panic payload captured on stored task",
                    "state task boom",
                    payload.message()
                );
            }
            other => panic!("panicking task must complete with Outcome::Panicked: {other:?}"),
        }

        let task_cx = state
            .task(task_id)
            .and_then(|record| record.cx.clone())
            .expect("task cx");
        let mut join_fut = std::pin::pin!(handle.join(&task_cx));
        match join_fut.as_mut().poll(&mut poll_cx) {
            Poll::Ready(Err(crate::runtime::task_handle::JoinError::Panicked(payload))) => {
                crate::assert_with_log!(
                    payload.message() == "state task boom",
                    "join handle receives panic payload",
                    "state task boom",
                    payload.message()
                );
            }
            other => {
                panic!("join of panicked state task must return JoinError::Panicked: {other:?}")
            }
        }

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

    #[test]
    fn snapshot_captures_entities() {
        init_test("snapshot_captures_entities");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(region, Budget::INFINITE, async { 42 })
            .expect("task create");

        let obl_idx = state.obligations.insert(ObligationRecord::new(
            ObligationId::from_arena(ArenaIndex::new(0, 0)),
            ObligationKind::SendPermit,
            task_id,
            region,
            state.now,
        ));
        let obl_id = ObligationId::from_arena(obl_idx);
        state
            .obligations
            .get_mut(obl_idx)
            .expect("obligation missing")
            .id = obl_id;

        let snapshot = state.snapshot();
        crate::assert_with_log!(
            snapshot.regions.len() == 1,
            "region count",
            1,
            snapshot.regions.len()
        );
        crate::assert_with_log!(
            snapshot.tasks.len() == 1,
            "task count",
            1,
            snapshot.tasks.len()
        );
        crate::assert_with_log!(
            snapshot.obligations.len() == 1,
            "obligation count",
            1,
            snapshot.obligations.len()
        );

        let task_snapshot = snapshot
            .tasks
            .iter()
            .find(|t| t.id == IdSnapshot::from(task_id))
            .expect("task snapshot missing");
        let has_obligation = task_snapshot
            .obligations
            .contains(&IdSnapshot::from(obl_id));
        crate::assert_with_log!(has_obligation, "task has obligation", true, has_obligation);
        crate::test_complete!("snapshot_captures_entities");
    }

    #[test]
    fn snapshot_preserves_event_version() {
        init_test("snapshot_preserves_event_version");
        let state = RuntimeState::new();
        let event = TraceEvent::new(1, Time::ZERO, TraceEventKind::UserTrace, TraceData::None);
        state.trace.push_event(event);

        let snapshot = state.snapshot();
        let event_snapshot = snapshot
            .recent_events
            .first()
            .expect("event snapshot missing");
        crate::assert_with_log!(
            event_snapshot.version == TRACE_EVENT_SCHEMA_VERSION,
            "event version",
            TRACE_EVENT_SCHEMA_VERSION,
            event_snapshot.version
        );
        crate::test_complete!("snapshot_preserves_event_version");
    }

    #[test]
    fn snapshot_json_scrubs_ids_and_timestamps() {
        init_test("snapshot_json_scrubs_ids_and_timestamps");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let (task_id, _handle) = state
            .create_task(region, Budget::INFINITE, async { 42 })
            .expect("task create");

        let obligation_idx = state.obligations.insert(ObligationRecord::new(
            ObligationId::from_arena(ArenaIndex::new(0, 0)),
            ObligationKind::SendPermit,
            task_id,
            region,
            state.now,
        ));
        let obligation_id = ObligationId::from_arena(obligation_idx);
        state
            .obligations
            .get_mut(obligation_idx)
            .expect("obligation missing")
            .id = obligation_id;

        state.trace.push_event(TraceEvent::new(
            99,
            Time::from_millis(42),
            TraceEventKind::UserTrace,
            TraceData::None,
        ));

        let snapshot = state.snapshot();

        insta::assert_json_snapshot!(
            "runtime_snapshot_entities_scrubbed",
            scrub_runtime_snapshot_for_snapshot_test(serde_json::to_value(&snapshot).unwrap())
        );
        crate::test_complete!("snapshot_json_scrubs_ids_and_timestamps");
    }

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

        insta::assert_json_snapshot!(
            "region_cancel_cause_chain_dump_scrubbed",
            json!({
                "full_chain": nested_region_cancel_cause_chain_dump(
                    CancelAttributionConfig::DEFAULT_MAX_DEPTH,
                ),
                "depth_limited_chain": nested_region_cancel_cause_chain_dump(3),
            })
        );

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

    #[test]
    fn can_region_complete_close_checks_running_finalizer_tasks() {
        init_test("can_region_complete_close_checks_running_finalizer_tasks");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Manually transition to Finalizing (simulating finalizer execution)
        let region_record = state.regions.get_mut(region.arena_index()).expect("region");
        region_record.begin_close(None);
        region_record.begin_finalize();

        // Add a running task (representing an async finalizer)
        let task = insert_task(&mut state, region);
        state.task_mut(task).expect("task").start_running();

        // Should NOT be able to close because a task is running
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(
            !can_close,
            "cannot close with running task",
            false,
            can_close
        );

        // Complete the task
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));

        // Under the new strict quiescence checks, a terminal task must be removed from
        // the region (which happens naturally in `task_completed` cleanup) before the
        // region is allowed to close.
        let region_record = state.regions.get(region.arena_index()).expect("region");
        region_record.remove_task(task);

        // Now should be able to close
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(can_close, "can close after task completes", true, can_close);
        crate::test_complete!("can_region_complete_close_checks_running_finalizer_tasks");
    }

    #[test]
    fn empty_state_is_quiescent() {
        init_test("empty_state_is_quiescent");
        let state = RuntimeState::new();
        let quiescent = state.is_quiescent();
        crate::assert_with_log!(quiescent, "state quiescent", true, quiescent);
        crate::test_complete!("empty_state_is_quiescent");
    }

    #[test]
    fn create_root_region() {
        init_test("create_root_region");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        crate::assert_with_log!(
            state.root_region.is_some(),
            "root region set",
            true,
            state.root_region.is_some()
        );
        crate::assert_with_log!(
            state.root_region == Some(root),
            "root id matches",
            Some(root),
            state.root_region
        );
        crate::assert_with_log!(
            state.live_region_count() == 1,
            "live region count",
            1usize,
            state.live_region_count()
        );
        crate::test_complete!("create_root_region");
    }

    #[test]
    fn policy_can_cancel_siblings() {
        init_test("policy_can_cancel_siblings");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let child = insert_task(&mut state, region);
        let sib1 = insert_task(&mut state, region);
        let sib2 = insert_task(&mut state, region);

        let policy = crate::types::policy::FailFast;
        let outcome = Outcome::<(), crate::error::Error>::Err(crate::error::Error::new(
            crate::error::ErrorKind::User,
        ));
        let (action, tasks) = state.apply_policy_on_child_outcome(region, child, &outcome, &policy);

        let expected_action = PolicyAction::CancelSiblings(CancelReason::sibling_failed());
        crate::assert_with_log!(
            action == expected_action,
            "cancel siblings action",
            expected_action,
            action
        );
        crate::assert_with_log!(tasks.len() == 2, "tasks len", 2usize, tasks.len());

        for sib in [sib1, sib2] {
            let record = state.task(sib).expect("sib missing");
            let is_cancel_requested = matches!(&record.state, TaskState::CancelRequested { .. });
            assert!(
                is_cancel_requested,
                "expected CancelRequested, got {:?}",
                record.state
            );

            if let TaskState::CancelRequested { reason, .. } = &record.state {
                crate::assert_with_log!(
                    reason.kind == CancelKind::FailFast,
                    "cancel reason kind",
                    CancelKind::FailFast,
                    reason.kind
                );
            }
        }
        let child_record = state.task(child).expect("child missing");
        let is_created = matches!(child_record.state, TaskState::Created);
        crate::assert_with_log!(is_created, "child remains created", true, is_created);
        crate::test_complete!("policy_can_cancel_siblings");
    }

    #[test]
    fn policy_does_not_cancel_siblings_on_cancelled_child() {
        init_test("policy_does_not_cancel_siblings_on_cancelled_child");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let child = insert_task(&mut state, region);
        let sib = insert_task(&mut state, region);

        let policy = crate::types::policy::FailFast;
        let outcome = Outcome::<(), crate::error::Error>::Cancelled(CancelReason::timeout());
        let (action, _) = state.apply_policy_on_child_outcome(region, child, &outcome, &policy);

        crate::assert_with_log!(
            action == PolicyAction::Continue,
            "action continue",
            PolicyAction::Continue,
            action
        );
        let sib_record = state.task(sib).expect("sib missing");
        let is_created = matches!(sib_record.state, TaskState::Created);
        crate::assert_with_log!(is_created, "sibling remains created", true, is_created);
        crate::test_complete!("policy_does_not_cancel_siblings_on_cancelled_child");
    }

    fn create_child_region(state: &mut RuntimeState, parent: RegionId) -> RegionId {
        let idx = state.regions.insert(RegionRecord::new(
            RegionId::from_arena(ArenaIndex::new(0, 0)),
            Some(parent),
            Budget::INFINITE,
        ));
        let id = RegionId::from_arena(idx);
        state.regions.get_mut(idx).expect("region missing").id = id;
        let added = state
            .regions
            .get_mut(parent.arena_index())
            .expect("parent missing")
            .add_child(id);
        crate::assert_with_log!(added.is_ok(), "child added to parent", true, added.is_ok());
        id
    }

    #[test]
    fn cancel_request_marks_region() {
        init_test("cancel_request_marks_region");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let idx = state.insert_task_with(|idx| {
            TaskRecord::new_with_time(
                TaskId::from_arena(idx),
                region,
                Budget::INFINITE,
                Time::ZERO,
            )
        });
        state
            .regions
            .get(region.arena_index())
            .unwrap()
            .add_task(TaskId::from_arena(idx))
            .unwrap();

        let _tasks = state.cancel_request(region, &CancelReason::timeout(), None);

        let region_record = state
            .regions
            .get(region.arena_index())
            .expect("region missing");
        let cancel_reason = region_record.cancel_reason();
        crate::assert_with_log!(
            cancel_reason.is_some(),
            "cancel reason set",
            true,
            cancel_reason.is_some()
        );
        let kind = cancel_reason.as_ref().unwrap().kind;
        crate::assert_with_log!(
            kind == CancelKind::Timeout,
            "cancel kind timeout",
            CancelKind::Timeout,
            kind
        );
        crate::test_complete!("cancel_request_marks_region");
    }

    #[test]
    fn cancel_request_marks_tasks() {
        init_test("cancel_request_marks_tasks");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task1 = insert_task(&mut state, region);
        let task2 = insert_task(&mut state, region);

        let tasks_to_schedule = state.cancel_request(region, &CancelReason::timeout(), None);

        // Both tasks should be returned for scheduling
        crate::assert_with_log!(
            tasks_to_schedule.len() == 2,
            "tasks scheduled",
            2usize,
            tasks_to_schedule.len()
        );
        let task_ids: Vec<_> = tasks_to_schedule.iter().map(|(id, _)| *id).collect();
        crate::assert_with_log!(
            task_ids.contains(&task1),
            "contains task1",
            true,
            task_ids.contains(&task1)
        );
        crate::assert_with_log!(
            task_ids.contains(&task2),
            "contains task2",
            true,
            task_ids.contains(&task2)
        );

        // Tasks should be in CancelRequested state
        for (task_id, _) in tasks_to_schedule {
            let task = state.task(task_id).expect("task missing");
            let is_cancel_requested = matches!(task.state, TaskState::CancelRequested { .. });
            crate::assert_with_log!(
                is_cancel_requested,
                "task cancel requested",
                true,
                is_cancel_requested
            );
        }
        crate::test_complete!("cancel_request_marks_tasks");
    }

    #[test]
    fn cancel_request_propagates_to_descendants() {
        init_test("cancel_request_propagates_to_descendants");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let grandchild = create_child_region(&mut state, child);

        let root_task = insert_task(&mut state, root);
        let child_task = insert_task(&mut state, child);
        let grandchild_task = insert_task(&mut state, grandchild);

        let tasks_to_schedule = state.cancel_request(root, &CancelReason::user("stop"), None);

        // All 3 tasks should be scheduled
        crate::assert_with_log!(
            tasks_to_schedule.len() == 3,
            "tasks scheduled",
            3usize,
            tasks_to_schedule.len()
        );

        // Root region gets original reason
        let root_record = state.regions.get(root.arena_index()).expect("root missing");
        let root_kind = root_record.cancel_reason().as_ref().unwrap().kind;
        crate::assert_with_log!(
            root_kind == CancelKind::User,
            "root cancel kind",
            CancelKind::User,
            root_kind
        );

        // Descendants get ParentCancelled
        let child_record = state
            .regions
            .get(child.arena_index())
            .expect("child missing");
        let child_kind = child_record.cancel_reason().as_ref().unwrap().kind;
        crate::assert_with_log!(
            child_kind == CancelKind::ParentCancelled,
            "child cancel kind",
            CancelKind::ParentCancelled,
            child_kind
        );

        let grandchild_record = state
            .regions
            .get(grandchild.arena_index())
            .expect("grandchild missing");
        let grandchild_kind = grandchild_record.cancel_reason().as_ref().unwrap().kind;
        crate::assert_with_log!(
            grandchild_kind == CancelKind::ParentCancelled,
            "grandchild cancel kind",
            CancelKind::ParentCancelled,
            grandchild_kind
        );

        // Root task gets User reason, descendants get ParentCancelled
        let root_task_record = state.task(root_task).expect("task missing");
        let is_cancel_requested =
            matches!(&root_task_record.state, TaskState::CancelRequested { .. });
        assert!(
            is_cancel_requested,
            "expected CancelRequested, got {:?}",
            root_task_record.state
        );

        if let TaskState::CancelRequested { reason, .. } = &root_task_record.state {
            crate::assert_with_log!(
                reason.kind == CancelKind::User,
                "root task cancel kind",
                CancelKind::User,
                reason.kind
            );
        }

        let child_task_record = state.task(child_task).expect("task missing");
        let is_cancel_requested =
            matches!(&child_task_record.state, TaskState::CancelRequested { .. });
        assert!(
            is_cancel_requested,
            "expected CancelRequested, got {:?}",
            child_task_record.state
        );

        if let TaskState::CancelRequested { reason, .. } = &child_task_record.state {
            crate::assert_with_log!(
                reason.kind == CancelKind::ParentCancelled,
                "child task cancel kind",
                CancelKind::ParentCancelled,
                reason.kind
            );
        }

        let grandchild_task_record = state.task(grandchild_task).expect("task missing");
        let is_cancel_requested = matches!(
            &grandchild_task_record.state,
            TaskState::CancelRequested { .. }
        );
        assert!(
            is_cancel_requested,
            "expected CancelRequested, got {:?}",
            grandchild_task_record.state
        );

        if let TaskState::CancelRequested { reason, .. } = &grandchild_task_record.state {
            crate::assert_with_log!(
                reason.kind == CancelKind::ParentCancelled,
                "grandchild task cancel kind",
                CancelKind::ParentCancelled,
                reason.kind
            );
        }
        crate::test_complete!("cancel_request_propagates_to_descendants");
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn cancel_request_builds_cause_chains() {
        init_test("cancel_request_builds_cause_chains");
        let mut state = RuntimeState::new();

        // Create a region tree: root -> child -> grandchild
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let grandchild = create_child_region(&mut state, child);

        // Create tasks in each region
        let root_task = insert_task(&mut state, root);
        let child_task = insert_task(&mut state, child);
        let grandchild_task = insert_task(&mut state, grandchild);

        // Cancel the root with a Deadline reason
        let original_reason = CancelReason::deadline().with_message("budget exhausted");
        let _ = state.cancel_request(root, &original_reason, None);

        // Verify root region has original reason (no cause chain)
        let root_record = state.regions.get(root.arena_index()).expect("root missing");
        let root_reason_opt = root_record.cancel_reason();
        let root_reason = root_reason_opt.as_ref().unwrap();
        crate::assert_with_log!(
            root_reason.kind == CancelKind::Deadline,
            "root reason kind",
            CancelKind::Deadline,
            root_reason.kind
        );
        crate::assert_with_log!(
            root_reason.chain_depth() == 1,
            "root chain depth",
            1,
            root_reason.chain_depth()
        );
        crate::assert_with_log!(
            root_reason.cause.is_none(),
            "root has no cause",
            true,
            root_reason.cause.is_none()
        );

        // Verify child region has ParentCancelled with cause chain to root's reason
        let child_record = state
            .regions
            .get(child.arena_index())
            .expect("child missing");
        let child_reason_opt = child_record.cancel_reason();
        let child_reason = child_reason_opt.as_ref().unwrap();
        crate::assert_with_log!(
            child_reason.kind == CancelKind::ParentCancelled,
            "child reason kind",
            CancelKind::ParentCancelled,
            child_reason.kind
        );
        crate::assert_with_log!(
            child_reason.chain_depth() == 2,
            "child chain depth",
            2,
            child_reason.chain_depth()
        );
        // Root cause should be the original Deadline
        let child_root_cause = child_reason.root_cause();
        crate::assert_with_log!(
            child_root_cause.kind == CancelKind::Deadline,
            "child root cause kind",
            CancelKind::Deadline,
            child_root_cause.kind
        );
        // Origin region should be the root (where cancellation originated)
        crate::assert_with_log!(
            child_reason.origin_region == root,
            "child origin region",
            root,
            child_reason.origin_region
        );

        // Verify grandchild region has ParentCancelled with chain depth of 3
        let grandchild_record = state
            .regions
            .get(grandchild.arena_index())
            .expect("grandchild missing");
        let grandchild_reason_opt = grandchild_record.cancel_reason();
        let grandchild_reason = grandchild_reason_opt.as_ref().unwrap();
        crate::assert_with_log!(
            grandchild_reason.kind == CancelKind::ParentCancelled,
            "grandchild reason kind",
            CancelKind::ParentCancelled,
            grandchild_reason.kind
        );
        crate::assert_with_log!(
            grandchild_reason.chain_depth() == 3,
            "grandchild chain depth",
            3,
            grandchild_reason.chain_depth()
        );
        // Root cause should still be the original Deadline
        let grandchild_root_cause = grandchild_reason.root_cause();
        crate::assert_with_log!(
            grandchild_root_cause.kind == CancelKind::Deadline,
            "grandchild root cause kind",
            CancelKind::Deadline,
            grandchild_root_cause.kind
        );
        // Origin region should be the child (immediate parent)
        crate::assert_with_log!(
            grandchild_reason.origin_region == child,
            "grandchild origin region",
            child,
            grandchild_reason.origin_region
        );

        // Verify tasks also have properly chained reasons
        let grandchild_task_record = state.task(grandchild_task).expect("task missing");
        let is_cancel_requested = matches!(
            &grandchild_task_record.state,
            TaskState::CancelRequested { .. }
        );
        assert!(
            is_cancel_requested,
            "expected CancelRequested, got {:?}",
            grandchild_task_record.state
        );

        if let TaskState::CancelRequested { reason, .. } = &grandchild_task_record.state {
            crate::assert_with_log!(
                reason.chain_depth() == 3,
                "grandchild task chain depth",
                3,
                reason.chain_depth()
            );
            crate::assert_with_log!(
                reason.root_cause().kind == CancelKind::Deadline,
                "grandchild task root cause",
                CancelKind::Deadline,
                reason.root_cause().kind
            );
        }

        // Verify we can traverse the full cause chain
        let chain: Vec<_> = grandchild_reason.chain().collect();
        crate::assert_with_log!(chain.len() == 3, "chain length", 3, chain.len());
        crate::assert_with_log!(
            chain[0].kind == CancelKind::ParentCancelled,
            "chain[0] kind",
            CancelKind::ParentCancelled,
            chain[0].kind
        );
        crate::assert_with_log!(
            chain[1].kind == CancelKind::ParentCancelled,
            "chain[1] kind",
            CancelKind::ParentCancelled,
            chain[1].kind
        );
        crate::assert_with_log!(
            chain[2].kind == CancelKind::Deadline,
            "chain[2] kind",
            CancelKind::Deadline,
            chain[2].kind
        );

        // Suppress unused variable warnings
        let _ = root_task;
        let _ = child_task;

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

    #[test]
    fn cancel_request_respects_attribution_limits() {
        init_test("cancel_request_respects_attribution_limits");
        let mut state = RuntimeState::new();
        state.set_cancel_attribution_config(CancelAttributionConfig::new(2, 256));

        let root = state.create_root_region(Budget::INFINITE);
        let idx_root = state.insert_task_with(|idx| {
            TaskRecord::new_with_time(TaskId::from_arena(idx), root, Budget::INFINITE, Time::ZERO)
        });
        state
            .regions
            .get(root.arena_index())
            .unwrap()
            .add_task(TaskId::from_arena(idx_root))
            .unwrap();
        let child = create_child_region(&mut state, root);
        let idx_child = state.insert_task_with(|idx| {
            TaskRecord::new_with_time(TaskId::from_arena(idx), child, Budget::INFINITE, Time::ZERO)
        });
        state
            .regions
            .get(child.arena_index())
            .unwrap()
            .add_task(TaskId::from_arena(idx_child))
            .unwrap();
        let grandchild = create_child_region(&mut state, child);
        let idx_grandchild = state.insert_task_with(|idx| {
            TaskRecord::new_with_time(
                TaskId::from_arena(idx),
                grandchild,
                Budget::INFINITE,
                Time::ZERO,
            )
        });
        state
            .regions
            .get(grandchild.arena_index())
            .unwrap()
            .add_task(TaskId::from_arena(idx_grandchild))
            .unwrap();

        let reason = CancelReason::deadline().with_message("root deadline");
        let _ = state.cancel_request(root, &reason, None);

        let child_reason = state
            .regions
            .get(child.arena_index())
            .and_then(RegionRecord::cancel_reason)
            .expect("child cancel reason missing");
        crate::assert_with_log!(
            child_reason.chain_depth() == 2,
            "child chain depth",
            2,
            child_reason.chain_depth()
        );
        crate::assert_with_log!(
            !child_reason.truncated,
            "child chain not truncated",
            false,
            child_reason.truncated
        );

        let grandchild_reason = state
            .regions
            .get(grandchild.arena_index())
            .and_then(RegionRecord::cancel_reason)
            .expect("grandchild cancel reason missing");
        crate::assert_with_log!(
            grandchild_reason.chain_depth() == 2,
            "grandchild chain depth",
            2,
            grandchild_reason.chain_depth()
        );
        crate::assert_with_log!(
            grandchild_reason.truncated,
            "grandchild chain truncated",
            true,
            grandchild_reason.truncated
        );
        crate::assert_with_log!(
            grandchild_reason.truncated_at_depth == Some(2),
            "grandchild truncation depth",
            Some(2),
            grandchild_reason.truncated_at_depth
        );

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

    #[test]
    fn cancel_request_respects_chain_depth_limit() {
        init_test("cancel_request_respects_chain_depth_limit");
        let mut state = RuntimeState::new();
        state.set_cancel_attribution_config(CancelAttributionConfig::new(2, usize::MAX));

        let root = state.create_root_region(Budget::INFINITE);
        let mut current = root;
        for _ in 0..4 {
            current = create_child_region(&mut state, current);
        }
        let leaf_task = insert_task(&mut state, current);

        let _ = state.cancel_request(root, &CancelReason::timeout(), None);

        let leaf_record = state
            .regions
            .get(current.arena_index())
            .expect("leaf missing");
        let binding = leaf_record.cancel_reason();
        let leaf_reason = binding.as_ref().expect("reason missing");
        crate::assert_with_log!(
            leaf_reason.chain_depth() <= 2,
            "leaf chain depth bounded",
            2,
            leaf_reason.chain_depth()
        );
        crate::assert_with_log!(
            leaf_reason.any_truncated(),
            "leaf reason truncated",
            true,
            leaf_reason.any_truncated()
        );

        let leaf_task_record = state
            .tasks
            .get(leaf_task.arena_index())
            .expect("task missing");
        match &leaf_task_record.state {
            TaskState::CancelRequested { reason, .. } => {
                crate::assert_with_log!(
                    reason.chain_depth() <= 2,
                    "leaf task chain depth bounded",
                    2,
                    reason.chain_depth()
                );
                crate::assert_with_log!(
                    reason.any_truncated(),
                    "leaf task reason truncated",
                    true,
                    reason.any_truncated()
                );
            }
            _other => {
                unreachable!("expected CancelRequested");
            }
        }

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

    #[test]
    fn cancel_request_truncates_large_tree() {
        init_test("cancel_request_truncates_large_tree");
        let mut state = RuntimeState::new();
        state.set_cancel_attribution_config(CancelAttributionConfig::new(4, 256));

        let root = state.create_root_region(Budget::INFINITE);
        let mut current = root;
        for _ in 0..64 {
            current = create_child_region(&mut state, current);
        }
        let leaf_task = insert_task(&mut state, current);

        let _ = state.cancel_request(root, &CancelReason::shutdown(), None);

        let leaf_record = state
            .regions
            .get(current.arena_index())
            .expect("leaf missing");
        let binding = leaf_record.cancel_reason();
        let leaf_reason = binding.as_ref().expect("reason missing");
        crate::assert_with_log!(
            leaf_reason.chain_depth() <= 4,
            "large tree chain depth bounded",
            4,
            leaf_reason.chain_depth()
        );
        crate::assert_with_log!(
            leaf_reason.any_truncated(),
            "large tree reason truncated",
            true,
            leaf_reason.any_truncated()
        );

        let leaf_task_record = state
            .tasks
            .get(leaf_task.arena_index())
            .expect("task missing");
        match &leaf_task_record.state {
            TaskState::CancelRequested { reason, .. } => {
                crate::assert_with_log!(
                    reason.chain_depth() <= 4,
                    "large tree task chain depth bounded",
                    4,
                    reason.chain_depth()
                );
                crate::assert_with_log!(
                    reason.any_truncated(),
                    "large tree task reason truncated",
                    true,
                    reason.any_truncated()
                );
            }
            _other => {
                unreachable!("expected CancelRequested");
            }
        }

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

    #[test]
    fn cancel_request_strengthens_existing_reason() {
        init_test("cancel_request_strengthens_existing_reason");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // First cancel with User
        let _ = state.cancel_request(region, &CancelReason::user("stop"), None);

        // Second cancel with Shutdown (higher severity)
        let _ = state.cancel_request(region, &CancelReason::shutdown(), None);

        // Region should have Shutdown reason
        let region_record = state
            .regions
            .get(region.arena_index())
            .expect("region missing");
        let region_kind = region_record.cancel_reason().as_ref().unwrap().kind;
        crate::assert_with_log!(
            region_kind == CancelKind::Shutdown,
            "region cancel kind",
            CancelKind::Shutdown,
            region_kind
        );

        // Task should have Shutdown reason
        let task_record = state.task(task).expect("task missing");
        let is_cancel_requested = matches!(&task_record.state, TaskState::CancelRequested { .. });
        assert!(
            is_cancel_requested,
            "expected CancelRequested, got {:?}",
            task_record.state
        );

        if let TaskState::CancelRequested { reason, .. } = &task_record.state {
            crate::assert_with_log!(
                reason.kind == CancelKind::Shutdown,
                "task cancel kind",
                CancelKind::Shutdown,
                reason.kind
            );
        }
        crate::test_complete!("cancel_request_strengthens_existing_reason");
    }

    #[test]
    fn can_region_finalize_with_all_tasks_done() {
        init_test("can_region_finalize_with_all_tasks_done");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Not finalizable while task is live
        let can_finalize = state.can_region_finalize(region);
        crate::assert_with_log!(
            !can_finalize,
            "cannot finalize with live task",
            false,
            can_finalize
        );

        // Complete the task
        state
            .task_mut(task)
            .expect("task missing")
            .complete(Outcome::Ok(()));

        // Now region can finalize
        let can_finalize = state.can_region_finalize(region);
        crate::assert_with_log!(can_finalize, "can finalize", true, can_finalize);
        crate::test_complete!("can_region_finalize_with_all_tasks_done");
    }

    #[test]
    fn can_region_finalize_requires_child_regions_closed() {
        init_test("can_region_finalize_requires_child_regions_closed");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);

        // Child region is Open, so root cannot finalize
        let can_finalize = state.can_region_finalize(root);
        crate::assert_with_log!(
            !can_finalize,
            "cannot finalize with open child",
            false,
            can_finalize
        );

        // Close the child region
        let child_record = state
            .regions
            .get_mut(child.arena_index())
            .expect("child missing");
        child_record.begin_close(None);
        child_record.begin_finalize();
        child_record.complete_close();

        // Now root can finalize
        let can_finalize = state.can_region_finalize(root);
        crate::assert_with_log!(can_finalize, "can finalize", true, can_finalize);
        crate::test_complete!("can_region_finalize_requires_child_regions_closed");
    }

    // =========================================================================
    // Finalizer Tests
    // =========================================================================

    #[test]
    fn register_sync_finalizer() {
        init_test("register_sync_finalizer");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        crate::assert_with_log!(
            state.region_finalizers_empty(region),
            "finalizers empty",
            true,
            state.region_finalizers_empty(region)
        );
        crate::assert_with_log!(
            state.region_finalizer_count(region) == 0,
            "finalizer count",
            0usize,
            state.region_finalizer_count(region)
        );

        // Register a sync finalizer
        let registered = state.register_sync_finalizer(region, || {});
        crate::assert_with_log!(registered, "register sync finalizer", true, registered);

        crate::assert_with_log!(
            !state.region_finalizers_empty(region),
            "finalizers not empty",
            false,
            state.region_finalizers_empty(region)
        );
        crate::assert_with_log!(
            state.region_finalizer_count(region) == 1,
            "finalizer count",
            1usize,
            state.region_finalizer_count(region)
        );
        crate::test_complete!("register_sync_finalizer");
    }

    #[test]
    fn register_async_finalizer() {
        init_test("register_async_finalizer");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let registered = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(registered, "register async finalizer", true, registered);
        crate::assert_with_log!(
            state.region_finalizer_count(region) == 1,
            "finalizer count",
            1usize,
            state.region_finalizer_count(region)
        );
        crate::test_complete!("register_async_finalizer");
    }

    #[test]
    fn register_finalizer_fails_when_region_not_open() {
        init_test("register_finalizer_fails_when_region_not_open");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Close the region
        state
            .regions
            .get_mut(region.arena_index())
            .expect("region missing")
            .begin_close(None);

        // Registration should fail
        let sync_ok = state.register_sync_finalizer(region, || {});
        let async_ok = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(!sync_ok, "sync finalizer rejected", false, sync_ok);
        crate::assert_with_log!(!async_ok, "async finalizer rejected", false, async_ok);
        crate::test_complete!("register_finalizer_fails_when_region_not_open");
    }

    #[test]
    fn register_finalizer_fails_for_nonexistent_region() {
        init_test("register_finalizer_fails_for_nonexistent_region");
        let mut state = RuntimeState::new();
        let fake_region = RegionId::from_arena(ArenaIndex::new(999, 0));

        let sync_ok = state.register_sync_finalizer(fake_region, || {});
        let async_ok = state.register_async_finalizer(fake_region, async {});
        crate::assert_with_log!(!sync_ok, "sync finalizer rejected", false, sync_ok);
        crate::assert_with_log!(!async_ok, "async finalizer rejected", false, async_ok);
        crate::test_complete!("register_finalizer_fails_for_nonexistent_region");
    }

    #[test]
    fn pop_region_finalizer_lifo() {
        init_test("pop_region_finalizer_lifo");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let order = std::sync::Arc::new(parking_lot::Mutex::new(Vec::new()));
        let o1 = order.clone();
        let o2 = order.clone();
        let o3 = order.clone();

        // Register finalizers: 1, 2, 3
        state.register_sync_finalizer(region, move || o1.lock().push(1));
        state.register_sync_finalizer(region, move || o2.lock().push(2));
        state.register_sync_finalizer(region, move || o3.lock().push(3));

        // Pop and execute in LIFO order
        while let Some(finalizer) = state.pop_region_finalizer(region) {
            if let Finalizer::Sync(f) = finalizer {
                f();
            }
        }

        // Should be 3, 2, 1 (LIFO)
        let observed = order.lock().clone();
        crate::assert_with_log!(
            observed == vec![3, 2, 1],
            "finalizer order",
            vec![3, 2, 1],
            observed
        );
        crate::test_complete!("pop_region_finalizer_lifo");
    }

    #[test]
    fn run_sync_finalizers_executes_and_returns_async() {
        init_test("run_sync_finalizers_executes_and_returns_async");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        let sync_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let sync_called_clone = sync_called.clone();

        // Register mix of sync and async finalizers
        // Execution Order (LIFO): Sync(empty), Async, Sync(flag=true)
        state.register_sync_finalizer(region, move || {
            sync_called_clone.store(true, std::sync::atomic::Ordering::SeqCst);
        });
        state.register_async_finalizer(region, async {});
        state.register_sync_finalizer(region, || {}); // Another sync

        // First pass: runs the top Sync(empty), stops at Async
        let async_finalizer = state.run_sync_finalizers(region);

        // The first sync finalizer (bottom of stack) should NOT have run yet due to async barrier
        let sync_flag = sync_called.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(
            !sync_flag,
            "first sync finalizer NOT called yet",
            false,
            sync_flag
        );

        // One async finalizer should be returned
        crate::assert_with_log!(
            async_finalizer.is_some(),
            "async finalizer returned",
            true,
            async_finalizer.is_some()
        );
        let is_async = matches!(async_finalizer, Some(Finalizer::Async(_)));
        crate::assert_with_log!(is_async, "is async", true, is_async);

        // Second pass: runs the remaining Sync(flag=true)
        let remaining = state.run_sync_finalizers(region);
        crate::assert_with_log!(
            remaining.is_none(),
            "no more async",
            true,
            remaining.is_none()
        );

        // Now the first sync finalizer should have run
        let sync_flag = sync_called.load(std::sync::atomic::Ordering::SeqCst);
        crate::assert_with_log!(sync_flag, "first sync finalizer called", true, sync_flag);

        // All finalizers should be cleared from region
        let empty = state.region_finalizers_empty(region);
        crate::assert_with_log!(empty, "finalizers cleared", true, empty);
        crate::test_complete!("run_sync_finalizers_executes_and_returns_async");
    }

    #[test]
    fn finalizer_history_tracks_sync_registration_run_and_close() {
        init_test("finalizer_history_tracks_sync_registration_run_and_close");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

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

        state.now = Time::from_nanos(20);
        let pending_async = state.run_sync_finalizers(region);
        crate::assert_with_log!(
            pending_async.is_none(),
            "no async barrier",
            true,
            pending_async.is_none()
        );

        state.now = Time::from_nanos(30);
        state.record_finalizer_close_for_test(region);

        crate::assert_with_log!(
            state.finalizer_history
                == vec![
                    FinalizerHistoryEvent::Registered {
                        id: 0,
                        region,
                        time: Time::from_nanos(10),
                    },
                    FinalizerHistoryEvent::Ran {
                        id: 0,
                        time: Time::from_nanos(20),
                    },
                    FinalizerHistoryEvent::RegionClosed {
                        region,
                        time: Time::from_nanos(30),
                    },
                ],
            "finalizer history",
            "registered -> ran -> closed",
            format!("{:?}", state.finalizer_history)
        );
        crate::test_complete!("finalizer_history_tracks_sync_registration_run_and_close");
    }

    #[test]
    fn task_completed_records_async_finalizer_run_history() {
        init_test("task_completed_records_async_finalizer_run_history");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        state.now = Time::from_nanos(10);
        let registered = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(registered, "registered", true, registered);

        let region_record = state
            .regions
            .get_mut(region.arena_index())
            .expect("region missing");
        region_record.begin_close(None);
        region_record.begin_finalize();
        state.finalizing_regions.push(region);

        state.now = Time::from_nanos(20);
        let scheduled = state.drain_ready_async_finalizers();
        crate::assert_with_log!(
            scheduled.len() == 1,
            "scheduled len",
            1usize,
            scheduled.len()
        );
        let task_id = scheduled[0].0;

        let task = state
            .task_mut(task_id)
            .expect("async finalizer task missing");
        task.complete(Outcome::Ok(()));

        state.now = Time::from_nanos(30);
        let _ = state.task_completed(task_id);

        crate::assert_with_log!(
            state.finalizer_history
                == vec![
                    FinalizerHistoryEvent::Registered {
                        id: 0,
                        region,
                        time: Time::from_nanos(10),
                    },
                    FinalizerHistoryEvent::Ran {
                        id: 0,
                        time: Time::from_nanos(30),
                    },
                    FinalizerHistoryEvent::RegionClosed {
                        region,
                        time: Time::from_nanos(30),
                    },
                ],
            "finalizer history",
            "registered -> ran -> closed",
            format!("{:?}", state.finalizer_history)
        );
        crate::test_complete!("task_completed_records_async_finalizer_run_history");
    }

    #[test]
    fn drain_ready_async_finalizers_runs_async_cleanup_even_with_zero_task_limit() {
        init_test("drain_ready_async_finalizers_runs_async_cleanup_even_with_zero_task_limit");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let set_limits = state.set_region_limits(
            region,
            RegionLimits {
                max_tasks: Some(0),
                ..RegionLimits::unlimited()
            },
        );
        crate::assert_with_log!(set_limits, "limits set", true, set_limits);

        let registered = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(registered, "registered", true, registered);

        let region_record = state
            .regions
            .get_mut(region.arena_index())
            .expect("region missing");
        region_record.begin_close(None);
        region_record.begin_finalize();
        state.finalizing_regions.push(region);

        let scheduled = state.drain_ready_async_finalizers();
        crate::assert_with_log!(
            scheduled.len() == 1,
            "async finalizer task scheduled even when normal task limit is zero",
            1usize,
            scheduled.len()
        );
        let task_id = scheduled[0].0;
        crate::assert_with_log!(
            state.region_finalizer_count(region) == 0,
            "async finalizer moved from barrier stack into running cleanup task",
            0usize,
            state.region_finalizer_count(region)
        );
        crate::assert_with_log!(
            !state.can_region_complete_close(region),
            "region must remain uncloseable while async cleanup task is still running",
            false,
            state.can_region_complete_close(region)
        );
        state
            .task_mut(task_id)
            .expect("async finalizer task missing")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task_id);
        crate::assert_with_log!(
            state.finalizer_history
                == vec![
                    FinalizerHistoryEvent::Registered {
                        id: 0,
                        region,
                        time: Time::ZERO,
                    },
                    FinalizerHistoryEvent::Ran {
                        id: 0,
                        time: Time::ZERO,
                    },
                    FinalizerHistoryEvent::RegionClosed {
                        region,
                        time: Time::ZERO,
                    },
                ],
            "history records cleanup execution and close once the finalizer task finishes",
            "registered -> ran -> closed",
            format!("{:?}", state.finalizer_history)
        );
        crate::test_complete!(
            "drain_ready_async_finalizers_runs_async_cleanup_even_with_zero_task_limit"
        );
    }

    #[test]
    fn drain_ready_async_finalizers_blocks_lower_finalizers_while_async_barrier_runs() {
        init_test("drain_ready_async_finalizers_blocks_lower_finalizers_while_async_barrier_runs");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let sync_runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let sync_runs_clone = Arc::clone(&sync_runs);

        // LIFO order: async barrier on top, then a lower sync finalizer that must wait.
        let registered_sync = state.register_sync_finalizer(region, move || {
            sync_runs_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        });
        crate::assert_with_log!(registered_sync, "sync registered", true, registered_sync);
        let registered_async = state.register_async_finalizer(region, async {});
        crate::assert_with_log!(registered_async, "async registered", true, registered_async);

        let region_record = state
            .regions
            .get(region.arena_index())
            .expect("region missing");
        region_record.begin_close(None);
        region_record.begin_finalize();
        state.finalizing_regions.push(region);

        let first = state.drain_ready_async_finalizers();
        crate::assert_with_log!(
            first.len() == 1,
            "first async barrier scheduled",
            1usize,
            first.len()
        );
        crate::assert_with_log!(
            sync_runs.load(std::sync::atomic::Ordering::SeqCst) == 0,
            "lower sync finalizer has not run yet",
            0usize,
            sync_runs.load(std::sync::atomic::Ordering::SeqCst)
        );
        crate::assert_with_log!(
            state.region_finalizer_count(region) == 1,
            "lower finalizer still queued behind async barrier",
            1usize,
            state.region_finalizer_count(region)
        );

        let second = state.drain_ready_async_finalizers();
        crate::assert_with_log!(
            second.is_empty(),
            "second drain does not bypass in-flight async barrier",
            true,
            second.is_empty()
        );
        crate::assert_with_log!(
            sync_runs.load(std::sync::atomic::Ordering::SeqCst) == 0,
            "lower sync finalizer still blocked",
            0usize,
            sync_runs.load(std::sync::atomic::Ordering::SeqCst)
        );

        let task_id = first[0].0;
        state
            .task_mut(task_id)
            .expect("async finalizer task missing")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task_id);

        crate::assert_with_log!(
            sync_runs.load(std::sync::atomic::Ordering::SeqCst) == 1,
            "lower sync finalizer runs after async barrier completes",
            1usize,
            sync_runs.load(std::sync::atomic::Ordering::SeqCst)
        );
        let region_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_removed,
            "region closes after deferred lower finalizer runs",
            true,
            region_removed
        );

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

    #[test]
    fn can_region_complete_close_requires_finalizing_state() {
        init_test("can_region_complete_close_requires_finalizing_state");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Must be in Finalizing state
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(
            !can_close,
            "cannot close when not finalizing",
            false,
            can_close
        );

        // Transition to Finalizing
        let region_record = state.regions.get_mut(region.arena_index()).expect("region");
        region_record.begin_close(None);
        region_record.begin_finalize();

        // Now it can complete (no finalizers)
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(can_close, "can close", true, can_close);
        crate::test_complete!("can_region_complete_close_requires_finalizing_state");
    }

    #[test]
    fn can_region_complete_close_checks_finalizers() {
        init_test("can_region_complete_close_checks_finalizers");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Add finalizer while open
        state.register_sync_finalizer(region, || {});

        // Transition to Finalizing
        let region_record = state.regions.get_mut(region.arena_index()).expect("region");
        region_record.begin_close(None);
        region_record.begin_finalize();

        // Can't complete while finalizers pending
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(
            !can_close,
            "cannot close with pending finalizers",
            false,
            can_close
        );

        // Run the finalizers
        let _ = state.run_sync_finalizers(region);

        // Now can complete
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(can_close, "can close", true, can_close);
        crate::test_complete!("can_region_complete_close_checks_finalizers");
    }

    #[test]
    fn task_completed_removes_task_from_region() {
        init_test("task_completed_removes_task_from_region");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Insert some tasks
        let task1 = insert_task(&mut state, region);
        let task2 = insert_task(&mut state, region);
        let task3 = insert_task(&mut state, region);

        // Verify all tasks are in the region
        let region_record = state.regions.get(region.arena_index()).expect("region");
        let task_ids = region_record.task_ids();
        crate::assert_with_log!(task_ids.len() == 3, "task count", 3usize, task_ids.len());
        crate::assert_with_log!(
            task_ids.contains(&task1),
            "contains task1",
            true,
            task_ids.contains(&task1)
        );
        crate::assert_with_log!(
            task_ids.contains(&task2),
            "contains task2",
            true,
            task_ids.contains(&task2)
        );
        crate::assert_with_log!(
            task_ids.contains(&task3),
            "contains task3",
            true,
            task_ids.contains(&task3)
        );

        // Complete task2 (transition to Completed state first)
        state
            .task_mut(task2)
            .expect("task2")
            .complete(Outcome::Ok(()));

        // Call task_completed to notify the runtime
        let waiters = state.task_completed(task2);
        crate::assert_with_log!(waiters.is_empty(), "no waiters", true, waiters.is_empty()); // No waiters registered

        // Verify task2 is removed from the region
        let region_record = state.regions.get(region.arena_index()).expect("region");
        let task_ids = region_record.task_ids();
        crate::assert_with_log!(task_ids.len() == 2, "task count", 2usize, task_ids.len());
        crate::assert_with_log!(
            task_ids.contains(&task1),
            "contains task1",
            true,
            task_ids.contains(&task1)
        );
        crate::assert_with_log!(
            !task_ids.contains(&task2),
            "task2 removed",
            false,
            task_ids.contains(&task2)
        );
        crate::assert_with_log!(
            task_ids.contains(&task3),
            "contains task3",
            true,
            task_ids.contains(&task3)
        );

        // Verify task2 is removed from the state
        let removed = state.task(task2).is_none();
        crate::assert_with_log!(removed, "task2 removed from state", true, removed);

        // Complete remaining tasks
        state
            .task_mut(task1)
            .expect("task1")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task1);

        state
            .task_mut(task3)
            .expect("task3")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task3);

        // Verify all tasks removed from region
        let region_record = state.regions.get(region.arena_index()).expect("region");
        let empty = region_record.task_ids().is_empty();
        crate::assert_with_log!(empty, "region tasks empty", true, empty);
        crate::test_complete!("task_completed_removes_task_from_region");
    }

    #[test]
    fn spawn_rejected_when_task_limit_reached() {
        init_test("spawn_rejected_when_task_limit_reached");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let limits = RegionLimits {
            max_tasks: Some(1),
            ..RegionLimits::unlimited()
        };
        let set = state.set_region_limits(region, limits);
        crate::assert_with_log!(set, "limits set", true, set);

        let (task_id, _handle) = state
            .create_task(region, Budget::INFINITE, async { 1_u8 })
            .expect("first task");
        let result = state.create_task(region, Budget::INFINITE, async { 2_u8 });
        let rejected = matches!(result, Err(SpawnError::RegionAtCapacity { .. }));
        crate::assert_with_log!(rejected, "spawn rejected", true, rejected);
        let region_record = state.regions.get(region.arena_index()).expect("region");
        let tasks = region_record.task_ids();
        crate::assert_with_log!(tasks.len() == 1, "one task live", 1, tasks.len());
        crate::assert_with_log!(
            tasks.contains(&task_id),
            "task id preserved",
            true,
            tasks.contains(&task_id)
        );
        crate::assert_with_log!(
            state.tasks_arena().len() == 1,
            "arena len stable",
            1,
            state.tasks_arena().len()
        );
        crate::test_complete!("spawn_rejected_when_task_limit_reached");
    }

    #[test]
    fn obligation_rejected_when_limit_reached() {
        init_test("obligation_rejected_when_limit_reached");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let limits = RegionLimits {
            max_obligations: Some(0),
            ..RegionLimits::unlimited()
        };
        let set = state.set_region_limits(region, limits);
        crate::assert_with_log!(set, "limits set", true, set);

        let holder = insert_task(&mut state, region);
        let err = state
            .create_obligation(ObligationKind::IoOp, holder, region, None)
            .expect_err("obligation limit enforced");
        crate::assert_with_log!(
            err.kind() == ErrorKind::AdmissionDenied,
            "admission denied",
            ErrorKind::AdmissionDenied,
            err.kind()
        );
        let pending = state.pending_obligation_count();
        crate::assert_with_log!(pending == 0, "no obligations recorded", 0, pending);
        crate::test_complete!("obligation_rejected_when_limit_reached");
    }

    #[test]
    fn create_obligation_rejects_missing_holder_task() {
        init_test("create_obligation_rejects_missing_holder_task");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let missing_holder = TaskId::from_arena(ArenaIndex::new(999, 0));

        let err = state
            .create_obligation(ObligationKind::IoOp, missing_holder, region, None)
            .expect_err("missing holder should be rejected");
        crate::assert_with_log!(
            err.kind() == ErrorKind::TaskNotOwned,
            "missing holder rejected as task ownership error",
            ErrorKind::TaskNotOwned,
            err.kind()
        );
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "no obligations created for missing holder",
            0usize,
            state.pending_obligation_count()
        );
        crate::test_complete!("create_obligation_rejects_missing_holder_task");
    }

    #[test]
    fn create_obligation_rejects_holder_owned_by_different_region() {
        init_test("create_obligation_rejects_holder_owned_by_different_region");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let child_task = insert_task(&mut state, child);

        let err = state
            .create_obligation(ObligationKind::IoOp, child_task, root, None)
            .expect_err("cross-region holder should be rejected");
        crate::assert_with_log!(
            err.kind() == ErrorKind::TaskNotOwned,
            "cross-region holder rejected as task ownership error",
            ErrorKind::TaskNotOwned,
            err.kind()
        );
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "no obligations created for cross-region holder",
            0usize,
            state.pending_obligation_count()
        );
        crate::test_complete!("create_obligation_rejects_holder_owned_by_different_region");
    }

    #[test]
    fn cancel_request_should_prevent_new_spawns() {
        init_test("cancel_request_should_prevent_new_spawns");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let idx = state.insert_task_with(|idx| {
            TaskRecord::new_with_time(
                TaskId::from_arena(idx),
                region,
                Budget::INFINITE,
                Time::ZERO,
            )
        });
        state
            .regions
            .get(region.arena_index())
            .unwrap()
            .add_task(TaskId::from_arena(idx))
            .unwrap();

        // Request cancellation
        let _ = state.cancel_request(region, &CancelReason::user("stop"), None);

        // Verify state transition
        let region_record = state.regions.get(region.arena_index()).expect("region");
        let region_state = region_record.state();
        let can_spawn = region_state.can_spawn();
        crate::assert_with_log!(
            !can_spawn,
            "region no longer accepts spawns",
            false,
            can_spawn
        );

        // Verify spawning is rejected with error (not panic)
        let result = state.create_task(region, Budget::INFINITE, async { 42 });
        let rejected = matches!(result, Err(SpawnError::RegionClosed(_)));
        crate::assert_with_log!(rejected, "spawn rejected", true, rejected);
        crate::test_complete!("cancel_request_should_prevent_new_spawns");
    }

    // =========================================================================
    // IoDriver Integration Tests
    // =========================================================================

    #[test]
    fn new_creates_state_without_io_driver() {
        init_test("new_creates_state_without_io_driver");
        let state = RuntimeState::new();
        crate::assert_with_log!(
            !state.has_io_driver(),
            "no io driver",
            false,
            state.has_io_driver()
        );
        crate::assert_with_log!(
            state.io_driver().is_none(),
            "io driver none",
            true,
            state.io_driver().is_none()
        );
        crate::test_complete!("new_creates_state_without_io_driver");
    }

    #[test]
    fn without_reactor_creates_state_without_io_driver() {
        init_test("without_reactor_creates_state_without_io_driver");
        let state = RuntimeState::without_reactor();
        crate::assert_with_log!(
            !state.has_io_driver(),
            "no io driver",
            false,
            state.has_io_driver()
        );
        crate::assert_with_log!(
            state.io_driver().is_none(),
            "io driver none",
            true,
            state.io_driver().is_none()
        );
        crate::test_complete!("without_reactor_creates_state_without_io_driver");
    }

    #[test]
    fn with_reactor_creates_state_with_io_driver() {
        init_test("with_reactor_creates_state_with_io_driver");
        let reactor = Arc::new(LabReactor::new());
        let state = RuntimeState::with_reactor(reactor);

        crate::assert_with_log!(
            state.has_io_driver(),
            "has io driver",
            true,
            state.has_io_driver()
        );
        crate::assert_with_log!(
            state.io_driver().is_some(),
            "io driver some",
            true,
            state.io_driver().is_some()
        );

        // Verify the driver is functional
        let driver = state.io_driver().unwrap();
        crate::assert_with_log!(driver.is_empty(), "driver empty", true, driver.is_empty());
        crate::assert_with_log!(
            driver.waker_count() == 0,
            "waker count",
            0usize,
            driver.waker_count()
        );
        crate::test_complete!("with_reactor_creates_state_with_io_driver");
    }

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

        let mut state = RuntimeState::new();
        crate::assert_with_log!(
            !state.has_io_driver(),
            "starts without io driver",
            false,
            state.has_io_driver()
        );

        let handle = IoDriverHandle::new(Arc::new(LabReactor::new()));
        let waker_state = Arc::new(TestWaker(AtomicBool::new(false)));
        let waker = Waker::from(waker_state);
        {
            let mut driver = handle.lock();
            let _ = driver.register_waker(waker);
        }

        state.set_io_driver(handle);
        crate::assert_with_log!(
            state.has_io_driver(),
            "io driver attached",
            true,
            state.has_io_driver()
        );
        let injected = state.io_driver_handle().expect("state io driver");
        crate::assert_with_log!(
            injected.waker_count() == 1,
            "injected handle retained state",
            1usize,
            injected.waker_count()
        );

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

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

        let reactor = Arc::new(LabReactor::new());
        let state = RuntimeState::with_reactor(reactor);

        // Mutably access driver to register a waker
        let waker_state = Arc::new(TestWaker(AtomicBool::new(false)));
        let waker = Waker::from(waker_state);
        {
            let mut driver = state.io_driver_mut().unwrap();
            let _key = driver.register_waker(waker);
        }

        // Verify registration
        let waker_count = state.io_driver().unwrap().waker_count();
        crate::assert_with_log!(waker_count == 1, "waker count", 1usize, waker_count);
        let empty = state.io_driver().unwrap().is_empty();
        crate::assert_with_log!(!empty, "driver not empty", false, empty);
        crate::test_complete!("io_driver_mut_allows_modification");
    }

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

        let reactor = Arc::new(LabReactor::new());
        let state = RuntimeState::with_reactor(reactor);

        // Initially quiescent (no tasks, no I/O registrations)
        let quiescent = state.is_quiescent();
        crate::assert_with_log!(quiescent, "initial quiescent", true, quiescent);

        // Register a waker
        let waker_state = Arc::new(TestWaker(AtomicBool::new(false)));
        let waker = Waker::from(waker_state);
        let key = {
            let mut driver = state.io_driver_mut().unwrap();
            driver.register_waker(waker)
        };

        // No longer quiescent due to I/O registration
        let quiescent = state.is_quiescent();
        crate::assert_with_log!(!quiescent, "not quiescent", false, quiescent);

        // Deregister
        {
            let mut driver = state.io_driver_mut().unwrap();
            driver.deregister_waker(key);
        }

        // Quiescent again
        let quiescent = state.is_quiescent();
        crate::assert_with_log!(quiescent, "quiescent again", true, quiescent);
        crate::test_complete!("is_quiescent_considers_io_driver");
    }

    #[test]
    fn is_quiescent_without_io_driver_ignores_io() {
        init_test("is_quiescent_without_io_driver_ignores_io");
        let state = RuntimeState::new();

        // Quiescent without I/O driver
        let quiescent = state.is_quiescent();
        crate::assert_with_log!(quiescent, "quiescent", true, quiescent);
        crate::test_complete!("is_quiescent_without_io_driver_ignores_io");
    }

    // =========================================================================
    // Cancellation + Obligations Lifecycle Tests (bd-38kk)
    // =========================================================================

    #[test]
    #[allow(clippy::too_many_lines)]
    fn cancel_drain_finalize_full_lifecycle() {
        init_test("cancel_drain_finalize_full_lifecycle");
        let metrics = Arc::new(TestMetrics::default());
        let mut state = RuntimeState::new_with_metrics(metrics.clone());
        let root = state.create_root_region(Budget::INFINITE);

        // Spawn tasks in the region
        let task1 = insert_task(&mut state, root);
        let task2 = insert_task(&mut state, root);

        // Register a sync finalizer while region is open
        let finalizer_called = Arc::new(AtomicBool::new(false));
        let finalizer_flag = finalizer_called.clone();
        state.register_sync_finalizer(root, move || {
            finalizer_flag.store(true, Ordering::SeqCst);
        });

        // Phase 1: Cancel request → region enters Closing
        let tasks_to_schedule = state.cancel_request(root, &CancelReason::timeout(), None);
        crate::assert_with_log!(
            tasks_to_schedule.len() == 2,
            "both tasks scheduled for cancel",
            2usize,
            tasks_to_schedule.len()
        );
        let region_state = state
            .regions
            .get(root.arena_index())
            .expect("region")
            .state();
        crate::assert_with_log!(
            region_state == crate::record::region::RegionState::Closing,
            "region closing after cancel request",
            crate::record::region::RegionState::Closing,
            region_state
        );

        // Phase 2: First task completes with Cancelled outcome → still draining
        state
            .task_mut(task1)
            .expect("task1")
            .complete(Outcome::Cancelled(CancelReason::timeout()));
        let _ = state.task_completed(task1);
        let region_state = state
            .regions
            .get(root.arena_index())
            .expect("region")
            .state();
        // Region should still be Closing (one task remains)
        crate::assert_with_log!(
            region_state == crate::record::region::RegionState::Closing,
            "region still closing with live task",
            crate::record::region::RegionState::Closing,
            region_state
        );
        let finalizer_ran = finalizer_called.load(Ordering::SeqCst);
        crate::assert_with_log!(
            !finalizer_ran,
            "finalizer not yet called",
            false,
            finalizer_ran
        );

        // Phase 3: Second task completes → triggers advance_region_state
        // → Finalizing (no children, no tasks) → runs sync finalizers → Closed
        state
            .task_mut(task2)
            .expect("task2")
            .complete(Outcome::Cancelled(CancelReason::timeout()));
        let _ = state.task_completed(task2);

        // Region should transition through Finalizing → Closed
        // (sync finalizers are run inline by advance_region_state)
        let region_state_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed after all tasks complete (removed)",
            true,
            region_state_removed
        );
        let finalizer_ran = finalizer_called.load(Ordering::SeqCst);
        crate::assert_with_log!(
            finalizer_ran,
            "finalizer was called during finalization",
            true,
            finalizer_ran
        );

        // Verify metrics recorded both cancelled completions
        let cancelled_count = metrics
            .completions
            .lock()
            .iter()
            .filter(|o| **o == OutcomeKind::Cancelled)
            .count();
        crate::assert_with_log!(
            cancelled_count == 2,
            "cancelled completions count",
            2usize,
            cancelled_count
        );

        // Verify trace contains both CancelRequest and task completion events
        let events = state.trace.snapshot();
        let cancel_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::CancelRequest)
            .count();
        crate::assert_with_log!(
            cancel_events >= 1,
            "cancel request trace events",
            true,
            cancel_events >= 1
        );
        crate::test_complete!("cancel_drain_finalize_full_lifecycle");
    }

    #[test]
    fn cancel_drain_finalize_nested_regions() {
        init_test("cancel_drain_finalize_nested_regions");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);

        let root_task = insert_task(&mut state, root);
        let child_task = insert_task(&mut state, child);

        // Cancel the root region (propagates to child)
        let _ = state.cancel_request(root, &CancelReason::user("stop"), None);

        // Complete child task first
        state
            .task_mut(child_task)
            .expect("child_task")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(child_task);

        // Child region should close since it has no tasks and no children
        let child_state_removed = state.regions.get(child.arena_index()).is_none();
        crate::assert_with_log!(
            child_state_removed,
            "child closed after its task completes (removed)",
            true,
            child_state_removed
        );

        // Root should still be open (has root_task)
        let root_state = state
            .regions
            .get(root.arena_index())
            .expect("root region")
            .state();
        let root_closing = matches!(
            root_state,
            crate::record::region::RegionState::Closing
                | crate::record::region::RegionState::Draining
        );
        crate::assert_with_log!(
            root_closing,
            "root still closing/draining with live task",
            true,
            root_closing
        );

        // Complete root task → root should close
        state
            .task_mut(root_task)
            .expect("root_task")
            .complete(Outcome::Cancelled(CancelReason::user("stop")));
        let _ = state.task_completed(root_task);

        let root_state_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_state_removed,
            "root closed after all tasks and children done (removed)",
            true,
            root_state_removed
        );
        crate::test_complete!("cancel_drain_finalize_nested_regions");
    }

    #[test]
    fn obligations_auto_aborted_on_cancelled_task_completion() {
        init_test("obligations_auto_aborted_on_cancelled_task_completion");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Silent;
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create obligations of different kinds
        let obl_send = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create send permit");
        let obl_ack = state
            .create_obligation(ObligationKind::Ack, task, region, None)
            .expect("create ack");
        let obl_io = state
            .create_obligation(ObligationKind::IoOp, task, region, None)
            .expect("create io op");

        crate::assert_with_log!(
            state.pending_obligation_count() == 3,
            "three pending obligations",
            3usize,
            state.pending_obligation_count()
        );

        // Cancel region → task gets cancel-requested
        let _ = state.cancel_request(region, &CancelReason::timeout(), None);

        // Complete task with Cancelled outcome
        // task_completed() should auto-abort orphaned obligations
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::timeout()));
        let _ = state.task_completed(task);

        // All obligations should be resolved (aborted by task_completed)
        for obl_id in [obl_send, obl_ack, obl_io] {
            let record = state
                .obligations
                .get(obl_id.arena_index())
                .expect("obligation still in arena");
            crate::assert_with_log!(
                !record.is_pending(),
                "obligation resolved after task cancel",
                false,
                record.is_pending()
            );
        }

        // No pending obligations remain
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "zero pending obligations",
            0usize,
            state.pending_obligation_count()
        );

        // Verify trace has obligation events
        let events = state.trace.snapshot();
        let abort_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationAbort)
            .count();
        crate::assert_with_log!(
            abort_events == 3,
            "three obligation abort trace events",
            3usize,
            abort_events
        );
        crate::test_complete!("obligations_auto_aborted_on_cancelled_task_completion");
    }

    #[test]
    fn obligation_commit_before_cancel_then_drain() {
        init_test("obligation_commit_before_cancel_then_drain");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create obligation and commit it before cancellation
        let obl = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create obligation");
        let _ = state.commit_obligation(obl).expect("commit before cancel");

        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "no pending after commit",
            0usize,
            state.pending_obligation_count()
        );

        // Cancel and complete the task
        let _ = state.cancel_request(region, &CancelReason::timeout(), None);
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::timeout()));
        let _ = state.task_completed(task);

        // Region should close cleanly (no leaks, obligation was already committed)
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed cleanly (removed)",
            true,
            region_state_removed
        );

        // Verify trace has commit event
        let events = state.trace.snapshot();
        let commit_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationCommit)
            .count();
        crate::assert_with_log!(
            commit_events == 1,
            "one obligation commit event",
            1usize,
            commit_events
        );
        crate::test_complete!("obligation_commit_before_cancel_then_drain");
    }

    #[test]
    fn region_close_blocked_by_pending_obligations() {
        init_test("region_close_blocked_by_pending_obligations");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Silent;
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create an obligation
        let obl = state
            .create_obligation(ObligationKind::Lease, task, region, None)
            .expect("create obligation");

        // Transition region to Finalizing manually
        let region_record = state.regions.get_mut(region.arena_index()).expect("region");
        region_record.begin_close(None);
        region_record.begin_finalize();

        // Complete the task to make it terminal
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));

        // can_region_complete_close should return false (pending obligation)
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(
            !can_close,
            "cannot close with pending obligation",
            false,
            can_close
        );

        // Commit the obligation
        let _ = state.commit_obligation(obl).expect("commit obligation");

        // Now it should be closable (task is terminal, obligation resolved)
        // Remove the task from the region to simulate full completion
        if let Some(region_rec) = state.regions.get(region.arena_index()) {
            region_rec.remove_task(task);
        }
        let can_close = state.can_region_complete_close(region);
        crate::assert_with_log!(
            can_close,
            "can close after obligation committed",
            true,
            can_close
        );
        crate::test_complete!("region_close_blocked_by_pending_obligations");
    }

    #[test]
    fn cancel_with_obligations_full_trace_lifecycle() {
        init_test("cancel_with_obligations_full_trace_lifecycle");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);
        state.record_task_spawn(task, region);

        // Create obligation
        let _obl = state
            .create_obligation(
                ObligationKind::SendPermit,
                task,
                region,
                Some("test-permit".to_string()),
            )
            .expect("create obligation");

        // Cancel and complete
        let _ = state.cancel_request(region, &CancelReason::deadline(), None);
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::deadline()));
        let _ = state.task_completed(task);

        // Verify full trace event sequence
        let events = state.trace.snapshot();
        let kinds: Vec<_> = events.iter().map(|e| e.kind).collect();

        // Should contain: Spawn, ObligationReserve, CancelRequest, ObligationAbort
        let has_spawn = kinds.contains(&TraceEventKind::Spawn);
        let has_reserve = kinds.contains(&TraceEventKind::ObligationReserve);
        let has_cancel = kinds.contains(&TraceEventKind::CancelRequest);
        let has_abort = kinds.contains(&TraceEventKind::ObligationAbort);

        crate::assert_with_log!(has_spawn, "trace has spawn", true, has_spawn);
        crate::assert_with_log!(
            has_reserve,
            "trace has obligation reserve",
            true,
            has_reserve
        );
        crate::assert_with_log!(has_cancel, "trace has cancel request", true, has_cancel);
        crate::assert_with_log!(has_abort, "trace has obligation abort", true, has_abort);

        // Verify ordering: reserve < cancel < abort
        let reserve_seq = events
            .iter()
            .find(|e| e.kind == TraceEventKind::ObligationReserve)
            .map(|e| e.seq)
            .expect("reserve event");
        let cancel_seq = events
            .iter()
            .find(|e| e.kind == TraceEventKind::CancelRequest)
            .map(|e| e.seq)
            .expect("cancel event");
        let abort_seq = events
            .iter()
            .find(|e| e.kind == TraceEventKind::ObligationAbort)
            .map(|e| e.seq)
            .expect("abort event");
        crate::assert_with_log!(
            reserve_seq < cancel_seq,
            "reserve before cancel",
            true,
            reserve_seq < cancel_seq
        );
        crate::assert_with_log!(
            cancel_seq < abort_seq,
            "cancel before abort",
            true,
            cancel_seq < abort_seq
        );

        // Region should be fully closed
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed (removed)",
            true,
            region_state_removed
        );
        crate::test_complete!("cancel_with_obligations_full_trace_lifecycle");
    }

    #[test]
    fn mixed_obligation_resolution_during_cancel() {
        init_test("mixed_obligation_resolution_during_cancel");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create three obligations
        let obl_committed = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create send");
        let obl_aborted = state
            .create_obligation(ObligationKind::Ack, task, region, None)
            .expect("create ack");
        let obl_orphaned = state
            .create_obligation(ObligationKind::IoOp, task, region, None)
            .expect("create io");

        // Commit one before cancellation
        let _ = state.commit_obligation(obl_committed).expect("commit send");

        // Explicitly abort another before cancellation
        let _ = state
            .abort_obligation(obl_aborted, ObligationAbortReason::Explicit)
            .expect("abort ack");

        crate::assert_with_log!(
            state.pending_obligation_count() == 1,
            "one obligation still pending",
            1usize,
            state.pending_obligation_count()
        );

        // Cancel and complete task (obl_orphaned should be auto-aborted)
        let _ = state.cancel_request(region, &CancelReason::shutdown(), None);
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::shutdown()));
        let _ = state.task_completed(task);

        // All obligations resolved
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "zero pending obligations",
            0usize,
            state.pending_obligation_count()
        );

        // Verify the orphaned one was aborted
        let orphaned_record = state
            .obligations
            .get(obl_orphaned.arena_index())
            .expect("orphaned obligation");
        crate::assert_with_log!(
            !orphaned_record.is_pending(),
            "orphaned obligation resolved",
            false,
            orphaned_record.is_pending()
        );

        // Region should be closed
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed (removed)",
            true,
            region_state_removed
        );
        crate::test_complete!("mixed_obligation_resolution_during_cancel");
    }

    #[test]
    fn region_quiescence_requires_no_live_children_or_tasks() {
        init_test("region_quiescence_requires_no_live_children_or_tasks");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let task = insert_task(&mut state, child);

        // Root cannot finalize: has open child with live task
        let can_finalize_root = state.can_region_finalize(root);
        crate::assert_with_log!(
            !can_finalize_root,
            "root cannot finalize with open child",
            false,
            can_finalize_root
        );

        // Child cannot finalize: has live task
        let can_finalize_child = state.can_region_finalize(child);
        crate::assert_with_log!(
            !can_finalize_child,
            "child cannot finalize with live task",
            false,
            can_finalize_child
        );

        // Cancel and complete everything
        let _ = state.cancel_request(root, &CancelReason::user("done"), None);
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(task);

        // Both should now be closed (advance_region_state drives the cascade)
        let child_state_removed = state.regions.get(child.arena_index()).is_none();
        crate::assert_with_log!(
            child_state_removed,
            "child closed (removed)",
            true,
            child_state_removed
        );
        let root_state_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_state_removed,
            "root closed (removed)",
            true,
            root_state_removed
        );
        crate::test_complete!("region_quiescence_requires_no_live_children_or_tasks");
    }

    #[test]
    fn cancel_prevents_new_obligation_creation() {
        init_test("cancel_prevents_new_obligation_creation");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Cancel the region
        let _ = state.cancel_request(region, &CancelReason::timeout(), None);

        // Attempt to create an obligation in a cancelled region should fail
        let result = state.create_obligation(ObligationKind::SendPermit, task, region, None);
        let rejected = result.is_err();
        crate::assert_with_log!(
            rejected,
            "obligation creation rejected in cancelled region",
            true,
            rejected
        );
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "no obligations created",
            0usize,
            state.pending_obligation_count()
        );
        crate::test_complete!("cancel_prevents_new_obligation_creation");
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn multiple_tasks_obligations_cancel_drain_finalize() {
        init_test("multiple_tasks_obligations_cancel_drain_finalize");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task_a = insert_task(&mut state, region);
        let task_b = insert_task(&mut state, region);

        // Each task holds obligations
        let obl_a = state
            .create_obligation(ObligationKind::SendPermit, task_a, region, None)
            .expect("obl_a");
        let obl_b1 = state
            .create_obligation(ObligationKind::Ack, task_b, region, None)
            .expect("obl_b1");
        let obl_b2 = state
            .create_obligation(ObligationKind::Lease, task_b, region, None)
            .expect("obl_b2");

        crate::assert_with_log!(
            state.pending_obligation_count() == 3,
            "three pending",
            3usize,
            state.pending_obligation_count()
        );

        // Cancel the region
        let _ = state.cancel_request(region, &CancelReason::deadline(), None);

        // task_a commits its obligation during cleanup, then completes
        let _ = state.commit_obligation(obl_a).expect("commit obl_a");
        state
            .task_mut(task_a)
            .expect("task_a")
            .complete(Outcome::Cancelled(CancelReason::deadline()));
        let _ = state.task_completed(task_a);

        // Region still open: task_b still alive with obligations
        let region_state = state
            .regions
            .get(region.arena_index())
            .expect("region")
            .state();
        crate::assert_with_log!(
            region_state == crate::record::region::RegionState::Closing,
            "region still closing",
            crate::record::region::RegionState::Closing,
            region_state
        );
        crate::assert_with_log!(
            state.pending_obligation_count() == 2,
            "two pending (task_b's)",
            2usize,
            state.pending_obligation_count()
        );

        // task_b completes → its orphaned obligations auto-aborted
        state
            .task_mut(task_b)
            .expect("task_b")
            .complete(Outcome::Cancelled(CancelReason::deadline()));
        let _ = state.task_completed(task_b);

        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "all obligations resolved",
            0usize,
            state.pending_obligation_count()
        );

        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed (removed)",
            true,
            region_state_removed
        );

        // Verify trace events
        let events = state.trace.snapshot();
        let reserve_count = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationReserve)
            .count();
        let commit_count = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationCommit)
            .count();
        let abort_count = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationAbort)
            .count();
        crate::assert_with_log!(
            reserve_count == 3,
            "three reserve events",
            3usize,
            reserve_count
        );
        crate::assert_with_log!(
            commit_count == 1,
            "one commit event (obl_a)",
            1usize,
            commit_count
        );
        crate::assert_with_log!(
            abort_count == 2,
            "two abort events (obl_b1 + obl_b2)",
            2usize,
            abort_count
        );
        // Suppress unused variable warnings
        let _ = obl_b1;
        let _ = obl_b2;
        crate::test_complete!("multiple_tasks_obligations_cancel_drain_finalize");
    }

    /// Integration test with real epoll reactor.
    #[cfg(target_os = "linux")]
    mod epoll_integration {
        use super::*;
        use crate::runtime::reactor::{EpollReactor, Interest};
        use std::io::Write;
        use std::os::unix::net::UnixStream;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::task::Waker;
        use std::time::Duration;

        struct FlagWaker(AtomicBool);
        impl Wake for FlagWaker {
            fn wake(self: Arc<Self>) {
                self.0.store(true, Ordering::SeqCst);
            }
        }

        #[test]
        fn runtime_state_with_epoll_reactor() {
            super::init_test("runtime_state_with_epoll_reactor");
            let reactor = Arc::new(EpollReactor::new().expect("create reactor"));
            let state = RuntimeState::with_reactor(reactor);

            crate::assert_with_log!(
                state.has_io_driver(),
                "has io driver",
                true,
                state.has_io_driver()
            );
            let quiescent = state.is_quiescent();
            crate::assert_with_log!(quiescent, "quiescent", true, quiescent);

            // Create a socket pair
            let (sock_read, mut sock_write) = UnixStream::pair().expect("socket pair");

            // Register with the driver
            let waker_state = Arc::new(FlagWaker(AtomicBool::new(false)));
            let waker = Waker::from(waker_state.clone());

            let registration = {
                let mut driver = state.io_driver_mut().unwrap();
                driver
                    .register(&sock_read, Interest::READABLE, waker)
                    .expect("register")
            };

            // Not quiescent due to I/O registration
            let quiescent = state.is_quiescent();
            crate::assert_with_log!(!quiescent, "not quiescent", false, quiescent);

            // Make socket readable
            sock_write.write_all(b"hello").expect("write");

            // Turn the driver to dispatch waker
            let count = {
                let mut driver = state.io_driver_mut().unwrap();
                driver.turn(Some(Duration::from_millis(100))).expect("turn")
            };

            crate::assert_with_log!(count >= 1, "event count", true, count >= 1);
            let flag = waker_state.0.load(Ordering::SeqCst);
            crate::assert_with_log!(flag, "waker fired", true, flag);

            // Deregister and verify quiescence
            {
                let mut driver = state.io_driver_mut().unwrap();
                driver.deregister(registration).expect("deregister");
            }
            let quiescent = state.is_quiescent();
            crate::assert_with_log!(quiescent, "quiescent", true, quiescent);
            crate::test_complete!("runtime_state_with_epoll_reactor");
        }
    }

    // =========================================================================
    // OBLIGATION LEAK ESCALATION POLICY TESTS (bd-n6xm4)
    // =========================================================================

    /// Helper: create a state with an obligation that will leak on task completion.
    /// Returns (state, region, task, obligation_id).
    fn setup_leakable_obligation(
        response: ObligationLeakResponse,
    ) -> (RuntimeState, RegionId, TaskId, ObligationId) {
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(response);
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);
        let obl = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create obligation");
        (state, region, task, obl)
    }

    /// Helper: complete a task with Ok outcome (triggers leak detection for
    /// pending obligations, unlike Cancelled which auto-aborts them).
    fn complete_task_ok(state: &mut RuntimeState, task: TaskId) {
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task);
    }

    #[test]
    fn leak_response_silent_marks_leaked_no_log() {
        init_test("leak_response_silent_marks_leaked_no_log");
        let (mut state, _region, task, obl) =
            setup_leakable_obligation(ObligationLeakResponse::Silent);

        complete_task_ok(&mut state, task);

        // Obligation should be in Leaked state
        let record = state.obligations.get(obl.arena_index()).expect("obl");
        crate::assert_with_log!(
            record.state == ObligationState::Leaked,
            "obligation leaked",
            ObligationState::Leaked,
            record.state
        );
        crate::assert_with_log!(
            state.leak_count() == 1,
            "leak count incremented",
            1u64,
            state.leak_count()
        );
        crate::test_complete!("leak_response_silent_marks_leaked_no_log");
    }

    #[test]
    fn leak_response_log_marks_leaked() {
        init_test("leak_response_log_marks_leaked");
        let (mut state, _region, task, obl) =
            setup_leakable_obligation(ObligationLeakResponse::Log);

        complete_task_ok(&mut state, task);

        let record = state.obligations.get(obl.arena_index()).expect("obl");
        crate::assert_with_log!(
            record.state == ObligationState::Leaked,
            "obligation leaked via Log mode",
            ObligationState::Leaked,
            record.state
        );

        // Trace should contain ObligationLeak event
        let events = state.trace.snapshot();
        let leak_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationLeak)
            .count();
        crate::assert_with_log!(
            leak_events == 1,
            "one leak trace event",
            1usize,
            leak_events
        );
        crate::assert_with_log!(
            state.leak_count() == 1,
            "leak count",
            1u64,
            state.leak_count()
        );
        crate::test_complete!("leak_response_log_marks_leaked");
    }

    #[test]
    fn leak_response_recover_aborts_instead_of_leaking() {
        init_test("leak_response_recover_aborts_instead_of_leaking");
        let (mut state, _region, task, obl) =
            setup_leakable_obligation(ObligationLeakResponse::Recover);

        complete_task_ok(&mut state, task);

        // With Recover, the obligation is aborted (not leaked)
        let record = state.obligations.get(obl.arena_index()).expect("obl");
        crate::assert_with_log!(
            record.state == ObligationState::Aborted,
            "obligation aborted by recovery",
            ObligationState::Aborted,
            record.state
        );

        // Trace should contain ObligationAbort (not ObligationLeak)
        let events = state.trace.snapshot();
        let abort_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationAbort)
            .count();
        let leak_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationLeak)
            .count();
        crate::assert_with_log!(
            abort_events >= 1,
            "abort trace event from recovery",
            true,
            abort_events >= 1
        );
        crate::assert_with_log!(
            leak_events == 0,
            "no leak trace event in recover mode",
            0usize,
            leak_events
        );
        crate::assert_with_log!(
            state.leak_count() == 1,
            "leak count still incremented",
            1u64,
            state.leak_count()
        );
        crate::test_complete!("leak_response_recover_aborts_instead_of_leaking");
    }

    #[test]
    #[should_panic(expected = "obligation leak")]
    fn leak_response_panic_panics() {
        init_test("leak_response_panic_panics");
        let (mut state, _region, task, _obl) =
            setup_leakable_obligation(ObligationLeakResponse::Panic);

        complete_task_ok(&mut state, task);
        // Should panic before reaching here
    }

    #[test]
    fn leak_escalation_from_log_to_panic() {
        init_test("leak_escalation_from_log_to_panic");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Log);
        state.set_leak_escalation(Some(LeakEscalation::new(3, ObligationLeakResponse::Panic)));
        let region = state.create_root_region(Budget::INFINITE);

        // First two leaks should be logged (not panic)
        for i in 0u64..2 {
            let task = insert_task(&mut state, region);
            state
                .create_obligation(ObligationKind::SendPermit, task, region, None)
                .expect("create obligation");
            complete_task_ok(&mut state, task);
            let expected = i + 1;
            crate::assert_with_log!(
                state.leak_count() == expected,
                &format!("leak count after batch {expected}"),
                expected,
                state.leak_count()
            );
        }

        // Third leak should escalate to Panic
        let task = insert_task(&mut state, region);
        state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create obligation");

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            complete_task_ok(&mut state, task);
        }));
        crate::assert_with_log!(
            result.is_err(),
            "escalated to panic at threshold",
            true,
            result.is_err()
        );
        crate::test_complete!("leak_escalation_from_log_to_panic");
    }

    #[test]
    fn leak_escalation_from_silent_to_recover() {
        init_test("leak_escalation_from_silent_to_recover");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);
        state.set_leak_escalation(Some(LeakEscalation::new(
            2,
            ObligationLeakResponse::Recover,
        )));
        let region = state.create_root_region(Budget::INFINITE);

        // First leak: Silent mode — obligation gets Leaked state
        let task1 = insert_task(&mut state, region);
        let obl1 = state
            .create_obligation(ObligationKind::Ack, task1, region, None)
            .expect("create");
        complete_task_ok(&mut state, task1);
        let record1 = state.obligations.get(obl1.arena_index()).expect("obl1");
        crate::assert_with_log!(
            record1.state == ObligationState::Leaked,
            "first leak: Leaked state (silent)",
            ObligationState::Leaked,
            record1.state
        );

        // Second leak: escalates to Recover — obligation gets Aborted state
        let task2 = insert_task(&mut state, region);
        let obl2 = state
            .create_obligation(ObligationKind::Lease, task2, region, None)
            .expect("create");
        complete_task_ok(&mut state, task2);
        let record2 = state.obligations.get(obl2.arena_index()).expect("obl2");
        crate::assert_with_log!(
            record2.state == ObligationState::Aborted,
            "second leak: Aborted (recovered)",
            ObligationState::Aborted,
            record2.state
        );
        crate::assert_with_log!(
            state.leak_count() == 2,
            "total leak count",
            2u64,
            state.leak_count()
        );
        crate::test_complete!("leak_escalation_from_silent_to_recover");
    }

    #[test]
    fn leak_count_accumulates_across_tasks() {
        init_test("leak_count_accumulates_across_tasks");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);
        let region = state.create_root_region(Budget::INFINITE);

        // Create 5 tasks, each with 2 obligations — 10 total leaks
        for _ in 0..5 {
            let task = insert_task(&mut state, region);
            state
                .create_obligation(ObligationKind::SendPermit, task, region, None)
                .expect("create");
            state
                .create_obligation(ObligationKind::IoOp, task, region, None)
                .expect("create");
            complete_task_ok(&mut state, task);
        }

        crate::assert_with_log!(
            state.leak_count() == 10,
            "10 cumulative leaks",
            10u64,
            state.leak_count()
        );
        crate::test_complete!("leak_count_accumulates_across_tasks");
    }

    #[test]
    fn no_escalation_when_not_configured() {
        init_test("no_escalation_when_not_configured");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);
        // No escalation configured
        let region = state.create_root_region(Budget::INFINITE);

        // Even after 100 leaks, response stays Silent (no escalation)
        for _ in 0..100 {
            let task = insert_task(&mut state, region);
            state
                .create_obligation(ObligationKind::SendPermit, task, region, None)
                .expect("create");
            complete_task_ok(&mut state, task);
        }

        crate::assert_with_log!(
            state.leak_count() == 100,
            "100 leaks, no panic",
            100u64,
            state.leak_count()
        );
        crate::test_complete!("no_escalation_when_not_configured");
    }

    // ── bd-2wfti: Cross-entity lock ordering regression tests ──────────
    //
    // These tests exercise multi-entity state machine transitions that will
    // need to hold multiple shard locks (B→A→C) once RuntimeState is migrated
    // to ShardedState. They serve as safety nets for that migration.

    #[test]
    #[allow(clippy::too_many_lines)]
    fn three_level_cascade_with_obligations() {
        // Verifies: cancel propagation through 3-level region tree with
        // obligations at each level. Tests the B→A→C lock ordering path
        // through advance_region_state's cascading parent advancement.
        init_test("three_level_cascade_with_obligations");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Silent;
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let grandchild = create_child_region(&mut state, child);

        // Insert tasks at each level
        let root_task = insert_task(&mut state, root);
        let child_task = insert_task(&mut state, child);
        let gc_task = insert_task(&mut state, grandchild);

        // Create obligations at each level
        let _root_obl = state
            .create_obligation(ObligationKind::SendPermit, root_task, root, None)
            .expect("root obl");
        let child_obl = state
            .create_obligation(ObligationKind::Ack, child_task, child, None)
            .expect("child obl");
        let _gc_obl = state
            .create_obligation(ObligationKind::IoOp, gc_task, grandchild, None)
            .expect("gc obl");

        crate::assert_with_log!(
            state.pending_obligation_count() == 3,
            "three pending obligations across tree",
            3usize,
            state.pending_obligation_count()
        );

        // Cancel root (propagates to child and grandchild)
        let tasks_to_schedule = state.cancel_request(root, &CancelReason::user("shutdown"), None);
        crate::assert_with_log!(
            tasks_to_schedule.len() == 3,
            "all three tasks scheduled for cancel",
            3usize,
            tasks_to_schedule.len()
        );

        // Complete leaf-first: grandchild task (gc_obl auto-aborted)
        state
            .task_mut(gc_task)
            .expect("gc_task")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(gc_task);

        // Grandchild region should close (no tasks, no children, no pending obligations)
        let gc_state_removed = state.regions.get(grandchild.arena_index()).is_none();
        crate::assert_with_log!(
            gc_state_removed,
            "grandchild closed (removed)",
            true,
            gc_state_removed
        );

        // Child still open (child_task alive with child_obl)
        let child_state_now = state
            .regions
            .get(child.arena_index())
            .expect("child")
            .state();
        let child_still_active = !matches!(child_state_now, RegionState::Closed);
        crate::assert_with_log!(
            child_still_active,
            "child not yet closed",
            true,
            child_still_active
        );

        // Commit child obligation explicitly, then complete child task
        let _ = state
            .commit_obligation(child_obl)
            .expect("commit child obl");
        state
            .task_mut(child_task)
            .expect("child_task")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(child_task);

        // Child region should close (no tasks, no children, obligation committed)
        let child_state_final_removed = state.regions.get(child.arena_index()).is_none();
        crate::assert_with_log!(
            child_state_final_removed,
            "child closed after task + obligation resolved (removed)",
            true,
            child_state_final_removed
        );

        // Root still open (root_task alive with root_obl)
        let root_state_mid = state.regions.get(root.arena_index()).expect("root").state();
        let root_not_closed = !matches!(root_state_mid, RegionState::Closed);
        crate::assert_with_log!(
            root_not_closed,
            "root not yet closed",
            true,
            root_not_closed
        );

        // Complete root task (root_obl orphaned, auto-aborted via leak detection)
        state
            .task_mut(root_task)
            .expect("root_task")
            .complete(Outcome::Cancelled(CancelReason::user("shutdown")));
        let _ = state.task_completed(root_task);

        // Root should close (all children closed, all tasks done, obligations resolved)
        let root_state_final_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_state_final_removed,
            "root closed after full cascade (removed)",
            true,
            root_state_final_removed
        );

        // All obligations resolved
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "zero pending obligations after cascade",
            0usize,
            state.pending_obligation_count()
        );

        // Verify trace has events for all three levels
        let events = state.trace.snapshot();
        let cancel_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::CancelRequest)
            .count();
        crate::assert_with_log!(
            cancel_events >= 1,
            "cancel trace events emitted",
            true,
            cancel_events >= 1
        );

        let abort_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationAbort)
            .count();
        // gc_obl and root_obl were auto-aborted (child_obl was committed)
        crate::assert_with_log!(
            abort_events >= 2,
            "at least two obligation aborts (gc + root)",
            true,
            abort_events >= 2
        );
        crate::test_complete!("three_level_cascade_with_obligations");
    }

    #[test]
    fn obligation_resolve_advances_draining_region() {
        // Verifies: resolving the last obligation in a draining region
        // triggers advance_region_state through the Finalizing path.
        // This exercises the B→A→C path in for_obligation_resolve.
        init_test("obligation_resolve_advances_draining_region");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create two obligations
        let obl1 = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("obl1");
        let obl2 = state
            .create_obligation(ObligationKind::Ack, task, region, None)
            .expect("obl2");

        // Cancel region → Closing
        let _ = state.cancel_request(region, &CancelReason::timeout(), None);

        // Complete task (obligations become orphans → auto-aborted only if
        // task_completed detects them). Let's commit one before completing.
        let _ = state.commit_obligation(obl1).expect("commit obl1");

        // Abort the second explicitly
        let _ = state
            .abort_obligation(obl2, ObligationAbortReason::Cancel)
            .expect("abort obl2");

        // Now complete the task
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Cancelled(CancelReason::timeout()));
        let _ = state.task_completed(task);

        // Region should advance through Finalizing → Closed
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed after obligation resolve + task complete (removed)",
            true,
            region_state_removed
        );

        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "zero pending",
            0usize,
            state.pending_obligation_count()
        );
        crate::test_complete!("obligation_resolve_advances_draining_region");
    }

    #[test]
    fn shardguard_locking_patterns_exercised() {
        use crate::runtime::ShardGuard;
        use crate::runtime::ShardedState;
        use crate::runtime::sharded_state::ShardedConfig;

        // Verifies: ShardGuard factory methods correctly acquire locks
        // for each cross-entity operation pattern.
        // This test validates the ShardGuard infrastructure that will be
        // used when RuntimeState methods are migrated to work with shards.
        init_test("shardguard_locking_patterns_exercised");

        let trace = TraceBufferHandle::new(1024);
        let metrics: Arc<dyn MetricsProvider> = Arc::new(TestMetrics::default());
        let config = ShardedConfig {
            io_driver: None,
            timer_driver: None,
            logical_clock_mode: LogicalClockMode::Lamport,
            cancel_attribution: CancelAttributionConfig::default(),
            entropy_source: Arc::new(OsEntropy),
            blocking_pool: None,
            obligation_leak_response: ObligationLeakResponse::Log,
            leak_escalation: None,
            observability: None,
        };
        let shards = ShardedState::new(trace, metrics, config);

        // Verify each guard pattern acquires the correct shards
        {
            let guard = ShardGuard::for_spawn(&shards);
            let has_regions = guard.regions.is_some();
            let has_tasks = guard.tasks.is_some();
            let no_obligations = guard.obligations.is_none();
            drop(guard);
            crate::assert_with_log!(
                has_regions && has_tasks && no_obligations,
                "for_spawn: B+A only",
                true,
                has_regions && has_tasks && no_obligations
            );
        }

        {
            let guard = ShardGuard::for_obligation(&shards);
            let has_regions = guard.regions.is_some();
            let no_tasks = guard.tasks.is_none();
            let has_obligations = guard.obligations.is_some();
            drop(guard);
            crate::assert_with_log!(
                has_regions && no_tasks && has_obligations,
                "for_obligation: B+C only",
                true,
                has_regions && no_tasks && has_obligations
            );
        }

        {
            let guard = ShardGuard::for_task_completed(&shards);
            let all_present =
                guard.regions.is_some() && guard.tasks.is_some() && guard.obligations.is_some();
            drop(guard);
            crate::assert_with_log!(all_present, "for_task_completed: B+A+C", true, all_present);
        }

        {
            let guard = ShardGuard::for_cancel(&shards);
            let all_present =
                guard.regions.is_some() && guard.tasks.is_some() && guard.obligations.is_some();
            drop(guard);
            crate::assert_with_log!(all_present, "for_cancel: B+A+C", true, all_present);
        }

        {
            let guard = ShardGuard::for_obligation_resolve(&shards);
            let all_present =
                guard.regions.is_some() && guard.tasks.is_some() && guard.obligations.is_some();
            drop(guard);
            crate::assert_with_log!(
                all_present,
                "for_obligation_resolve: B+A+C",
                true,
                all_present
            );
        }

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

    #[test]
    fn task_completed_ok_with_leaked_obligations_closes_region() {
        // Verifies: non-cancelled task completing with pending obligations
        // triggers the leak handling path (not the auto-abort path).
        // mark_obligation_leaked must call resolve_obligation() so the
        // region's pending_obligations counter is decremented. Without this,
        // the region would be stuck in Finalizing with a desynchronized counter.
        // This exercises the B→A→C path through handle_obligation_leaks.
        init_test("task_completed_ok_with_leaked_obligations_closes_region");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Silent;
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create obligations but DO NOT commit/abort them
        let _obl1 = state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("obl1");
        let _obl2 = state
            .create_obligation(ObligationKind::Ack, task, region, None)
            .expect("obl2");

        // Request close on the region so advance_region_state is allowed to
        // drive it through Closing -> Finalizing -> Closed.
        {
            let region_record = state.regions.get(region.arena_index()).expect("region");
            region_record.begin_close(None);
        }

        crate::assert_with_log!(
            state.pending_obligation_count() == 2,
            "two pending obligations",
            2usize,
            state.pending_obligation_count()
        );

        // Complete the task with Ok (NOT Cancelled) — this triggers the leak
        // handling path at task_completed:1831-1841 instead of the auto-abort.
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task);

        // Region should still close because mark_obligation_leaked resolves
        // the obligation from the region's perspective.
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed despite leaked obligations (Silent mode) (removed)",
            true,
            region_state_removed
        );

        // Verify leak trace events were emitted
        let events = state.trace.snapshot();
        let leak_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationLeak)
            .count();
        crate::assert_with_log!(
            leak_events == 2,
            "two obligation leak trace events",
            2usize,
            leak_events
        );
        crate::test_complete!("task_completed_ok_with_leaked_obligations_closes_region");
    }

    #[test]
    fn finalizing_leak_detection_waits_for_task_cleanup() {
        // Regression: Finalizing leak detection used to treat "all tracked
        // tasks are terminal" as equivalent to "task cleanup has finished".
        // That is too early because task_completed still owns orphan abort/leak
        // handling and region unlinking. We must not mark leaks until the task
        // is fully removed from the owning region.
        init_test("finalizing_leak_detection_waits_for_task_cleanup");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        state
            .create_obligation(ObligationKind::SendPermit, task, region, None)
            .expect("create obligation");

        {
            let region_record = state.regions.get(region.arena_index()).expect("region");
            region_record.begin_close(None);
            region_record.begin_finalize();
        }

        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));

        // Advancing the Finalizing region before task_completed runs must not
        // leak-resolve the obligation yet, even though the task is terminal.
        state.advance_region_state(region);
        crate::assert_with_log!(
            state.pending_obligation_count() == 1,
            "pending obligation preserved until task cleanup",
            1usize,
            state.pending_obligation_count()
        );
        crate::assert_with_log!(
            state.leak_count() == 0,
            "no leaks emitted before task cleanup",
            0u64,
            state.leak_count()
        );
        let early_leak_events = state
            .trace
            .snapshot()
            .into_iter()
            .filter(|event| event.kind == TraceEventKind::ObligationLeak)
            .count();
        crate::assert_with_log!(
            early_leak_events == 0,
            "no leak trace events before task cleanup",
            0usize,
            early_leak_events
        );

        let _ = state.task_completed(task);

        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "task_completed resolves leaked obligation",
            0usize,
            state.pending_obligation_count()
        );
        crate::assert_with_log!(
            state.leak_count() == 1,
            "exactly one leak emitted after task cleanup",
            1u64,
            state.leak_count()
        );
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closes after task cleanup handles leak",
            true,
            region_state_removed
        );
        crate::test_complete!("finalizing_leak_detection_waits_for_task_cleanup");
    }

    #[test]
    fn cancel_sibling_tasks_preserves_triggering_child() {
        // Verifies: cancel_sibling_tasks cancels all siblings in a region
        // EXCEPT the triggering child. This exercises the B→A path through
        // the sibling cancellation flow.
        init_test("cancel_sibling_tasks_preserves_triggering_child");
        let mut state = RuntimeState::new();
        let region = state.create_root_region(Budget::INFINITE);

        // Insert 4 tasks in the same region
        let task_a = insert_task(&mut state, region);
        let task_b = insert_task(&mut state, region);
        let task_c = insert_task(&mut state, region);
        let task_d = insert_task(&mut state, region);

        // Cancel siblings of task_b (should cancel a, c, d but not b)
        let reason = CancelReason::fail_fast().with_message("sibling failed");
        let to_cancel = state.cancel_sibling_tasks(region, task_b, &reason);

        // task_b should NOT appear in the cancellation list
        let cancelled_ids: Vec<TaskId> = to_cancel.iter().map(|(id, _)| *id).collect();
        crate::assert_with_log!(
            !cancelled_ids.contains(&task_b),
            "triggering child not cancelled",
            false,
            cancelled_ids.contains(&task_b)
        );

        // All other tasks should be cancelled
        crate::assert_with_log!(
            cancelled_ids.len() == 3,
            "three siblings cancelled",
            3usize,
            cancelled_ids.len()
        );
        for &expected in &[task_a, task_c, task_d] {
            crate::assert_with_log!(
                cancelled_ids.contains(&expected),
                "sibling in cancel list",
                true,
                cancelled_ids.contains(&expected)
            );
        }

        // Verify task_b's state is unchanged (still Created)
        let b_record = state.task(task_b).expect("task_b");
        crate::assert_with_log!(
            matches!(b_record.state, TaskState::Created),
            "triggering child state unchanged",
            true,
            matches!(b_record.state, TaskState::Created)
        );

        // Verify cancelled siblings have CancelRequested state
        for &sib in &[task_a, task_c, task_d] {
            let record = state.task(sib).expect("sibling");
            let is_cancel_requested = record.state.is_cancelling();
            crate::assert_with_log!(
                is_cancel_requested,
                "sibling is cancelling",
                true,
                is_cancel_requested
            );
        }
        crate::test_complete!("cancel_sibling_tasks_preserves_triggering_child");
    }

    #[test]
    fn bottom_up_cascade_without_cancel() {
        // Verifies: regions close bottom-up via advance_region_state when
        // tasks complete naturally (no cancellation involved). This tests
        // the iterative parent advancement in advance_region_state.
        init_test("bottom_up_cascade_without_cancel");
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let grandchild = create_child_region(&mut state, child);

        // One task in each region
        let gc_task = insert_task(&mut state, grandchild);
        let child_task = insert_task(&mut state, child);
        let root_task = insert_task(&mut state, root);

        // Request close on root (sets Closing, but doesn't cancel tasks)
        {
            let region = state.regions.get(root.arena_index()).expect("root");
            region.begin_close(None);
        }
        {
            let region = state.regions.get(child.arena_index()).expect("child");
            region.begin_close(None);
        }
        {
            let region = state
                .regions
                .get(grandchild.arena_index())
                .expect("grandchild");
            region.begin_close(None);
        }

        // Complete grandchild task → grandchild region should cascade to Closed
        state
            .task_mut(gc_task)
            .expect("gc_task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(gc_task);

        let gc_state_removed = state.regions.get(grandchild.arena_index()).is_none();
        crate::assert_with_log!(
            gc_state_removed,
            "grandchild closed after task done (removed)",
            true,
            gc_state_removed
        );

        // Child should NOT be closed yet (child_task still alive)
        let child_state = state
            .regions
            .get(child.arena_index())
            .expect("child")
            .state();
        let child_not_closed = !matches!(child_state, RegionState::Closed);
        crate::assert_with_log!(
            child_not_closed,
            "child not closed (task alive)",
            true,
            child_not_closed
        );

        // Complete child task → child region should cascade to Closed
        state
            .task_mut(child_task)
            .expect("child_task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(child_task);

        let child_state_final_removed = state.regions.get(child.arena_index()).is_none();
        crate::assert_with_log!(
            child_state_final_removed,
            "child closed after task done + grandchild closed (removed)",
            true,
            child_state_final_removed
        );

        // Root should NOT be closed yet (root_task still alive)
        let root_state = state.regions.get(root.arena_index()).expect("root").state();
        let root_not_closed = !matches!(root_state, RegionState::Closed);
        crate::assert_with_log!(
            root_not_closed,
            "root not closed (task alive)",
            true,
            root_not_closed
        );

        // Complete root task → root should cascade to Closed
        state
            .task_mut(root_task)
            .expect("root_task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(root_task);

        let root_state_final_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_state_final_removed,
            "root closed after full cascade (removed)",
            true,
            root_state_final_removed
        );
        crate::test_complete!("bottom_up_cascade_without_cancel");
    }

    #[test]
    fn obligation_leak_recover_mode_allows_region_close() {
        // Verifies: Recover mode aborts leaked obligations (via abort_obligation)
        // so the region's pending_obligations counter is decremented and the
        // region can complete close. This exercises the B→A→C path through
        // handle_obligation_leaks → abort_obligation → resolve_obligation →
        // advance_region_state.
        init_test("obligation_leak_recover_mode_allows_region_close");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Recover;
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create obligations that will be leaked
        let _obl1 = state
            .create_obligation(ObligationKind::Lease, task, region, None)
            .expect("lease");
        let _obl2 = state
            .create_obligation(ObligationKind::IoOp, task, region, None)
            .expect("io_op");

        // Request close on the region so advance_region_state can complete close
        // once leaked obligations are recovered (auto-aborted).
        {
            let region_record = state.regions.get(region.arena_index()).expect("region");
            region_record.begin_close(None);
        }

        crate::assert_with_log!(
            state.pending_obligation_count() == 2,
            "two pending obligations",
            2usize,
            state.pending_obligation_count()
        );

        // Complete task with Err (non-cancelled) → triggers leak handler
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Err(Error::new(ErrorKind::Internal)));
        let _ = state.task_completed(task);

        // In Recover mode, leaked obligations are aborted, so region should close
        let region_state_removed = state.regions.get(region.arena_index()).is_none();
        crate::assert_with_log!(
            region_state_removed,
            "region closed in Recover mode (removed)",
            true,
            region_state_removed
        );

        // Verify abort events (Recover mode aborts, doesn't just mark leaked)
        let events = state.trace.snapshot();
        let abort_events = events
            .iter()
            .filter(|e| e.kind == TraceEventKind::ObligationAbort)
            .count();
        crate::assert_with_log!(
            abort_events == 2,
            "two obligation aborts in recover mode",
            2usize,
            abort_events
        );
        crate::test_complete!("obligation_leak_recover_mode_allows_region_close");
    }

    #[test]
    fn mixed_obligation_resolution_during_cancel_cascade() {
        // Verifies: a mix of committed, aborted, and orphaned obligations
        // during a cancel cascade all resolve correctly, allowing the region
        // tree to close. Exercises the full B→A→C cross-entity path with
        // interleaved obligation state changes.
        init_test("mixed_obligation_resolution_during_cancel_cascade");
        let mut state = RuntimeState::new();
        state.obligation_leak_response = ObligationLeakResponse::Silent;
        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);

        let root_task = insert_task(&mut state, root);
        let child_task1 = insert_task(&mut state, child);
        let child_task2 = insert_task(&mut state, child);

        // Create obligations on different tasks
        let root_obl = state
            .create_obligation(ObligationKind::SendPermit, root_task, root, None)
            .expect("root obl");
        let child_obl1 = state
            .create_obligation(ObligationKind::Ack, child_task1, child, None)
            .expect("child obl1");
        let _child_obl2 = state
            .create_obligation(ObligationKind::IoOp, child_task2, child, None)
            .expect("child obl2");

        // Commit root obligation BEFORE cancel
        let _ = state.commit_obligation(root_obl).expect("commit root obl");

        // Cancel the root (cascades to child)
        let _ = state.cancel_request(root, &CancelReason::user("test"), None);

        // Abort child_obl1 explicitly during cancellation
        let _ = state
            .abort_obligation(child_obl1, ObligationAbortReason::Cancel)
            .expect("abort child obl1");

        // Complete child tasks (child_obl2 will be orphaned → auto-aborted)
        state
            .task_mut(child_task1)
            .expect("child_task1")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(child_task1);

        state
            .task_mut(child_task2)
            .expect("child_task2")
            .complete(Outcome::Cancelled(CancelReason::parent_cancelled()));
        let _ = state.task_completed(child_task2);

        // Child should be closed
        let child_state_removed = state.regions.get(child.arena_index()).is_none();
        crate::assert_with_log!(
            child_state_removed,
            "child closed (removed)",
            true,
            child_state_removed
        );

        // Complete root task
        state
            .task_mut(root_task)
            .expect("root_task")
            .complete(Outcome::Cancelled(CancelReason::user("test")));
        let _ = state.task_completed(root_task);

        // Root should close (all children closed, tasks done, obligations resolved)
        let root_state_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_state_removed,
            "root closed after mixed resolution (removed)",
            true,
            root_state_removed
        );

        // No pending obligations
        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "zero pending",
            0usize,
            state.pending_obligation_count()
        );
        crate::test_complete!("mixed_obligation_resolution_during_cancel_cascade");
    }

    // ── asupersync-sipro: Regression tests for audit findings ────────────

    /// Test metrics that tracks region_closed calls.
    #[derive(Default)]
    struct RegionCloseMetrics {
        closed: Mutex<Vec<(RegionId, Duration)>>,
    }

    impl MetricsProvider for RegionCloseMetrics {
        fn task_spawned(&self, _: RegionId, _: TaskId) {}
        fn task_completed(&self, _: TaskId, _: OutcomeKind, _: Duration) {}
        fn region_created(&self, _: RegionId, _: Option<RegionId>) {}
        fn region_closed(&self, id: RegionId, lifetime: Duration) {
            self.closed.lock().push((id, lifetime));
        }
        fn cancellation_requested(&self, _: RegionId, _: CancelKind) {}
        fn drain_completed(&self, _: RegionId, _: Duration) {}
        fn deadline_set(&self, _: RegionId, _: Duration) {}
        fn deadline_exceeded(&self, _: RegionId) {}
        fn deadline_warning(&self, _: &str, _: &'static str, _: Duration) {}
        fn deadline_violation(&self, _: &str, _: Duration) {}
        fn deadline_remaining(&self, _: &str, _: Duration) {}
        fn checkpoint_interval(&self, _: &str, _: Duration) {}
        fn task_stuck_detected(&self, _: &str) {}
        fn obligation_created(&self, _: RegionId) {}
        fn obligation_discharged(&self, _: RegionId) {}
        fn obligation_leaked(&self, _: RegionId) {}
        fn scheduler_tick(&self, _: usize, _: Duration) {}
    }

    #[test]
    #[allow(clippy::significant_drop_tightening)]
    fn region_closed_metric_fires_on_close() {
        // Regression: advance_region_state did not call metrics.region_closed()
        // after complete_close(), causing active region gauge to grow monotonically.
        init_test("region_closed_metric_fires_on_close");
        let metrics = Arc::new(RegionCloseMetrics::default());
        let mut state = RuntimeState::new_with_metrics(metrics.clone());
        let root = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, root);

        // Close region: begin_close, complete task, advance
        {
            let region = state.regions.get(root.arena_index()).expect("root");
            region.begin_close(None);
        }
        state
            .task_mut(task)
            .expect("task")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(task);

        {
            let closed = metrics.closed.lock();
            crate::assert_with_log!(
                closed.len() == 1,
                "region_closed metric fired exactly once",
                1usize,
                closed.len()
            );
            crate::assert_with_log!(
                closed[0].0 == root,
                "correct region ID in metric",
                root,
                closed[0].0
            );
        }
        crate::test_complete!("region_closed_metric_fires_on_close");
    }

    #[test]
    fn leak_count_exact_for_multiple_obligations() {
        // Regression: handle_obligation_leaks was reentrant via
        // mark_obligation_leaked → advance_region_state → collect_obligation_leaks,
        // causing leak_count to inflate to N*(N+1)/2 instead of N.
        init_test("leak_count_exact_for_multiple_obligations");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);
        let region = state.create_root_region(Budget::INFINITE);
        let task = insert_task(&mut state, region);

        // Create 5 obligations on the same task — all will leak on completion
        for _ in 0..5 {
            state
                .create_obligation(ObligationKind::SendPermit, task, region, None)
                .expect("create obligation");
        }

        complete_task_ok(&mut state, task);

        // Without the reentrance guard, leak_count would be 5+4+3+2+1 = 15
        crate::assert_with_log!(
            state.leak_count() == 5,
            "leak_count is exactly N, not inflated by reentrance",
            5u64,
            state.leak_count()
        );
        crate::test_complete!("leak_count_exact_for_multiple_obligations");
    }

    #[test]
    fn nested_parent_leaks_are_not_suppressed_by_child_leak_handling() {
        // Regression: the old global `handling_leaks` boolean suppressed all
        // nested leak handling, not just duplicates of the current batch. When
        // a child leak closed the child region and advanced its parent into
        // `Finalizing`, the parent's distinct pending obligations were skipped
        // and the parent region stayed stuck with leaked-but-unhandled state.
        init_test("nested_parent_leaks_are_not_suppressed_by_child_leak_handling");
        let mut state = RuntimeState::new();
        state.set_obligation_leak_response(ObligationLeakResponse::Silent);

        let root = state.create_root_region(Budget::INFINITE);
        let child = create_child_region(&mut state, root);
        let root_task = insert_task(&mut state, root);
        let child_task = insert_task(&mut state, child);

        state
            .create_obligation(ObligationKind::Lease, root_task, root, None)
            .expect("root obligation");
        state
            .create_obligation(ObligationKind::Ack, child_task, child, None)
            .expect("child obligation");

        state
            .regions
            .get(root.arena_index())
            .expect("root missing")
            .begin_close(None);
        state
            .regions
            .get(child.arena_index())
            .expect("child missing")
            .begin_close(None);

        // Simulate a stale parent-cleanup gap: the task is already unlinked,
        // but its obligation is still pending. Child leak handling will advance
        // the parent into Finalizing, where the parent's leak must still be
        // processed even though we are already inside the child's leak handler.
        let _ = state.remove_task(root_task);
        state
            .regions
            .get(root.arena_index())
            .expect("root missing")
            .remove_task(root_task);

        state
            .task_mut(child_task)
            .expect("child task missing")
            .complete(Outcome::Ok(()));
        let _ = state.task_completed(child_task);

        crate::assert_with_log!(
            state.pending_obligation_count() == 0,
            "all nested leaks resolved",
            0usize,
            state.pending_obligation_count()
        );
        crate::assert_with_log!(
            state.leak_count() == 2,
            "both child and parent leaks counted exactly once",
            2u64,
            state.leak_count()
        );
        let leak_events = state
            .trace
            .snapshot()
            .into_iter()
            .filter(|event| event.kind == TraceEventKind::ObligationLeak)
            .count();
        crate::assert_with_log!(
            leak_events == 2,
            "trace records both nested leaks",
            2usize,
            leak_events
        );
        let root_removed = state.regions.get(root.arena_index()).is_none();
        crate::assert_with_log!(
            root_removed,
            "parent region closes after nested leak handling",
            true,
            root_removed
        );

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

    // =========================================================================
    // Wave 58 – pure data-type trait coverage (snapshot types)
    // =========================================================================

    #[test]
    fn budget_snapshot_debug_clone_copy() {
        let s = BudgetSnapshot {
            deadline: Some(1_000_000),
            poll_quota: 128,
            cost_quota: None,
            priority: 5,
        };
        let dbg = format!("{s:?}");
        assert!(dbg.contains("BudgetSnapshot"), "{dbg}");
        let copied = s;
        let cloned = s;
        assert_eq!(copied.priority, cloned.priority);
    }

    #[test]
    fn cancel_kind_snapshot_debug_clone() {
        let k = CancelKindSnapshot::User;
        let dbg = format!("{k:?}");
        assert!(dbg.contains("User"), "{dbg}");
        let cloned = k;
        let dbg2 = format!("{cloned:?}");
        assert_eq!(dbg, dbg2);
    }

    #[test]
    fn region_state_snapshot_debug_clone() {
        let s = RegionStateSnapshot::Open;
        let dbg = format!("{s:?}");
        assert!(dbg.contains("Open"), "{dbg}");
        let cloned = s;
        let dbg2 = format!("{cloned:?}");
        assert_eq!(dbg, dbg2);
    }

    #[test]
    fn event_data_snapshot_preserves_worker_replay_linkage() {
        let task = TaskId::from_arena(ArenaIndex::new(1, 2));
        let region = RegionId::from_arena(ArenaIndex::new(3, 4));
        let obligation = ObligationId::from_arena(ArenaIndex::new(5, 6));
        let snapshot = EventDataSnapshot::from_trace_data(&TraceData::Worker {
            worker_id: "worker-a".to_string(),
            job_id: 77,
            decision_seq: 91,
            replay_hash: 0x00C0_FFEE,
            task,
            region,
            obligation,
        });

        match snapshot {
            EventDataSnapshot::Worker {
                worker_id,
                job_id,
                decision_seq,
                replay_hash,
                task: task_snapshot,
                region: region_snapshot,
                obligation: obligation_snapshot,
            } => {
                assert_eq!(worker_id, "worker-a");
                assert_eq!(job_id, 77);
                assert_eq!(decision_seq, 91);
                assert_eq!(replay_hash, 0x00C0_FFEE);
                assert_eq!(task_snapshot, IdSnapshot::from(task));
                assert_eq!(region_snapshot, IdSnapshot::from(region));
                assert_eq!(obligation_snapshot, IdSnapshot::from(obligation));
            }
            other => panic!("expected worker snapshot, got {other:?}"), // ubs:ignore - test assertion
        }
    }

    // ============================================================================
    // Metamorphic Tests for Region Close Idempotency
    // ============================================================================

    mod metamorphic_region_close_tests {
        use super::*;
        use crate::lab::config::LabConfig;
        use crate::lab::runtime::LabRuntime;
        use proptest::prelude::*;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

        /// Test data structure for capturing region close outcomes.
        #[derive(Debug, Clone, PartialEq)]
        struct RegionCloseOutcome {
            region_id: RegionId,
            close_successful: bool,
            final_state: crate::record::region::RegionState,
            task_count: usize,
            child_count: usize,
            pending_obligations: usize,
            cancel_reason: Option<CancelReason>,
        }

        impl RegionCloseOutcome {
            fn from_region(runtime: &LabRuntime, region_id: RegionId) -> Option<Self> {
                let state = &runtime.state;
                let regions = &state.regions;

                regions.get(region_id.arena_index()).map(|region| Self {
                    region_id,
                    close_successful: region.state() == crate::record::region::RegionState::Closed,
                    final_state: region.state(),
                    task_count: region.task_count(),
                    child_count: region.child_count(),
                    pending_obligations: region.pending_obligations(),
                    cancel_reason: region.cancel_reason(),
                })
            }
        }

        fn cancel_reason_for_variant(variant: u8) -> CancelReason {
            match variant {
                0 => CancelReason::default(),
                1 => CancelReason::timeout(),
                2 => CancelReason::resource_unavailable(),
                _ => CancelReason::user("redundant close"),
            }
        }

        /// Metamorphic Relation 1: Region close idempotency
        /// Property: Calling region.close() twice should return the same outcome the second time
        #[test]
        fn mr_region_close_idempotency() {
            proptest!(|(seed in any::<u64>())| {
                let config = LabConfig::new(seed).max_steps(1000);
                let mut runtime = LabRuntime::new(config);

                // Create a region and immediately close it
                let region_id = runtime.state.create_root_region(Budget::default());

                // First close attempt
                let _first_close_result = {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    let begin_result = region.begin_close(None);

                    // Transition through states
                    if begin_result {
                        let _ = region.begin_finalize();
                        region.complete_close()
                    } else {
                        false
                    }
                };

                let first_outcome = RegionCloseOutcome::from_region(&runtime, region_id);

                // Second close attempt (should be idempotent)
                let second_close_result = {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    region.complete_close()  // Should return false (already closed)
                };

                let second_outcome = RegionCloseOutcome::from_region(&runtime, region_id);

                // Metamorphic relation: Second call should be no-op
                prop_assert_eq!(second_close_result, false, "Second close should return false (idempotent)");
                prop_assert_eq!(&first_outcome, &second_outcome, "Region state should be unchanged by second close");

                if let Some(outcome) = first_outcome {
                    prop_assert_eq!(outcome.final_state, crate::record::region::RegionState::Closed);
                }
            });
        }

        /// Metamorphic Relation 2: Cancelling closed region is no-op
        /// Property: Attempting to cancel an already closed region should have no effect
        #[test]
        fn mr_cancel_closed_region_noop() {
            proptest!(|(seed in any::<u64>(), cancel_reason_variant in 0..3u8)| {
                let config = LabConfig::new(seed).max_steps(1000);
                let mut runtime = LabRuntime::new(config);

                let region_id = runtime.state.create_root_region(Budget::default());

                // Close the region first
                {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    let _ = region.begin_close(None);
                    let _ = region.begin_finalize();
                    let _ = region.complete_close();
                }

                let outcome_before_cancel = RegionCloseOutcome::from_region(&runtime, region_id);

                // Attempt to cancel the already-closed region
                let cancel_reason = cancel_reason_for_variant(cancel_reason_variant);

                {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    let _ = region.begin_close(Some(cancel_reason));  // Should be no-op
                }

                let outcome_after_cancel = RegionCloseOutcome::from_region(&runtime, region_id);

                // Metamorphic relation: Cancel should be no-op on closed region
                prop_assert_eq!(outcome_before_cancel, outcome_after_cancel,
                    "Cancelling closed region should have no effect");
            });
        }

        /// Metamorphic Relation 2b: Closed regions preserve their terminal cancel cause
        /// Property: Once a region reaches Closed, redundant close attempts cannot rewrite the terminal reason
        #[test]
        fn mr_closed_region_preserves_terminal_cancel_reason() {
            proptest!(|(seed in any::<u64>(), initial_variant in 0..4u8, followup_variant in 0..4u8)| {
                let config = LabConfig::new(seed).max_steps(1000);
                let mut runtime = LabRuntime::new(config);

                let region_id = runtime.state.create_root_region(Budget::default());
                let initial_reason = cancel_reason_for_variant(initial_variant);
                let followup_reason = cancel_reason_for_variant(followup_variant);

                {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    let _ = region.begin_close(Some(initial_reason.clone()));
                    let _ = region.begin_finalize();
                    let _ = region.complete_close();
                }

                let outcome_before_redundant_close = RegionCloseOutcome::from_region(&runtime, region_id);

                {
                    let state = &mut runtime.state;
                    let region = state.regions.get_mut(region_id.arena_index()).unwrap();
                    let redundant_close_result = region.begin_close(Some(followup_reason));
                    prop_assert!(!redundant_close_result, "redundant close on terminal region should be a no-op");
                }

                let outcome_after_redundant_close = RegionCloseOutcome::from_region(&runtime, region_id);

                prop_assert_eq!(
                    &outcome_before_redundant_close,
                    &outcome_after_redundant_close,
                    "redundant close must preserve the terminal cancel reason and region snapshot"
                );

                if let Some(outcome) = &outcome_after_redundant_close {
                    prop_assert_eq!(
                        outcome.cancel_reason.clone(),
                        Some(initial_reason),
                        "terminal cancel reason should remain the original close cause"
                    );
                }
            });
        }

        /// Metamorphic Relation 3: Child region close containment
        /// Property: Child region close never escapes parent before parent.close()
        #[test]
        fn mr_child_close_containment() {
            proptest!(|(seed in any::<u64>(), num_children in 1..5usize)| {
                let config = LabConfig::new(seed).max_steps(2000);
                let mut runtime = LabRuntime::new(config);

                let parent_id = runtime.state.create_root_region(Budget::default());
                let mut child_ids = Vec::new();

                // Create child regions
                for _ in 0..num_children {
                    let child_id = runtime.state.create_child_region(parent_id, Budget::default()).unwrap();
                    child_ids.push(child_id);
                }

                // Close all children first
                for &child_id in &child_ids {
                    let state = &mut runtime.state;
                    let child = state.regions.get_mut(child_id.arena_index()).unwrap();
                    let _ = child.begin_close(None);
                    let _ = child.begin_finalize();
                    let _ = child.complete_close();
                }

                // Verify children are closed but parent is still open
                let parent_outcome_before = RegionCloseOutcome::from_region(&runtime, parent_id);
                prop_assert!(parent_outcome_before.is_some());

                if let Some(outcome) = parent_outcome_before {
                    // Parent should still be open (children closed first)
                    prop_assert_ne!(outcome.final_state, crate::record::region::RegionState::Closed,
                        "Parent should not auto-close when children close");
                }

                // Now close parent
                {
                    let state = &mut runtime.state;
                    let parent = state.regions.get_mut(parent_id.arena_index()).unwrap();
                    let _ = parent.begin_close(None);
                    let _ = parent.begin_finalize();
                    let _ = parent.complete_close();
                }

                let parent_outcome_after = RegionCloseOutcome::from_region(&runtime, parent_id);

                // Metamorphic relation: Parent close should succeed after all children are closed
                prop_assert!(parent_outcome_after.is_some());
                if let Some(outcome) = parent_outcome_after {
                    prop_assert_eq!(outcome.final_state, crate::record::region::RegionState::Closed);
                    prop_assert_eq!(outcome.child_count, 0, "Closed parent should have no children");
                }
            });
        }

        /// Metamorphic Relation 4: No-orphan invariant under concurrent spawn+close
        /// Property: Concurrent spawn+close races never produce orphan tasks
        #[test]
        fn mr_no_orphan_invariant() {
            proptest!(|(seed in any::<u64>(), num_operations in 5..20usize)| {
                let config = LabConfig::new(seed).max_steps(3000).worker_count(2);
                let mut runtime = LabRuntime::new(config);

                let region_id = runtime.state.create_root_region(Budget::default());
                let spawned_tasks = Arc::new(AtomicUsize::new(0));
                let completed_tasks = Arc::new(AtomicUsize::new(0));
                let close_attempted = Arc::new(AtomicBool::new(false));

                // Simulate concurrent spawn and close operations
                for i in 0..num_operations {
                    let spawned_count = spawned_tasks.clone();
                    let completed_count = completed_tasks.clone();
                    let close_flag = close_attempted.clone();

                    if i % 3 == 0 && !close_flag.load(Ordering::Relaxed) {
                        // Attempt to close region
                        close_flag.store(true, Ordering::Relaxed);
                        let _close_task = futures_lite::future::block_on(async move {
                            // Simulate close operation
                            Ok::<(), ()>(())
                        });
                    } else {
                        // Spawn task in region
                        let task_spawned = spawned_count.clone();
                        let task_completed = completed_count.clone();

                        let task_result = futures_lite::future::block_on(async move {
                            task_spawned.fetch_add(1, Ordering::Relaxed);

                            // Simulate some work
                            task_completed.fetch_add(1, Ordering::Relaxed);
                            Ok::<(), ()>(())
                        });

                        // Task spawn might fail if region is closing/closed
                        if task_result.is_err() {
                            // This is expected behavior when region is closing
                        }
                    }
                }

                // Run the scenario
                runtime.run_until_quiescent();

                // Verify no-orphan invariant
                let region_outcome = RegionCloseOutcome::from_region(&runtime, region_id);

                if let Some(outcome) = region_outcome {
                    // Metamorphic relation: No tasks should be orphaned
                    prop_assert_eq!(outcome.task_count, 0,
                        "Region should have no remaining tasks (no orphans)");

                    // If region closed successfully, all spawned tasks should be accounted for
                    if outcome.close_successful {
                        let spawned = spawned_tasks.load(Ordering::Relaxed);
                        let completed = completed_tasks.load(Ordering::Relaxed);

                        // All spawned tasks should complete or be cancelled (no orphans)
                        prop_assert!(spawned >= completed,
                            "Completed tasks should not exceed spawned tasks");
                    }
                }
            });
        }

        /// Composite metamorphic relation: Multiple close operations with different orderings
        /// Tests interaction between all four metamorphic relations
        #[test]
        fn mr_composite_region_lifecycle() {
            proptest!(|(seed in any::<u64>(), operation_sequence in prop::collection::vec(0..4u8, 3..10))| {
                let config = LabConfig::new(seed).max_steps(5000);
                let mut runtime = LabRuntime::new(config);

                let parent_id = runtime.state.create_root_region(Budget::default());
                let child_id = runtime.state.create_child_region(parent_id, Budget::default()).unwrap();

                let mut parent_close_count = 0;
                let mut child_close_count = 0;
                let mut cancel_attempts = 0;

                // Execute operation sequence
                for &op in &operation_sequence {
                    match op {
                        0 => {
                            // Close parent (should fail if child not closed)
                            let state = &mut runtime.state;
                            if let Some(parent) = state.regions.get_mut(parent_id.arena_index()) {
                                if parent.begin_close(None) {
                                    let _ = parent.begin_finalize();
                                    let _ = parent.complete_close();
                                }
                                parent_close_count += 1;
                            }
                        }
                        1 => {
                            // Close child
                            let state = &mut runtime.state;
                            if let Some(child) = state.regions.get_mut(child_id.arena_index()) {
                                if child.begin_close(None) {
                                    let _ = child.begin_finalize();
                                    let _ = child.complete_close();
                                }
                                child_close_count += 1;
                            }
                        }
                        2 => {
                            // Cancel parent
                            let state = &mut runtime.state;
                            if let Some(parent) = state.regions.get_mut(parent_id.arena_index()) {
                                let _ = parent.begin_close(Some(CancelReason::user("close")));
                                cancel_attempts += 1;
                            }
                        }
                        3 => {
                            // Cancel child
                            let state = &mut runtime.state;
                            if let Some(child) = state.regions.get_mut(child_id.arena_index()) {
                                let _ = child.begin_close(Some(CancelReason::user("close")));
                                cancel_attempts += 1;
                            }
                        }
                        _ => unreachable!(),
                    }
                }

                // Verify final states satisfy all metamorphic relations
                let parent_outcome = RegionCloseOutcome::from_region(&runtime, parent_id);
                let child_outcome = RegionCloseOutcome::from_region(&runtime, child_id);

                // MR1 (Idempotency): Multiple close attempts should be handled gracefully
                prop_assert!(parent_close_count >= 0 && child_close_count >= 0);

                // MR2 (Cancel no-op): Cancel attempts on closed regions should be no-ops
                prop_assert!(cancel_attempts >= 0);

                // MR3 (Containment): If both are closed, child must have closed first (or together)
                if let (Some(parent), Some(child)) = (parent_outcome, child_outcome) {
                    if parent.close_successful && child.close_successful {
                        // Both closed successfully - this satisfies containment
                        prop_assert_eq!(parent.child_count, 0, "Closed parent should have no children");
                    }

                    if parent.close_successful {
                        // MR4 (No orphans): Closed regions should have no remaining tasks
                        prop_assert_eq!(parent.task_count, 0, "Closed parent should have no tasks");
                    }

                    if child.close_successful {
                        prop_assert_eq!(child.task_count, 0, "Closed child should have no tasks");
                    }
                }
            });
        }
    }

    mod metamorphic_cancel_cause_chain_tests {
        use super::*;
        use proptest::prelude::*;
        use std::collections::HashMap;

        fn reason_from_variant(variant: u8) -> CancelReason {
            match variant {
                0 => CancelReason::deadline().with_message("root deadline"),
                1 => CancelReason::timeout().with_message("rpc timeout"),
                2 => CancelReason::resource_unavailable().with_message("peer unavailable"),
                _ => CancelReason::user("operator stop"),
            }
        }

        #[derive(Debug, Clone, PartialEq)]
        struct BranchCancelSnapshot {
            branch_region_reason: CancelReason,
            leaf_region_reason: CancelReason,
            branch_task_reason: CancelReason,
            leaf_task_reason: CancelReason,
        }

        fn branch_cancel_snapshot_with_sibling_noise(
            sibling_count: usize,
            reason: &CancelReason,
        ) -> BranchCancelSnapshot {
            let mut state = RuntimeState::new();
            state.set_cancel_attribution_config(CancelAttributionConfig::new(8, usize::MAX));

            let root = state.create_root_region(Budget::INFINITE);
            let branch = create_child_region(&mut state, root);
            let leaf = create_child_region(&mut state, branch);
            let branch_task = insert_task(&mut state, branch);
            let leaf_task = insert_task(&mut state, leaf);

            for _ in 0..sibling_count {
                let sibling = create_child_region(&mut state, root);
                let _ = insert_task(&mut state, sibling);
                let niece = create_child_region(&mut state, sibling);
                let _ = insert_task(&mut state, niece);
            }

            let _ = state.cancel_request(branch, reason, None);

            let branch_region_reason = state
                .regions
                .get(branch.arena_index())
                .and_then(RegionRecord::cancel_reason)
                .expect("branch cancel reason missing");
            let leaf_region_reason = state
                .regions
                .get(leaf.arena_index())
                .and_then(RegionRecord::cancel_reason)
                .expect("leaf cancel reason missing");
            let branch_task_reason = match &state
                .tasks
                .get(branch_task.arena_index())
                .expect("branch task missing")
                .state
            {
                TaskState::CancelRequested { reason, .. } => reason.clone(),
                other => panic!("expected branch task to be cancelling, got {other:?}"),
            };
            let leaf_task_reason = match &state
                .tasks
                .get(leaf_task.arena_index())
                .expect("leaf task missing")
                .state
            {
                TaskState::CancelRequested { reason, .. } => reason.clone(),
                other => panic!("expected leaf task to be cancelling, got {other:?}"),
            };

            BranchCancelSnapshot {
                branch_region_reason,
                leaf_region_reason,
                branch_task_reason,
                leaf_task_reason,
            }
        }

        #[test]
        fn mr_cancel_cause_chain_tracks_full_lineage_without_truncation() {
            proptest!(|(
                nesting_depth in 1..7usize,
                extra_depth_budget in 0..3usize,
                reason_variant in 0..4u8
            )| {
                let mut state = RuntimeState::new();
                let full_lineage_depth = nesting_depth + 1;
                state.set_cancel_attribution_config(CancelAttributionConfig::new(
                    full_lineage_depth + extra_depth_budget,
                    usize::MAX,
                ));

                let root = state.create_root_region(Budget::INFINITE);
                let mut lineage = vec![root];
                for _ in 0..nesting_depth {
                    let parent = *lineage.last().expect("lineage has root");
                    let child = create_child_region(&mut state, parent);
                    lineage.push(child);
                }

                let leaf = *lineage.last().expect("leaf region missing");
                let leaf_task = insert_task(&mut state, leaf);
                let original_reason = reason_from_variant(reason_variant);
                let expected_root_kind = original_reason.kind;
                let expected_root_message = original_reason.message.clone();

                let _ = state.cancel_request(root, &original_reason, None);

                for (depth_idx, &region_id) in lineage.iter().enumerate() {
                    let region_record = state
                        .regions
                        .get(region_id.arena_index())
                        .expect("region missing");
                    let region_reason = region_record.cancel_reason();
                    let reason = region_reason
                        .as_ref()
                        .expect("region cancel reason missing");

                    prop_assert_eq!(
                        reason.chain_depth(),
                        depth_idx + 1,
                        "depth {} should expose the full ancestry",
                        depth_idx
                    );
                    prop_assert!(
                        !reason.any_truncated(),
                        "full-depth attribution should not truncate at depth {}",
                        depth_idx
                    );

                    if depth_idx == 0 {
                        prop_assert_eq!(reason.kind, expected_root_kind);
                    } else {
                        prop_assert_eq!(reason.kind, CancelKind::ParentCancelled);
                        prop_assert_eq!(reason.origin_region, lineage[depth_idx - 1]);
                    }

                    let root_cause = reason.root_cause();
                    prop_assert_eq!(root_cause.kind, expected_root_kind);
                    prop_assert_eq!(
                        root_cause.message.as_deref(),
                        expected_root_message.as_deref()
                    );
                }

                let leaf_task_record = state.tasks.get(leaf_task.arena_index()).expect("task missing");
                match &leaf_task_record.state {
                    TaskState::CancelRequested { reason, .. } => {
                        prop_assert_eq!(reason.kind, CancelKind::ParentCancelled);
                        prop_assert_eq!(reason.origin_region, lineage[lineage.len() - 2]);
                        prop_assert_eq!(reason.chain_depth(), full_lineage_depth);
                        prop_assert!(!reason.any_truncated());
                        prop_assert_eq!(reason.root_cause().kind, expected_root_kind);
                        prop_assert_eq!(
                            reason.root_cause().message.as_deref(),
                            expected_root_message.as_deref()
                        );
                    }
                    other => {
                        prop_assert!(false, "expected CancelRequested task state, got {other:?}");
                    }
                }
            });
        }

        #[test]
        fn mr_parent_cancel_schedules_ancestors_before_descendants() {
            proptest!(|(
                child_count in 1..5usize,
                grandchildren_per_child in 1..4usize,
                reason_variant in 0..4u8
            )| {
                let mut state = RuntimeState::new();
                let root = state.create_root_region(Budget::INFINITE);
                let root_task = insert_task(&mut state, root);
                let mut depth_by_task = HashMap::from([(root_task, 0usize)]);

                for _ in 0..child_count {
                    let child = create_child_region(&mut state, root);
                    let child_task = insert_task(&mut state, child);
                    depth_by_task.insert(child_task, 1);

                    for _ in 0..grandchildren_per_child {
                        let grandchild = create_child_region(&mut state, child);
                        let grandchild_task = insert_task(&mut state, grandchild);
                        depth_by_task.insert(grandchild_task, 2);
                    }
                }

                let scheduled = state.cancel_request(root, &reason_from_variant(reason_variant), None);
                prop_assert_eq!(
                    scheduled.len(),
                    depth_by_task.len(),
                    "initial cancel cascade should schedule each task exactly once"
                );

                let scheduled_depths: Vec<_> = scheduled
                    .iter()
                    .map(|(task_id, _priority)| {
                        *depth_by_task
                            .get(task_id)
                            .expect("scheduled task missing from depth map")
                    })
                    .collect();
                prop_assert_eq!(scheduled_depths.first().copied(), Some(0));
                prop_assert!(
                    scheduled_depths.windows(2).all(|pair| pair[0] <= pair[1]),
                    "cancel scheduling should not visit descendants before ancestors: {scheduled_depths:?}"
                );
            });
        }

        #[test]
        fn mr_cancel_depth_profile_is_reason_invariant() {
            proptest!(|(
                child_count in 1..5usize,
                grandchildren_per_child in 1..4usize,
                lhs_reason_variant in 0..4u8,
                rhs_reason_variant in 0..4u8
            )| {
                let build_depth_profile = |reason_variant: u8| {
                    let mut state = RuntimeState::new();
                    let root = state.create_root_region(Budget::INFINITE);
                    let root_task = insert_task(&mut state, root);
                    let mut depth_by_task = HashMap::from([(root_task, 0usize)]);

                    for _ in 0..child_count {
                        let child = create_child_region(&mut state, root);
                        let child_task = insert_task(&mut state, child);
                        depth_by_task.insert(child_task, 1);

                        for _ in 0..grandchildren_per_child {
                            let grandchild = create_child_region(&mut state, child);
                            let grandchild_task = insert_task(&mut state, grandchild);
                            depth_by_task.insert(grandchild_task, 2);
                        }
                    }

                    state
                        .cancel_request(root, &reason_from_variant(reason_variant), None)
                        .into_iter()
                        .map(|(task_id, _priority)| {
                            *depth_by_task
                                .get(&task_id)
                                .expect("scheduled task missing from depth map")
                        })
                        .collect::<Vec<_>>()
                };

                let lhs_profile = build_depth_profile(lhs_reason_variant);
                let rhs_profile = build_depth_profile(rhs_reason_variant);

                prop_assert_eq!(
                    lhs_profile,
                    rhs_profile,
                    "cancel reason variants should not perturb ancestor-before-descendant scheduling"
                );
            });
        }

        #[test]
        fn mr_cancel_cause_chain_is_stable_under_sibling_noise() {
            proptest!(|(sibling_count in 1..5usize, reason_variant in 0..4u8)| {
                let reason = reason_from_variant(reason_variant);
                let baseline = branch_cancel_snapshot_with_sibling_noise(0, &reason);
                let noisy = branch_cancel_snapshot_with_sibling_noise(sibling_count, &reason);
                prop_assert_eq!(
                    noisy,
                    baseline,
                    "sibling regions outside the cancelled branch should not perturb cause chains"
                );
            });
        }

        #[test]
        fn mr_cancel_request_after_close_preserves_terminal_reason() {
            proptest!(|(initial_variant in 0..4u8, followup_variant in 0..4u8)| {
                let mut state = RuntimeState::new();
                let region_id = state.create_root_region(Budget::INFINITE);
                let initial_reason = reason_from_variant(initial_variant);
                let followup_reason = reason_from_variant(followup_variant);

                {
                    let region = state
                        .regions
                        .get_mut(region_id.arena_index())
                        .expect("region missing");
                    prop_assert!(region.begin_close(Some(initial_reason.clone())));
                    prop_assert!(region.begin_finalize());
                    prop_assert!(region.complete_close());
                }

                let tasks_to_cancel = state.cancel_request(region_id, &followup_reason, None);
                let region = state
                    .regions
                    .get(region_id.arena_index())
                    .expect("region missing");

                prop_assert!(tasks_to_cancel.is_empty());
                prop_assert_eq!(region.state(), crate::record::region::RegionState::Closed);
                prop_assert_eq!(region.cancel_reason(), Some(initial_reason));
            });
        }
    }
}