aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Scheduler for coordinating transfer execution.
//!
//! The scheduler holds transfers and polls them for work, maintaining control over
//! ordering and admission until the moment of execution. This enables priority
//! changes, cancellation, adaptive concurrency, and memory bounding.
//!
//! # Scheduling Model
//!
//! Transfers are state machines that implement [`Transfer`](crate::transfer::Transfer). The scheduler polls
//! them via `poll_work()` when capacity is available, receiving work items or
//! signals that the transfer is blocked (`Pending`) or finished (`Done`).
//!
//! Work generation is event-driven. The scheduler generates work when a transfer
//! arrives, is woken, work completes (freeing capacity), or the concurrency target
//! changes. It never polls on a timer.
//!
//! ```text
//!   enqueue ──► Transfers ──► Ready Set ──► generate_work() ──► Execution
//!                  ▲                                                │
//!   wake ─────────►│                                                │
//!                  │                                                │
//!                  └──────────── on_completion() ◄──────────────────┘
//! ```
//!
//! # Fair Scheduling (CFS)
//!
//! When multiple transfers are ready, the scheduler uses Completely Fair Scheduling.
//! Each transfer accumulates virtual runtime as it generates work. The transfer with
//! the lowest virtual runtime is selected next. Priority acts as a weight: higher
//! priority means slower accumulation, so the transfer generates more work before
//! yielding to others.
//!
//! # Backpressure
//!
//! Transfers that cannot produce dispatchable work return `Pending` from
//! `poll_work()`. The scheduler stops polling them until `wake()` is called. Work
//! whose readiness is discovered only after dispatch may instead return
//! [`WorkOutcome::Yielded`]. That retires its execution slot without reporting an
//! I/O operation or failure to the concurrency controller; transfer state must
//! already have retained any continuation or retracted the speculative operation.
//!
//! # Threading and Cost
//!
//! Scheduler work runs on the caller's thread. `on_completion` and `wake` drive
//! `generate_work` synchronously on whatever thread invoked them - typically a
//! managed execution thread. This is a deliberate choice for hot-path throughput
//! (no channel hop, warm caches, parallel drive across transfers), gated on the
//! constraints below holding.
//!
//! - **`poll_work` is synchronous and short.** No `.await`, no blocking I/O, no
//!   unbounded loops. Cost is O(1) per call with a bounded critical section on
//!   state. Long `poll_work` calls pin the caller's runtime, preventing it from
//!   polling its own async tasks (including in-flight SDK requests).
//! - **At most one thread is inside `poll_work(desc)` at a time.** Enforced by a
//!   claim atom on [`TransferDescriptor`]
//!   and the atomicity of `ReadySet`'s pop. `ReadySet::insert` is CAS-gated on
//!   this claim: a concurrent wake calling `insert` while the descriptor is
//!   already in the ready set (or being polled) finds claim=true and silently
//!   no-ops, preventing duplicate ready-set entries. Concurrent `poll_work` is
//!   prevented by `SkipMap`'s atomic dequeue, not by the claim.
//!
//!   The claim is asserted on first insert and held continuously across all
//!   subsequent `pop` -> `poll_work` -> `reinsert_under_claim` cycles in the
//!   `Ready` path, until `poll_work` returns `Pending` or `Done` (at which
//!   point the claim is explicitly released). This keeps the per-transfer
//!   state mutex effectively uncontended in steady state and lets a transfer
//!   making continuous progress avoid CAS overhead on each iteration.
//! - **Ready set entries are unique per transfer id.** Duplicates re-open the
//!   single-poll invariant and produce lock-contention storms under burst
//!   completions.
//! - **Composite transfers pay their own per-call cost.** A composite's
//!   `poll_work` may recursively call [`Scheduler::enqueue_transfer`] to spawn
//!   children. The per-call fan-out must be bounded - cost is
//!   `O(batch × enqueue_cost)`.
//! - **`execute` is the only async surface.** State locks must not be held across
//!   `.await`. Mid-execution the transfer may call `scheduler.wake(id)` to
//!   re-queue itself if intra-execute state changes unblock work.
//!
//! # State Machine Contracts
//!
//! A [`Transfer`](crate::transfer::Transfer) implementation must uphold:
//! - **Failed lifecycle**: record the error before returning a failure outcome, then
//!   either end the transfer and signal termination, or keep it active with a wake
//!   path until `poll_work` ends it.
//! - **Poll-time pending/wake obligation**: every `PollWork::Pending` must record
//!   its cause through `TransferContext::set_pending` and have a future wake path.
//!   Transfer-owned mutations use the edge-triggered
//!   `lock → mutate → unlock → try_wake` pattern; registered futures use the
//!   context waker. See [`crate::transfer::TransferContext`] for the protocol.
//! - **Execution-yield obligation**: before returning `WorkOutcome::Yielded`, a
//!   transfer must reconcile the dispatched work exactly once. A retained
//!   continuation keeps its progress and wake state; retracted work leaves no
//!   continuation behind.
//! - **Panic safety**: `execute` panics are caught by the runtime's
//!   `catch_unwind` wrapper and converted to a terminal transition.
//!   `poll_work` panics are caught by the scheduler itself inside
//!   `generate_work`, which force-terminates the panicking transfer
//!   (cascading to children) and continues processing other transfers.
//!
//! See `docs/design/scheduler.md` for the long-form design discussion,
//! invariants, and case studies.

use super::CompletionSample;
use crate::telemetry;
use crate::transfer::{BoxTransfer, PollWork, TransferId, WorkOutcome};

use crate::runtime::sync::{Submission, SubmissionQueue};
use crate::runtime::ScheduledWork;
use crate::scheduler::descriptor::{ClaimGuard, TransferDescriptor};
use crate::scheduler::ready_set::{OrphanedChild, ReadySet};
use std::collections::HashMap;

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock, Weak};
use std::time::Duration;

/// Batch size for work generated and submitted in a single round
const SUBMISSION_QUEUE_SIZE: usize = 64;

/// Maximum *proactive* generation passes a single `generate_work` entry runs
/// before retiring and leaning on the completion edge to re-drive (when one is
/// guaranteed). Bounds the per-`on_completion` cost so one execution thread
/// cannot stay engaged as the runner indefinitely under sustained wakes; the
/// runner role then rotates to whichever thread next completes work. The
/// `dispatched == 0` corner has no completion edge, so the bound does not apply
/// there — the runner keeps draining (self-bounded by finite published work).
/// Loom-verified in `gate.rs` (`..._bounded_handoff*`).
const MAX_GENERATION_PASSES: usize = 3;

use super::gate::GenerateWorkGate;

/// Event-driven scheduler for coordinating transfer work.
///
/// Clone is cheap (Arc).
#[derive(Clone)]
pub(crate) struct Scheduler(Arc<SchedulerInner>);

struct SchedulerInner {
    /// Transfers registered for scheduling.
    transfers: RwLock<HashMap<TransferId, TransferDescriptor>>,
    ready_set: ReadySet,
    handle: Weak<crate::client::Handle>,
    dispatched: AtomicUsize,
    /// Set when registry removal may leave only dispatched work keeping the
    /// scheduler active. The final dispatch consumes this candidate after
    /// verifying the registry is still empty.
    idle_candidate: AtomicBool,
    submission_queue: SubmissionQueue<ScheduledWork>,
    /// Admits one work-generation runner and coalesces requests without losing
    /// a wake. See [`GenerateWorkGate`].
    generate_work_gate: GenerateWorkGate,
}

impl std::fmt::Debug for Scheduler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scheduler").finish_non_exhaustive()
    }
}

/// Result of a [`Scheduler::cancel_transfer`] call.
///
/// Carries the descriptors that were cancelled (the target and any
/// depth-1 children). Drop the value for fire-and-forget cancel; await
/// [`Cancellation::wait_for_idle`] to wait for in-flight executing
/// work to drain before continuing. Pending (queued but not yet
/// dispatched) work is purged synchronously during cancel; only work
/// that was already dispatched needs draining.
pub(crate) struct Cancellation {
    pub(super) target: Option<TransferDescriptor>,
    pub(super) children: Vec<TransferDescriptor>,
}

impl Cancellation {
    /// Wait until the cancelled parent and each cancelled child report idle
    /// (no queued or executing work), checking each descriptor in turn.
    pub(crate) async fn wait_for_idle(self) {
        if let Some(d) = self.target {
            d.wait_for_idle().await;
        }
        for d in self.children {
            d.wait_for_idle().await;
        }
    }
}

impl Scheduler {
    pub(crate) fn new(handle: Weak<crate::client::Handle>) -> Self {
        Scheduler(Arc::new(SchedulerInner {
            transfers: RwLock::new(HashMap::new()),
            ready_set: ReadySet::new(),
            handle,
            dispatched: AtomicUsize::new(0),
            idle_candidate: AtomicBool::new(false),
            submission_queue: SubmissionQueue::new(SUBMISSION_QUEUE_SIZE),
            generate_work_gate: GenerateWorkGate::new(),
        }))
    }

    fn handle(&self) -> Arc<crate::client::Handle> {
        self.0
            .handle
            .upgrade()
            .expect("Handle dropped while scheduler active")
    }

    /// Called by the runtime when a worker picks up work.
    pub(crate) fn on_dispatch(&self) {
        self.handle().controller.on_dispatch();
    }

    /// Add a transfer and start generating work.
    ///
    /// Lock-ordering protocol: this method holds `transfers.write` while
    /// resolving the parent group via `by_group.read`. Together with
    /// `cancel_transfer` (which holds `transfers.write` across its
    /// `by_group.write`), the protocol prevents a child being orphaned
    /// in `transfers` after its parent group is removed. See
    /// `loom_tests::fixed_dance_no_orphan` at the bottom of this file.
    pub(crate) fn enqueue_transfer(&self, transfer: BoxTransfer) {
        let tid = transfer.ctx().id;

        // Lock order: transfers.write -> by_group.read.
        //
        // We acquire transfers.write first, then resolve the parent group's
        // vruntime arc under by_group.read, then insert into transfers, all
        // within the same critical section. This serializes against
        // `cancel_transfer`, which holds transfers.write across its own
        // by_group.write call. Without this ordering, a concurrent
        // cancel_transfer could remove the parent's group between our
        // resolve_group_vruntime check and our transfers.insert, leaving
        // a child orphaned in transfers.
        //
        // ready_set.insert (below) is performed AFTER releasing transfers.write
        // and re-acquires by_group.read on its own. If the parent's group was
        // removed in that window, insert returns OrphanedChild and we cancel
        // the child via the existing fallback path.
        let (group_vruntime, desc) = {
            let mut transfers = self.0.transfers.write().unwrap();
            let group_vruntime = match self.0.ready_set.resolve_group_vruntime(&tid) {
                Some(gv) => gv,
                None => {
                    // Parent group gone (cancelled mid-spawn). Set the
                    // transfer's context to cancelled and signal terminal
                    // so its handle resolves. No need to insert into the
                    // transfers map since nothing will ever poll or wake
                    // this transfer.
                    drop(transfers);
                    let ctx = transfer.ctx();
                    ctx.set_cancelled();
                    transfer.on_terminal();
                    ctx.signal_terminal();
                    return;
                }
            };
            let desc = TransferDescriptor::new_with_vruntime(
                transfer,
                self.0.ready_set.min_vruntime(),
                group_vruntime.clone(),
            );
            transfers.insert(desc.id(), desc.clone());
            // Serialize activity publication with registry insertion. An idle
            // observer holds this same lock while publishing, so either it
            // reports idle first and this event supersedes it, or it observes
            // this transfer and declines to publish idle.
            self.0.idle_candidate.store(false, Ordering::SeqCst);
            self.handle().scheduler_work_registered();
            (group_vruntime, desc)
        };
        let _ = group_vruntime; // returned by resolve_group_vruntime, retained inside desc
        let id = desc.id();

        match self.0.ready_set.insert(desc) {
            Ok(()) => {}
            Err(OrphanedChild) => {
                // Parent's group was removed between transfers.write release
                // and ready_set.insert. Cancel the new transfer so its handle
                // resolves to a cancelled state, no leaked oneshot.
                self.cancel_transfer(id);
                return;
            }
        }

        tracing::debug!(target: telemetry::TARGET_SCHEDULING, tid = %id, "transfer enqueued");
        // Drive `generate_work` unless we're already inside it on this
        // thread (the parent's `poll_work` called `spawn_children` →
        // `enqueue_transfer`). The `GenerateWorkGate` handles both cases:
        //
        // 1. Re-entrancy: `try_acquire` returns None on the runner's own
        //    thread. Without this, the re-entrant frame would call
        //    `submission_queue.enter()`, incrementing the global `pending`
        //    counter. The outer frame's `submit()` then sees pending > 0 and
        //    waits for the nested submission to flush — but the nested frame
        //    can't flush until the outer frame returns. Deadlock.
        //
        // 2. Cross-thread serialization: only the runner pops from the ready
        //    set at a time, preserving priority ordering. Priority depends on
        //    sequential pop-poll-reinsert cycles (hi-priority re-enters at
        //    lower vruntime, gets popped again sooner). Concurrent pops would
        //    short-circuit this by draining the tree in parallel without
        //    giving transfers the chance to re-insert.
        //
        // The runner picks up the newly-inserted transfer on its current pass,
        // or on the extra pass our recorded request forces (case 1).
        self.generate_work();
    }

    /// Wake a transfer, moving it from pending to ready.
    ///
    /// Called by state machines when they transition from blocked to ready.
    /// Only generates work if transfer exists and was inserted to ready set.
    pub(crate) fn wake(&self, id: TransferId) {
        let desc = {
            let transfers = self.0.transfers.read().unwrap();
            transfers.get(&id).cloned()
        };
        match desc {
            Some(desc) => {
                // Mark wake_requested before insert: if a poll is in
                // flight, it will observe the flag in the release-and-
                // recheck path. Otherwise the insert (or no-op if
                // already queued) puts the descriptor back in the
                // ready set.
                desc.record_wake_request();
                // OrphanedChild: parent's group was removed; wake is moot.
                let _ = self.0.ready_set.insert(desc);
                tracing::trace!(
                    target: telemetry::TARGET_SCHEDULING,
                    tid = %id,
                    "wake",
                );
                self.generate_work();
            }
            None => {
                tracing::trace!(
                    target: telemetry::TARGET_SCHEDULING,
                    tid = %id,
                    "wake.not_found",
                );
            }
        }
    }

    /// Cancel a transfer and any child transfers, removing them from the scheduler.
    ///
    /// Lock-ordering protocol: delegates to `remove_transfer_atomic`, which
    /// holds `transfers.write` across `ready_set.remove_group`. Together
    /// with `enqueue_transfer`, the protocol prevents a child being
    /// orphaned in `transfers` after its parent group is removed. See
    /// `loom_tests::fixed_dance_no_orphan` at the bottom of this file.
    ///
    /// Cancels the target transfer first, then cancels all transfers whose
    /// `TransferId.parent == Some(id.id)` (depth-1 children only). Each
    /// cancelled transfer has its status set to cancelled, pending work
    /// purged, and idle notification sent. Work already being executed is
    /// interrupted: the runtime drops its `execute` future at the next await
    /// point.
    ///
    /// Returns a [`Cancellation`] carrying the cancelled descriptors.
    /// Drop it for fire-and-forget; await
    /// [`Cancellation::wait_for_idle`] to wait for in-flight executing
    /// work to drain.
    pub(crate) fn cancel_transfer(&self, id: TransferId) -> Cancellation {
        let (target, children) = self.remove_transfer_atomic(id);
        if let Some(desc) = &target {
            self.cancel_descriptor(desc.clone());
        }
        for desc in &children {
            self.cancel_descriptor(desc.clone());
        }
        Cancellation { target, children }
    }

    /// Atomic protocol-respecting removal of a transfer and its direct children.
    ///
    /// Lock-ordering invariant: `transfers.write` is acquired first and
    /// held across the call to `ready_set.remove_group` (which takes
    /// `by_group.write` internally). The two map mutations therefore
    /// appear atomic to any observer.
    ///
    /// Without this ordering, a concurrent `enqueue_transfer` for a child
    /// of `id` could sneak its child into `transfers` between the parent's
    /// removal and the group's removal, leaving the child orphaned in
    /// `transfers` after its parent group is gone — its handle would
    /// never resolve.
    ///
    /// Used by both `cancel_transfer` (caller cancels the returned parent
    /// descriptor + each child) and `generate_work`'s `Done` branch
    /// (caller leaves the parent alone since it completed normally, but
    /// cancels any children defensively — they shouldn't exist if the
    /// Transfer contract was upheld, but we clean them up if they do).
    fn remove_transfer_atomic(
        &self,
        id: TransferId,
    ) -> (Option<TransferDescriptor>, Vec<TransferDescriptor>) {
        let mut transfers = self.0.transfers.write().unwrap();
        let target = transfers.remove(&id);
        let child_keys: Vec<TransferId> = transfers
            .keys()
            .filter(|tid| tid.parent == Some(id.id))
            .copied()
            .collect();
        let children: Vec<TransferDescriptor> = child_keys
            .iter()
            .filter_map(|k| transfers.remove(k))
            .collect();
        if target.is_some() && id.parent.is_none() {
            self.0.ready_set.remove_group(id.id);
        }
        let registry_became_empty =
            (target.is_some() || !children.is_empty()) && transfers.is_empty();
        if registry_became_empty {
            // Publish the candidate before dropping the registry lock. A
            // racing final dispatch then either observes the candidate, or
            // this thread observes that dispatch's decrement below.
            self.0.idle_candidate.store(true, Ordering::SeqCst);
        }
        drop(transfers);
        if registry_became_empty {
            self.publish_global_idle_if_candidate();
        }
        (target, children)
    }

    /// Cancel a single transfer descriptor: set cancelled, clean up through
    /// `on_terminal`, interrupt executing work, signal terminal, purge pending
    /// work, and notify idle.
    fn cancel_descriptor(&self, desc: TransferDescriptor) {
        let id = desc.id();
        let ctx = desc.transfer().ctx();
        if ctx.is_active() {
            ctx.set_cancelled();
        }
        // Runs from handle `Drop`, so an `on_terminal` panic must not escape
        // or skip the steps that release the handle and reach idle.
        let cleanup_completed = run_on_terminal(&desc);
        desc.cancellation_token().cancel();
        ctx.signal_terminal();
        let purged = self.handle().runtime.remove_pending_for_transfer(id);
        self.release_dispatched(purged);
        desc.work_purged(purged);
        desc.notify_idle();
        tracing::debug!(target: telemetry::TARGET_SCHEDULING, tid = %id, purged, "transfer cancelled");
        if !cleanup_completed {
            tracing::error!(
                target: telemetry::TARGET_SCHEDULING,
                tid = %id,
                "on_terminal panicked; transfer cleanup is incomplete",
            );
        }
    }

    /// Set the priority of a transfer.
    ///
    /// Priority affects how fast vruntime accumulates (CFS-style scheduling):
    /// - Higher priority (255) = slower accumulation = more work share
    /// - Lower priority (1) = faster accumulation = less work share
    /// - Default priority is 128
    ///
    /// The change takes effect on the next work generation cycle.
    pub(crate) fn set_priority(&self, id: TransferId, priority: u8) {
        let transfers = self.0.transfers.read().unwrap();
        if let Some(desc) = transfers.get(&id) {
            desc.set_priority(priority);
        }
    }

    /// Called by workers when work completes.
    pub(crate) fn on_completion(
        &self,
        work: ScheduledWork,
        outcome: WorkOutcome,
        elapsed: Duration,
    ) {
        let outcome_tag = match &outcome {
            WorkOutcome::Success { .. } => "success",
            WorkOutcome::Yielded => "yielded",
            WorkOutcome::Failed { .. } => "failed",
            WorkOutcome::Cancelled => "cancelled",
        };
        tracing::trace!(
            target: telemetry::TARGET_SCHEDULING,
            tid = %work.descriptor.id(),
            ?elapsed,
            outcome = outcome_tag,
            "work execution finished",
        );
        self.release_dispatched(1);

        // Report to the concurrency controller. Yielded work retires the dispatch slot without
        // contributing an I/O operation or failure observation.
        let completion_sample = if matches!(outcome, WorkOutcome::Yielded) {
            None
        } else {
            let classification = match &outcome {
                WorkOutcome::Failed { classification } => *classification,
                _ => None,
            };
            Some(CompletionSample {
                error: classification,
            })
        };
        self.handle()
            .controller
            .on_completion(completion_sample.as_ref());

        let desc = &work.descriptor;
        let is_idle = desc.work_finished();
        if is_idle {
            desc.notify_idle();
        }

        // Terminal transfer: no further work from THIS transfer. Clean up
        // when fully drained. Routed through `remove_transfer_atomic` so
        // the transfers/by_group/groups lock-ordering protocol is held;
        // a concurrent child enqueue cannot slip into a window between
        // the parent's removal from `transfers` and its group's removal,
        // which would otherwise orphan the child.
        if desc.is_terminal() && is_idle {
            let desc_id = desc.id();
            let (completed, orphans) = self.remove_transfer_atomic(desc_id);
            if !orphans.is_empty() {
                tracing::warn!(
                    target: telemetry::TARGET_SCHEDULING,
                    parent_id = %desc_id,
                    child_count = orphans.len(),
                    "transfer reached terminal+idle in on_completion while \
                     children still alive; cleaning up. This is a Transfer \
                     trait contract violation."
                );
                for desc in orphans {
                    self.cancel_descriptor(desc);
                }
            }
            // Signal the removed transfer's terminal. A transfer that became
            // terminal but was removed here before signaling would leave its
            // completion channel unfired, hanging the owning handle. Signal
            // after cancelling orphans so children are torn down before the
            // handle observes completion. Idempotent if already signaled.
            if let Some(completed) = completed {
                completed.transfer().ctx().signal_terminal();
            }
        }

        // A concurrency slot was freed - always generate work. Other transfers
        // may be waiting for capacity.
        self.generate_work();
    }

    /// Handle a panic during work execution. The transfer's internal state is
    /// unknown, so the scheduler forces the terminal transition from outside.
    pub(crate) fn on_panic(&self, work: ScheduledWork) {
        self.release_dispatched(1);

        let desc = &work.descriptor;
        let ctx = desc.transfer().ctx();

        let err = crate::error::from_kind(crate::error::ErrorKind::RuntimeError)(
            "worker panic during execute",
        );
        ctx.set_failed(err);
        // Already handling a worker panic: a second panic from `on_terminal`
        // (e.g. a state lock poisoned by that worker) must not skip the steps
        // that release the handle and reach idle.
        let cleanup_completed = run_on_terminal(desc);
        ctx.signal_terminal();

        let is_idle = desc.work_finished();
        if is_idle {
            // Same lock-ordering protocol as on_completion: route
            // through `remove_transfer_atomic` to keep transfers and
            // by_group/groups consistent under concurrent child enqueue.
            let desc_id = desc.id();
            let (_completed, orphans) = self.remove_transfer_atomic(desc_id);
            if !orphans.is_empty() {
                tracing::warn!(
                    target: telemetry::TARGET_SCHEDULING,
                    parent_id = %desc_id,
                    child_count = orphans.len(),
                    "panicking transfer reached idle while children still \
                     alive; cleaning up."
                );
                for desc in orphans {
                    self.cancel_descriptor(desc);
                }
            }
        }
        desc.notify_idle();
        if !cleanup_completed {
            tracing::error!(
                target: telemetry::TARGET_SCHEDULING,
                tid = %desc.id(),
                "on_terminal panicked; transfer cleanup is incomplete",
            );
        }

        // The panicking work item released a concurrency slot. A peer may already be queued behind
        // it, including at target=1 where no other completion can re-drive generation.
        self.generate_work();
    }

    fn has_capacity(&self) -> bool {
        let target = self.handle().controller.target();
        // The retire-at-capacity path in `generate_work` depends on this: at
        // capacity, `dispatched >= target >= 1` guarantees an in-flight item
        // will complete and re-drive generation. See `ConcurrencyController::target`.
        debug_assert!(target >= 1, "concurrency target must be >= 1");
        self.0.dispatched.load(Ordering::Relaxed) < target
    }

    /// `has_capacity`, but reading `dispatched` with a read-modify-write so the
    /// runner cannot retire on a stale view of capacity.
    ///
    /// The plain-load `has_capacity` is correct in the dispatch hot loop, where
    /// the runner just observed its own `dispatched` writes. It is NOT safe at
    /// the retire decision: a concurrent `on_completion` decrements `dispatched`
    /// and then bumps the gate epoch via `generate_work`'s `try_acquire`. When a
    /// runner is already active that bump *coalesces* — it records the request on
    /// the epoch but publishes no gate edge into this runner, so it establishes
    /// no happens-before with it. A `Relaxed` load may then read the stale
    /// pre-decrement value, and the runner retires leaving a freed slot with
    /// queued work and no runner — a lost wake (loom: `gate.rs`
    /// `..._at_capacity_with_producer`).
    ///
    /// An RMW reads the latest value in `dispatched`'s modification order, so it
    /// observes the completion's decrement; `SeqCst` places this read and the
    /// gate's retire CAS in one total order, so the runner and the completing
    /// thread agree on which of them drives the freed slot. Used only at the
    /// retire check — not per-pop — so its cost is off the hot path.
    fn recheck_capacity(&self) -> bool {
        let target = self.handle().controller.target();
        debug_assert!(target >= 1, "concurrency target must be >= 1");
        self.0.dispatched.fetch_add(0, Ordering::SeqCst) < target
    }

    /// Flush the current submission and re-enter for the next batch.
    fn submit_and_reenter<'a>(
        &'a self,
        sub: Submission<'a, ScheduledWork>,
    ) -> Submission<'a, ScheduledWork> {
        if let Some(mut guard) = sub.submit() {
            self.handle().runtime.dispatch(&mut guard);
        }
        self.0.submission_queue.enter()
    }

    /// Push work into the submission, flushing and retrying on contention.
    fn enqueue<'a>(
        &'a self,
        mut sub: Submission<'a, ScheduledWork>,
        work: ScheduledWork,
    ) -> Submission<'a, ScheduledWork> {
        let mut pending = work;
        loop {
            match sub.push(pending) {
                Ok(()) => return sub,
                Err(returned) => {
                    sub = self.submit_and_reenter(sub);
                    pending = returned;
                }
            }
        }
    }

    /// Generate work from ready transfers and dispatch to runtime.
    ///
    /// Callers (`wake`, `on_completion`, re-entrant `enqueue_transfer`) insert
    /// their descriptor into the ready set BEFORE calling this, then acquire the
    /// [`GenerateWorkGate`]: the sole runner drains generation passes, and any
    /// other caller's request is coalesced into an extra pass the runner makes
    /// on its behalf, so no wake is lost.
    fn generate_work(&self) {
        // A popped or removed descriptor can be the last owner of its
        // transfer, and through it of the client handle. Holding the handle
        // keeps it alive until the pass ends. With the client gone there is
        // nothing to generate.
        let Some(_handle) = self.0.handle.upgrade() else {
            return;
        };
        // Become the sole runner, or bail — a request was recorded for the
        // active runner to drain on our behalf (this is also the re-entrancy
        // guard; see `GenerateWorkGate::try_acquire`).
        let Some(mut permit) = self.0.generate_work_gate.try_acquire() else {
            return;
        };
        let mut passes = 0usize;
        'generate: loop {
            passes += 1;
            let mut sub = self.0.submission_queue.enter();
            let mut generated = 0usize;
            let mut polled = 0usize;
            let mut pending_count = 0usize;
            let mut done_count = 0usize;
            let mut terminal_skipped = 0usize;
            tracing::trace!(
                target: telemetry::TARGET_SCHEDULING,
                has_capacity = self.has_capacity(),
                dispatched = self.0.dispatched.load(Ordering::Relaxed),
                target = self.handle().controller.target(),
                "generate_work.enter",
            );
            let break_reason = loop {
                if !self.has_capacity() {
                    break "no_capacity";
                }
                let Some(desc) = self.0.ready_set.pop() else {
                    break "ready_set_empty";
                };

                // Skip cancelled/failed transfers still in the ready set.
                // Release the claim explicitly since we won't call poll_work.
                if desc.is_terminal() {
                    terminal_skipped += 1;
                    let claim = ClaimGuard::new(&desc);
                    claim.release();
                    continue;
                }

                polled += 1;
                let id = desc.id();
                // Consume any pre-existing wake signal so we only observe
                // wakes that arrive DURING the poll below.
                desc.clear_wake_request();
                desc.transfer().ctx().begin_poll();

                let claim = ClaimGuard::new(&desc);
                let poll_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    desc.transfer().poll_work()
                }));

                match poll_result {
                    Ok(PollWork::Ready { io, spawned }) => {
                        generated += 1;
                        desc.work_generated();
                        // If this poll also spawned a child (fused reap+spawn),
                        // charge one spawn's reduced vruntime too. The spawned
                        // child gets NO dispatch ticket here -- it increments
                        // `dispatched` when it is itself polled to `Ready`,
                        // identical to the `Spawned` contract. Only the IO below
                        // takes a ticket.
                        if spawned {
                            desc.work_generated_spawn();
                        }
                        // Re-insert under the still-held claim - bypasses the
                        // CAS gate that `insert` would otherwise apply.
                        claim.hold();
                        self.0.ready_set.reinsert_under_claim(desc.clone());
                        self.0.dispatched.fetch_add(1, Ordering::Relaxed);
                        desc.work_queued();
                        let work = ScheduledWork {
                            item: io,
                            descriptor: desc,
                        };
                        sub = self.enqueue(sub, work);
                    }
                    Ok(PollWork::Spawned) => {
                        // Charge the reduced spawn cost (not full work cost) so a
                        // composite parent stays scheduling-competitive with its
                        // own children and can refill continuously.
                        desc.work_generated_spawn();
                        // Re-insert under the still-held claim so the transfer
                        // is re-polled while has_capacity remains true.
                        claim.hold();
                        self.0.ready_set.reinsert_under_claim(desc.clone());
                        // No dispatched.fetch_add, no work_queued, no enqueue:
                        // nothing was dispatched. The spawned child increments
                        // dispatched when it is itself polled and yields a work item.
                    }
                    Ok(PollWork::Pending) => {
                        pending_count += 1;
                        tracing::trace!(
                            target: telemetry::TARGET_SCHEDULING,
                            tid = %id,
                            "poll_work.pending",
                        );
                        // Release-and-recheck. A wake arriving in this
                        // window either takes the claim itself (its CAS
                        // succeeds) or sets wake_requested for us to
                        // observe. See the `claim` module for the protocol.
                        claim.release();
                        if desc.reconcile_pending_wake() {
                            // OrphanedChild: parent's group was removed; wake is moot.
                            let _ = self.0.ready_set.insert(desc);
                        }
                    }
                    Ok(PollWork::Done) => {
                        done_count += 1;
                        tracing::trace!(
                            target: telemetry::TARGET_SCHEDULING,
                            tid = %id,
                            "poll_work.done",
                        );
                        claim.release();
                        let desc_id = desc.id();
                        let (_completed, orphans) = self.remove_transfer_atomic(desc_id);
                        // The parent's `_completed` descriptor is the same one
                        // we just polled; it terminated normally so we do not
                        // call `cancel_descriptor` on it. Children should not
                        // exist if the Transfer contract was upheld; if they
                        // do, the contract is violated — clean them up
                        // defensively and surface the violation as a warning.
                        if !orphans.is_empty() {
                            tracing::warn!(
                                target: telemetry::TARGET_SCHEDULING,
                                parent_id = %desc_id,
                                child_count = orphans.len(),
                                "transfer returned PollWork::Done while children \
                                 still alive; cleaning up. This is a Transfer \
                                 trait contract violation."
                            );
                            for desc in orphans {
                                self.cancel_descriptor(desc);
                            }
                        }
                    }
                    Err(_panic_payload) => {
                        // ClaimGuard's Drop releases the claim. cancel_transfer
                        // handles terminal transition + child cascade.
                        tracing::error!(
                            target: telemetry::TARGET_SCHEDULING,
                            tid = %id,
                            "panic in poll_work, forcing terminal",
                        );
                        drop(claim);
                        drop(desc);
                        self.cancel_transfer(id);
                    }
                }
            };
            if let Some(mut guard) = sub.submit() {
                self.handle().runtime.dispatch(&mut guard);
            }
            tracing::trace!(
                target: telemetry::TARGET_SCHEDULING,
                generated,
                polled,
                pending_count,
                done_count,
                terminal_skipped,
                break_reason,
                dispatched = self.0.dispatched.load(Ordering::Relaxed),
                target = self.handle().controller.target(),
                "generate_work.exit",
            );
            // Retire the runner, or run another pass if a wake()/on_completion()
            // bumped the request epoch while we drained (their try_acquire could
            // not take the permit, so they relied on us). try_release retires via
            // a CAS that requires the epoch to be unchanged — never a blind store
            // — so a racing request is never stomped:
            //   true  -> epoch unchanged; no request pending; retired. Done.
            //   false -> the epoch advanced; the permit re-synced and we keep it.
            loop {
                if permit.try_release() {
                    return;
                }
                // A request is pending. Run another pass only if we can
                // dispatch; otherwise a pass dispatches nothing and just pins
                // this worker thread, starving its own in-flight execute()
                // futures (the fairness regression). The RMW read is required
                // here, not a plain load: the pending request may be a coalesced
                // wake hiding a concurrent completion's slot release; a stale
                // read would retire into a lost wake. See `recheck_capacity`.
                if self.recheck_capacity() {
                    // Below capacity: a fresh pass could dispatch. Run one unless
                    // we have hit the proactive-pass bound AND an in-flight
                    // completion is guaranteed to re-drive us (dispatched >= 1) —
                    // in which case retire and let the runner role rotate to the
                    // completing thread, so no single thread stays engaged.
                    if passes < MAX_GENERATION_PASSES
                        || self.0.dispatched.fetch_add(0, Ordering::SeqCst) == 0
                    {
                        // Either under the bound, or in the dispatched == 0
                        // corner where no completion edge exists and we MUST keep
                        // draining (self-bounded by finite published work).
                        continue 'generate;
                    }
                    // Bound hit with a guaranteed completion edge: fall through to
                    // retry the epoch-CAS retire (hand off to that edge).
                }
                // At capacity (or bound-handoff): don't spin a useless pass.
                // dispatched >= target >= 1, so an in-flight item WILL complete
                // -> on_completion -> generate_work, which re-acquires and drains
                // the pending work. Retry the retire instead.
                //
                // No wake is lost across this retry. A completion racing in
                // decrements `dispatched` (in `on_completion`) BEFORE bumping the
                // epoch via `generate_work`'s `try_acquire`; the RMW reads above
                // observe that decrement, and the epoch-CAS retire fails if any
                // request bumped past the observed epoch — so a racing request
                // is always seen, never stranded.
            }
        }
    }

    #[allow(dead_code)]
    pub(crate) fn is_idle(&self) -> bool {
        self.0.transfers.read().unwrap().is_empty()
            && self.0.dispatched.load(Ordering::Relaxed) == 0
    }

    /// Release scheduler dispatch tickets and publish the final-dispatch edge.
    ///
    /// `SeqCst` pairs this decrement with registry removal's idle-candidate
    /// publication. If those transitions race, at least one side observes the
    /// other and checks the complete global-idle predicate.
    fn release_dispatched(&self, count: usize) {
        if count == 0 {
            return;
        }
        let previous = self.0.dispatched.fetch_sub(count, Ordering::SeqCst);
        debug_assert!(
            previous >= count,
            "released more scheduler dispatch tickets than were outstanding"
        );
        if previous == count {
            self.publish_global_idle_if_candidate();
        }
    }

    /// Publish scheduler-global idle after both independent counters reach zero.
    ///
    /// Registry removal creates the candidate. If dispatched work remains, the
    /// candidate stays armed until [`Self::release_dispatched`] releases the
    /// final ticket. Holding the registry lock through the callback serializes
    /// the event against new transfer registration.
    fn publish_global_idle_if_candidate(&self) {
        if !self.0.idle_candidate.load(Ordering::SeqCst) {
            return;
        }
        let transfers = self.0.transfers.read().unwrap();
        if transfers.is_empty()
            && self.0.dispatched.fetch_add(0, Ordering::SeqCst) == 0
            && self.0.idle_candidate.swap(false, Ordering::SeqCst)
        {
            self.handle().scheduler_became_idle();
        }
    }

    /// Pre-register an empty group for `group_id`. See
    /// [`crate::scheduler::ready_set::ReadySet::register_empty_group_for_test`].
    #[cfg(test)]
    pub(crate) fn register_empty_group_for_test(&self, group_id: u64) {
        self.0.ready_set.register_empty_group_for_test(group_id);
    }

    /// Number of members currently queued in a group's ready set.
    ///
    /// Returns `None` if the group does not exist (already removed).
    #[cfg(test)]
    pub(crate) fn group_member_count(&self, group_id: u64) -> Option<usize> {
        self.0.ready_set.member_count(group_id)
    }

    /// Number of transfers currently tracked by the scheduler.
    #[cfg(test)]
    pub(crate) fn transfer_count(&self) -> usize {
        self.0.transfers.read().unwrap().len()
    }

    /// Current dispatched count (test-only).
    #[cfg(test)]
    pub(crate) fn dispatched_for_test(&self) -> usize {
        self.0.dispatched.load(Ordering::Relaxed)
    }
}

/// Runs the transfer's `on_terminal` cleanup, containing any panic it raises.
///
/// Returns `false` if `on_terminal` panicked; its cleanup may be partial. The
/// panic is not re-raised, so the caller's remaining terminal steps always run.
fn run_on_terminal(desc: &TransferDescriptor) -> bool {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        desc.transfer().on_terminal()
    }))
    .is_ok()
}

#[cfg(test)]
mod tests {
    use crate::client::Handle;
    use crate::runtime::ScheduledWork;
    use crate::scheduler::descriptor::TransferDescriptor;
    use crate::scheduler::descriptor::{vruntime_delta_for_cost, IO_WORK_COST, SPAWN_WORK_COST};
    use crate::scheduler::transfer::mock::{
        BuggyDoneMock, FixedWorkCount, FusedReadySpawnedMock, MockStateMachine,
        TerminalWithoutSignalMock, WithDelay, WithExecute,
    };
    use crate::scheduler::MockTransfer;
    use crate::transfer::{
        IoRequest, PendingCategory, PendingCause, PollWork, Transfer, TransferContext, TransferId,
        WorkOutcome,
    };
    use aws_smithy_runtime::test_util::capture_test_logs::show_test_logs;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use std::time::Duration;

    fn test_handle(concurrency: usize) -> Arc<Handle> {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config");
        Handle::new_for_test(config, concurrency)
    }

    fn test_handle_with_diagnostics(concurrency: usize, detail: u64) -> Arc<Handle> {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), detail)
            .build()
            .expect("valid config");
        Handle::new_for_test(config, concurrency)
    }

    /// Transfer whose first poll wakes before publishing its pending cause.
    ///
    /// This models a future that invokes its registered waker synchronously
    /// from `poll`. The descriptor must retain the wake until `poll_work`
    /// returns `Pending`, then repoll the transfer.
    #[derive(Debug)]
    struct WakeBeforePendingTransfer {
        ctx: TransferContext,
        /// Number of scheduler polls observed by the test transfer.
        polls: AtomicUsize,
    }

    impl Transfer for WakeBeforePendingTransfer {
        fn ctx(&self) -> &TransferContext {
            &self.ctx
        }

        fn poll_work(&self) -> PollWork {
            if self.polls.fetch_add(1, Ordering::SeqCst) == 0 {
                // Model a registered future becoming ready inside poll_work,
                // before the state machine publishes its Pending outcome.
                self.ctx.waker().wake_by_ref();
                self.ctx
                    .set_pending(PendingCause::new(PendingCategory::Memory, "test"));
                PollWork::Pending
            } else {
                self.ctx.set_completed();
                self.ctx.signal_terminal();
                PollWork::Done
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async { unreachable!("test transfer produces no work") })
        }
    }

    /// Transfer that blocks inside `on_terminal` to expose notification order.
    ///
    /// Tests wait for `terminal_hook_entered`, verify that the terminal receiver
    /// remains pending, then release the hook.
    #[derive(Debug)]
    struct TerminalOrderingTransfer {
        ctx: TransferContext,
        terminal_hook_entered: Arc<Barrier>,
        release_terminal_hook: Arc<Barrier>,
    }

    impl Transfer for TerminalOrderingTransfer {
        fn ctx(&self) -> &TransferContext {
            &self.ctx
        }

        fn poll_work(&self) -> PollWork {
            self.ctx.set_pending(PendingCause::other("test"));
            PollWork::Pending
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async { unreachable!("test transfer produces no work") })
        }

        fn on_terminal(&self) {
            self.terminal_hook_entered.wait();
            self.release_terminal_hook.wait();
        }
    }

    /// A wake retained during `poll_work` is attributed after Pending is visible.
    // Builds a client handle: dropping the scheduler's ready set is not miri-clean.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn wake_before_pending_is_backfilled_and_repolled() {
        let handle = test_handle_with_diagnostics(1, 1);
        let id = TransferId {
            id: 40_001,
            parent: None,
        };
        let (ctx, completion_rx) = TransferContext::with_id(id, handle.clone());
        let observer = ctx.clone();
        let polls = AtomicUsize::new(0);
        let transfer = WakeBeforePendingTransfer { ctx, polls };

        handle.scheduler.enqueue_transfer(Box::new(transfer));
        completion_rx
            .await
            .expect("second poll should complete the transfer");

        let stats = observer
            .pending_stats()
            .expect("summary diagnostics enabled");
        assert_eq!(stats.category(PendingCategory::Memory).count, 1);
        assert_eq!(stats.terminal_cause, None);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Cancellation completes direction cleanup before notifying terminal waiters.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancellation_runs_terminal_hook_before_notification() {
        let handle = test_handle(1);
        let id = TransferId {
            id: 40_002,
            parent: None,
        };
        let (ctx, mut completion_rx) = TransferContext::with_id(id, handle.clone());
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Barrier::new(2));
        handle
            .scheduler
            .enqueue_transfer(Box::new(TerminalOrderingTransfer {
                ctx,
                terminal_hook_entered: Arc::clone(&entered),
                release_terminal_hook: Arc::clone(&release),
            }));

        let scheduler = handle.scheduler.clone();
        let cancel = std::thread::spawn(move || drop(scheduler.cancel_transfer(id)));
        entered.wait();
        assert_eq!(
            completion_rx.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty),
            "terminal notification must wait for on_terminal cleanup"
        );
        release.wait();
        cancel.join().unwrap();
        completion_rx
            .await
            .expect("cancellation should signal terminal");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Panic handling completes direction cleanup before notifying terminal waiters.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn worker_panic_runs_terminal_hook_before_notification() {
        let handle = test_handle(1);
        let id = TransferId {
            id: 40_003,
            parent: None,
        };
        let (ctx, mut completion_rx) = TransferContext::with_id(id, handle.clone());
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Barrier::new(2));
        let descriptor = TransferDescriptor::new(Box::new(TerminalOrderingTransfer {
            ctx,
            terminal_hook_entered: Arc::clone(&entered),
            release_terminal_hook: Arc::clone(&release),
        }));
        descriptor.work_queued();
        descriptor.work_started();
        handle.scheduler.0.dispatched.store(1, Ordering::Relaxed);
        let work = ScheduledWork {
            item: IoRequest { data: None },
            descriptor,
        };

        let scheduler = handle.scheduler.clone();
        let tokio_handle = tokio::runtime::Handle::current();
        let panic = std::thread::spawn(move || {
            let _runtime = tokio_handle.enter();
            scheduler.on_panic(work);
        });
        entered.wait();
        assert_eq!(
            completion_rx.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty),
            "terminal notification must wait for on_terminal cleanup"
        );
        release.wait();
        panic.join().unwrap();
        completion_rx
            .await
            .expect("panic handling should signal terminal");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Transfer whose `on_terminal` panics on a state mutex poisoned by an
    /// earlier panic, as a state machine's hook does after `execute` panics
    /// while holding its state lock.
    #[derive(Debug)]
    struct PoisonedTerminalTransfer {
        ctx: TransferContext,
        state: Arc<std::sync::Mutex<u32>>,
    }

    impl Transfer for PoisonedTerminalTransfer {
        fn ctx(&self) -> &TransferContext {
            &self.ctx
        }

        fn poll_work(&self) -> PollWork {
            self.ctx.set_pending(PendingCause::other("test"));
            PollWork::Pending
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async { unreachable!("test transfer produces no work") })
        }

        fn on_terminal(&self) {
            let _guard = self.state.lock().unwrap();
        }
    }

    /// Returns a mutex poisoned by a thread that panicked while holding it.
    fn poisoned_state() -> Arc<std::sync::Mutex<u32>> {
        let state = Arc::new(std::sync::Mutex::new(0u32));
        let poisoner = Arc::clone(&state);
        let _ = std::thread::spawn(move || {
            let _guard = poisoner.lock().unwrap();
            panic!("invalid discovery state");
        })
        .join();
        assert!(state.lock().is_err(), "mutex should be poisoned");
        state
    }

    /// A panicking `on_terminal` during worker-panic handling still signals
    /// terminal and drains the descriptor to idle without re-raising.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn panic_poisoning_state_still_signals_terminal() {
        let handle = test_handle(1);
        let id = TransferId {
            id: 40_009,
            parent: None,
        };
        let (ctx, completion_rx) = TransferContext::with_id(id, handle.clone());
        let _handle_side_ctx = ctx.clone();
        let state = poisoned_state();
        let descriptor = TransferDescriptor::new(Box::new(PoisonedTerminalTransfer {
            ctx,
            state: Arc::clone(&state),
        }));
        descriptor.work_queued();
        descriptor.work_started();
        let observer = descriptor.clone();
        handle.scheduler.0.dispatched.store(1, Ordering::Relaxed);
        let work = ScheduledWork {
            item: IoRequest { data: None },
            descriptor,
        };

        let scheduler = handle.scheduler.clone();
        let tokio_handle = tokio::runtime::Handle::current();
        let panicker = std::thread::spawn(move || {
            let _runtime = tokio_handle.enter();
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| scheduler.on_panic(work)))
                .is_err()
        });
        let signalled = tokio::time::timeout(Duration::from_secs(3), completion_rx).await;
        let on_panic_panicked = panicker.join().unwrap();
        let received = signalled.expect("join() never released");
        assert!(
            received.is_ok(),
            "terminal never signalled (on_panic panicked: {on_panic_panicked})"
        );
        assert!(!on_panic_panicked, "on_panic must not re-raise");
        assert!(observer.is_idle(), "descriptor should reach idle");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// A panicking `on_terminal` during cancellation still cancels the token,
    /// signals terminal, and reaches idle without escaping `cancel_transfer`.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancel_poisoning_state_still_signals_terminal() {
        let handle = test_handle(1);
        let id = TransferId {
            id: 40_010,
            parent: None,
        };
        let (ctx, completion_rx) = TransferContext::with_id(id, handle.clone());
        let state = poisoned_state();
        handle
            .scheduler
            .enqueue_transfer(Box::new(PoisonedTerminalTransfer {
                ctx,
                state: Arc::clone(&state),
            }));

        let scheduler = handle.scheduler.clone();
        let canceller = std::thread::spawn(move || {
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                scheduler.cancel_transfer(id)
            }))
        });
        let signalled = tokio::time::timeout(Duration::from_secs(3), completion_rx).await;
        let cancellation = canceller
            .join()
            .unwrap()
            .expect("cancel_transfer must not re-raise");
        let received = signalled.expect("join() never released");
        assert!(received.is_ok(), "terminal never signalled");
        let target = cancellation
            .target
            .clone()
            .expect("cancelled transfer should be registered");
        assert!(
            target.cancellation_token().is_cancelled(),
            "cancellation token should fire"
        );
        tokio::time::timeout(Duration::from_secs(3), cancellation.wait_for_idle())
            .await
            .expect("cancelled transfer should reach idle");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[derive(Debug)]
    struct CountingCompletionController {
        completions: AtomicUsize,
        samples: AtomicUsize,
    }

    impl crate::scheduler::ConcurrencyController for CountingCompletionController {
        fn target(&self) -> usize {
            1
        }

        fn on_completion(&self, sample: Option<&crate::scheduler::CompletionSample>) {
            self.completions.fetch_add(1, Ordering::Relaxed);
            if sample.is_some() {
                self.samples.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn yielded_work_releases_capacity_without_reporting_completion() {
        let controller = Arc::new(CountingCompletionController {
            completions: AtomicUsize::new(0),
            samples: AtomicUsize::new(0),
        });
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config");
        let handle = Handle::new_for_test_with_runtime(config, controller.clone(), |weak| {
            Arc::new(crate::runtime::TokioMultiThreadRuntime::new(weak))
        });
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(WithExecute::new(FixedWorkCount::new(1), |_| {
            WorkOutcome::Yielded
        }));
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(id, state)));

        tokio::time::timeout(Duration::from_secs(5), async {
            while !handle.scheduler.is_idle() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("scheduler did not drain yielded work");

        assert_eq!(controller.completions.load(Ordering::Relaxed), 1);
        assert_eq!(controller.samples.load(Ordering::Relaxed), 0);
    }

    fn test_handle_managed(concurrency: usize) -> Arc<Handle> {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config");
        Handle::new_for_test_with_runtime(
            config,
            Arc::new(crate::scheduler::FixedConcurrency::new(concurrency)),
            |weak| Arc::new(crate::runtime::ManagedExecution::for_test(weak, 4)),
        )
    }

    // ref: V2429410200
    /// The scheduler releases a transfer once it has completed and been
    /// removed, while the client is still alive.
    ///
    /// The mock's state machine is owned only by the transfer, so its weak
    /// reference dies exactly when the scheduler drops the transfer. The
    /// final worker reference can outlive registry removal, so the check
    /// waits a bounded time without forcing epoch collection.
    /// A transfer retained by scheduler structures past removal keeps its
    /// resources, such as a destination file and the client handle, alive.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn completed_transfer_is_dropped_while_the_client_is_alive() {
        let handle = test_handle(1);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let sm = Arc::new(FixedWorkCount::new(2));
        let released = Arc::downgrade(&sm);
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            id,
            sm,
            Arc::clone(&handle),
        )));

        let dropped = tokio::time::timeout(Duration::from_secs(2), async {
            while released.strong_count() > 0 {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await;
        let completed = released.upgrade().map(|sm| sm.completed_count());
        assert_eq!(scheduler.transfer_count(), 0, "transfer was not removed");
        assert!(
            dropped.is_ok(),
            "completed transfer is still retained; completed work items: {completed:?}"
        );
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Returns `Pending` on its first poll and `Done` after.
    #[derive(Debug, Default)]
    struct PendingThenDone {
        polls: AtomicUsize,
    }

    impl MockStateMachine for PendingThenDone {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if self.polls.fetch_add(1, Ordering::SeqCst) == 0 {
                PollWork::Pending
            } else {
                PollWork::Done
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async { WorkOutcome::Success { data: None } })
        }
    }

    // ref: V2429410200
    /// A work-generation pass that retires the last transfer holding the
    /// client handle finishes without panicking, and the handle is dropped
    /// once the pass ends.
    ///
    /// The scheduler holds the handle weakly, and a wake reaches it without a
    /// handle of its own. Once a retired transfer drops, nothing else may own
    /// the handle; a pass that did not hold it would fail its next handle
    /// lookup.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn generation_pass_survives_retiring_the_last_handle_owner() {
        let handle = test_handle(1);
        let scheduler = handle.scheduler.clone();
        let released = Arc::downgrade(&handle);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            id,
            Arc::new(PendingThenDone::default()),
            Arc::clone(&handle),
        )));
        drop(handle);
        assert!(
            released.upgrade().is_some(),
            "the pending transfer holds the handle"
        );

        scheduler.wake(id);
        assert_eq!(scheduler.transfer_count(), 0, "transfer was not removed");
        assert!(released.upgrade().is_none(), "the handle is still alive");
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_transfer_completes() {
        let _logs = show_test_logs();
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        let sm = Arc::new(FixedWorkCount::new(5));
        let transfer = Box::new(MockTransfer::new(id, sm.clone()));
        scheduler.enqueue_transfer(transfer);

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        assert!(sm.is_complete());
        assert_eq!(sm.completed_count(), 5);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_idle_candidate_waits_for_the_final_dispatch() {
        let handle = test_handle(1);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            id,
            Arc::new(PendingForever),
            Arc::clone(&handle),
        )));
        scheduler.0.dispatched.store(1, Ordering::SeqCst);

        let cancellation = scheduler.cancel_transfer(id);

        assert_eq!(scheduler.transfer_count(), 0);
        assert!(scheduler.0.idle_candidate.load(Ordering::SeqCst));
        assert_eq!(handle.buffer_pool.diagnostics().idle_deadlines, 0);

        scheduler.release_dispatched(1);

        assert!(!scheduler.0.idle_candidate.load(Ordering::SeqCst));
        assert_eq!(handle.buffer_pool.diagnostics().idle_deadlines, 1);
        drop(cancellation);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_registry_removal_observes_an_already_completed_dispatch() {
        let handle = test_handle(1);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            id,
            Arc::new(PendingForever),
            Arc::clone(&handle),
        )));
        scheduler.0.dispatched.store(1, Ordering::SeqCst);

        scheduler.release_dispatched(1);
        assert_eq!(handle.buffer_pool.diagnostics().idle_deadlines, 0);

        let cancellation = scheduler.cancel_transfer(id);

        assert!(!scheduler.0.idle_candidate.load(Ordering::SeqCst));
        assert_eq!(handle.buffer_pool.diagnostics().idle_deadlines, 1);
        drop(cancellation);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_new_work_cancels_a_pending_idle_candidate() {
        let handle = test_handle(1);
        let scheduler = &handle.scheduler;
        let first_id = TransferId {
            id: 1,
            parent: None,
        };
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            first_id,
            Arc::new(PendingForever),
            Arc::clone(&handle),
        )));
        scheduler.0.dispatched.store(1, Ordering::SeqCst);
        let first_cancellation = scheduler.cancel_transfer(first_id);
        assert!(scheduler.0.idle_candidate.load(Ordering::SeqCst));

        let second_id = TransferId {
            id: 2,
            parent: None,
        };
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            second_id,
            Arc::new(PendingForever),
            Arc::clone(&handle),
        )));
        scheduler.release_dispatched(1);

        assert!(!scheduler.0.idle_candidate.load(Ordering::SeqCst));
        assert_eq!(handle.buffer_pool.diagnostics().idle_deadlines, 0);

        drop(first_cancellation);
        drop(scheduler.cancel_transfer(second_id));
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_each_managed_work_interval_arms_one_idle_deadline() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        for expected_deadlines in 1..=2 {
            let id = TransferId {
                id: expected_deadlines,
                parent: None,
            };
            scheduler.enqueue_transfer(Box::new(MockTransfer::new(
                id,
                Arc::new(FixedWorkCount::new(1)),
            )));

            let reached_idle = tokio::time::timeout(Duration::from_secs(5), async {
                while !scheduler.is_idle()
                    || handle.buffer_pool.diagnostics().idle_deadlines < expected_deadlines
                {
                    tokio::task::yield_now().await;
                }
            })
            .await;
            assert!(
                reached_idle.is_ok(),
                "completed managed work should arm idle reclamation: \
                 registered={}, dispatched={}, diagnostics={:?}",
                scheduler.transfer_count(),
                scheduler.dispatched_for_test(),
                handle.buffer_pool.diagnostics(),
            );
            assert_eq!(
                handle.buffer_pool.diagnostics().idle_deadlines,
                expected_deadlines,
                "one deadline should be armed for each activity-to-idle interval"
            );
        }

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_transfer_completes_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(4);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        let sm = Arc::new(FixedWorkCount::new(5));
        let transfer = Box::new(MockTransfer::new(id, sm.clone()));
        scheduler.enqueue_transfer(transfer);

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        assert!(sm.is_complete());
        assert_eq!(sm.completed_count(), 5);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_multiple_transfers_complete() {
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;
        let mut state_machines = Vec::new();

        for i in 0..3u64 {
            let id = TransferId {
                id: i,
                parent: None,
            };
            let sm = Arc::new(FixedWorkCount::new(4));
            state_machines.push(sm.clone());
            scheduler.enqueue_transfer(Box::new(MockTransfer::new(id, sm)));
        }

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        for (i, sm) in state_machines.iter().enumerate() {
            assert!(sm.is_complete(), "transfer {} should be complete", i);
            assert_eq!(sm.completed_count(), 4);
        }
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Regression test: many single-work-item transfers with concurrency target
    /// lower than the transfer count. Each transfer generates exactly one work
    /// item (like a single PutObject upload). All must complete - if on_completion
    /// doesn't call generate_work() for terminal transfers, only the first
    /// `concurrency` transfers complete and the rest hang forever.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_work_transfers_exceed_concurrency() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;
        let mut state_machines = Vec::new();

        for i in 0..10u64 {
            let id = TransferId {
                id: i,
                parent: None,
            };
            let sm = Arc::new(FixedWorkCount::new(1));
            state_machines.push(sm.clone());
            scheduler.enqueue_transfer(Box::new(MockTransfer::new(id, sm)));
        }

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("all 10 transfers should complete - scheduler must generate work after terminal completions");

        for (i, sm) in state_machines.iter().enumerate() {
            assert!(sm.is_complete(), "transfer {} should be complete", i);
            assert_eq!(sm.completed_count(), 1);
        }
        crate::runtime::test_util::shutdown(&handle).await;
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_new_does_not_require_runtime() {
        let _handle = test_handle(4);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_set_priority() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        // Use a mock that returns Pending so it doesn't complete immediately
        let sm = Arc::new(PendingForever);
        let transfer = Box::new(MockTransfer::new(id, sm));
        scheduler.enqueue_transfer(transfer);

        // Default priority is 128
        {
            let transfers = scheduler.0.transfers.read().unwrap();
            let desc = transfers.get(&id).expect("transfer should exist");
            assert_eq!(desc.priority(), 128);
        }

        // Change priority
        scheduler.set_priority(id, 255);

        {
            let transfers = scheduler.0.transfers.read().unwrap();
            let desc = transfers.get(&id).expect("transfer should still exist");
            assert_eq!(desc.priority(), 255);
        }

        // Setting priority on non-existent transfer is a no-op
        let fake_id = TransferId {
            id: 999,
            parent: None,
        };
        scheduler.set_priority(fake_id, 100); // Should not panic

        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Mock that always returns Pending (never generates work, never completes)
    #[derive(Debug)]
    struct PendingForever;

    impl MockStateMachine for PendingForever {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            PollWork::Pending
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async { unreachable!("PendingForever never generates work") })
        }
    }

    /// Execution that remains active until the test releases it.
    #[derive(Debug)]
    struct BlockingExecute {
        generated: AtomicBool,
        started: tokio::sync::Notify,
        release: tokio::sync::Notify,
    }

    impl BlockingExecute {
        fn new() -> Self {
            Self {
                generated: AtomicBool::new(false),
                started: tokio::sync::Notify::new(),
                release: tokio::sync::Notify::new(),
            }
        }
    }

    impl MockStateMachine for BlockingExecute {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if self.generated.swap(true, Ordering::SeqCst) {
                PollWork::Pending
            } else {
                PollWork::ready(IoRequest { data: None })
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async move {
                self.started.notify_one();
                self.release.notified().await;
                WorkOutcome::Success { data: None }
            })
        }
    }

    async fn cancellation_interrupts_executing_work(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(BlockingExecute::new());
        scheduler.enqueue_transfer(Box::new(MockTransfer::new_with_handle(
            id,
            state.clone(),
            handle.clone(),
        )));

        tokio::time::timeout(Duration::from_secs(5), state.started.notified())
            .await
            .expect("work did not enter execute");
        let result = tokio::time::timeout(
            Duration::from_secs(1),
            scheduler.cancel_transfer(id).wait_for_idle(),
        )
        .await;

        if result.is_err() {
            state.release.notify_waiters();
            tokio::time::timeout(Duration::from_secs(5), async {
                while !scheduler.is_idle() {
                    tokio::task::yield_now().await;
                }
            })
            .await
            .expect("scheduler did not drain released work");
        }

        crate::runtime::test_util::shutdown(&handle).await;
        result.expect("cancellation did not interrupt executing transfer work");
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancellation_interrupts_executing_work_on_tokio_runtime() {
        cancellation_interrupts_executing_work(test_handle(1)).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancellation_interrupts_executing_work_on_managed_runtime() {
        cancellation_interrupts_executing_work(test_handle_managed(1)).await;
    }

    /// Concurrency controller with a fixed target that counts completion reports.
    ///
    /// `Scheduler::on_completion` reports to the controller exactly once per
    /// call and `Scheduler::on_panic` never does, so the count is the number of
    /// `on_completion` calls the scheduler has observed.
    #[derive(Debug)]
    struct CompletionCounter {
        target: usize,
        completions: AtomicUsize,
    }

    impl CompletionCounter {
        fn completions(&self) -> usize {
            self.completions.load(Ordering::SeqCst)
        }
    }

    impl crate::scheduler::ConcurrencyController for CompletionCounter {
        fn target(&self) -> usize {
            self.target
        }

        fn on_completion(&self, _sample: Option<&crate::scheduler::CompletionSample>) {
            self.completions.fetch_add(1, Ordering::SeqCst);
        }
    }

    /// Execution runtime backing a [`counted_handle`].
    #[derive(Clone, Copy, Debug)]
    enum TestRuntime {
        /// Workers are spawned onto the tokio runtime that performs the first dispatch.
        Tokio,
        /// Managed OS threads, one per topology core.
        Managed { threads: usize },
    }

    fn counted_handle(
        runtime: TestRuntime,
        target: usize,
    ) -> (Arc<Handle>, Arc<CompletionCounter>) {
        let controller = Arc::new(CompletionCounter {
            target,
            completions: AtomicUsize::new(0),
        });
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config");
        let handle =
            Handle::new_for_test_with_runtime(
                config,
                controller.clone(),
                move |weak| match runtime {
                    TestRuntime::Tokio => {
                        Arc::new(crate::runtime::TokioMultiThreadRuntime::new(weak))
                            as Arc<dyn crate::runtime::ExecutionRuntime>
                    }
                    TestRuntime::Managed { threads } => {
                        Arc::new(crate::runtime::ManagedExecution::for_test(weak, threads))
                    }
                },
            );
        (handle, controller)
    }

    fn registered_descriptor(
        handle: &Handle,
        id: TransferId,
    ) -> crate::scheduler::descriptor::TransferDescriptor {
        handle
            .scheduler
            .0
            .transfers
            .read()
            .unwrap()
            .get(&id)
            .cloned()
            .expect("transfer is not registered with the scheduler")
    }

    async fn wait_for_scheduler_idle(handle: &Handle) {
        tokio::time::timeout(Duration::from_secs(5), async {
            while !handle.scheduler.is_idle() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("scheduler did not drain");
    }

    /// Bounds `desc.wait_for_idle()` and checks the packed counter is back at
    /// zero queued and zero executing.
    async fn expect_descriptor_idle(desc: &crate::scheduler::descriptor::TransferDescriptor) {
        tokio::time::timeout(Duration::from_secs(5), desc.wait_for_idle())
            .await
            .expect("a dispatched work item never reported completion");
        assert!(
            desc.is_idle(),
            "queued/executing counter must return to (0, 0)"
        );
    }

    /// Single-work transfer whose execute waits for the test to release it.
    ///
    /// `poll_work` yields one work item, returns `Pending` until that item's
    /// execute returns, then returns `Done`. Execute panics instead of
    /// returning when constructed with [`GatedSingleWork::panicking`].
    #[derive(Debug)]
    struct GatedSingleWork {
        generated: AtomicBool,
        finished: AtomicBool,
        panics: bool,
        started: tokio::sync::Notify,
        release: tokio::sync::Notify,
    }

    impl GatedSingleWork {
        fn succeeding() -> Self {
            Self::new(false)
        }

        fn panicking() -> Self {
            Self::new(true)
        }

        fn new(panics: bool) -> Self {
            Self {
                generated: AtomicBool::new(false),
                finished: AtomicBool::new(false),
                panics,
                started: tokio::sync::Notify::new(),
                release: tokio::sync::Notify::new(),
            }
        }
    }

    impl MockStateMachine for GatedSingleWork {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if !self.generated.swap(true, Ordering::SeqCst) {
                PollWork::ready(IoRequest { data: None })
            } else if self.finished.load(Ordering::SeqCst) {
                PollWork::Done
            } else {
                PollWork::Pending
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async move {
                self.started.notify_one();
                self.release.notified().await;
                if self.panics {
                    panic!("intentional execute panic");
                }
                self.finished.store(true, Ordering::SeqCst);
                WorkOutcome::Success { data: None }
            })
        }
    }

    /// Single-work transfer whose execute blocks its OS thread until released.
    ///
    /// On a single managed thread, work dispatched while this execute is
    /// blocked stays queued behind it. The block gives up after ten seconds so
    /// a failing test cannot wedge the thread indefinitely. `poll_work` yields
    /// one work item and then `Pending`, so the transfer stays registered until
    /// cancelled.
    #[derive(Debug)]
    struct ThreadBlockingExecute {
        generated: AtomicBool,
        started: tokio::sync::Notify,
        released: std::sync::Mutex<bool>,
        release_cv: std::sync::Condvar,
    }

    impl ThreadBlockingExecute {
        fn new() -> Self {
            Self {
                generated: AtomicBool::new(false),
                started: tokio::sync::Notify::new(),
                released: std::sync::Mutex::new(false),
                release_cv: std::sync::Condvar::new(),
            }
        }

        fn release(&self) {
            *self.released.lock().unwrap() = true;
            self.release_cv.notify_all();
        }
    }

    impl MockStateMachine for ThreadBlockingExecute {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if self.generated.swap(true, Ordering::SeqCst) {
                PollWork::Pending
            } else {
                PollWork::ready(IoRequest { data: None })
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async move {
                self.started.notify_one();
                let released = self.released.lock().unwrap();
                let (_released, _timeout) = self
                    .release_cv
                    .wait_timeout_while(released, Duration::from_secs(10), |released| !*released)
                    .unwrap();
                WorkOutcome::Success { data: None }
            })
        }
    }

    const BLOCKER_ID: TransferId = TransferId {
        id: 100,
        parent: None,
    };

    /// Occupies the only thread of a single-thread managed runtime with
    /// [`ThreadBlockingExecute`] and returns once its execute has started.
    async fn occupy_managed_thread(
        handle: &Arc<Handle>,
    ) -> (
        Arc<ThreadBlockingExecute>,
        crate::scheduler::descriptor::TransferDescriptor,
    ) {
        let blocker = Arc::new(ThreadBlockingExecute::new());
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(BLOCKER_ID, blocker.clone())));
        tokio::time::timeout(Duration::from_secs(5), blocker.started.notified())
            .await
            .expect("blocking work did not enter execute");
        (blocker, registered_descriptor(handle, BLOCKER_ID))
    }

    async fn normal_completion_finishes_work_once(runtime: TestRuntime) {
        let (handle, counter) = counted_handle(runtime, 1);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(GatedSingleWork::succeeding());
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(id, state.clone())));
        tokio::time::timeout(Duration::from_secs(5), state.started.notified())
            .await
            .expect("work did not enter execute");
        let desc = registered_descriptor(&handle, id);

        state.release.notify_one();

        expect_descriptor_idle(&desc).await;
        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        assert_eq!(counter.completions(), 1);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn normal_completion_finishes_work_once_on_tokio_runtime() {
        normal_completion_finishes_work_once(TestRuntime::Tokio).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn normal_completion_finishes_work_once_on_managed_runtime() {
        normal_completion_finishes_work_once(TestRuntime::Managed { threads: 4 }).await;
    }

    /// Work dispatched for a transfer that turns terminal before a worker picks
    /// it up completes through the terminal-skip path without executing.
    ///
    /// The tokio variant relies on the current-thread test runtime: the worker
    /// spawned by the first dispatch cannot run until the test yields.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn terminal_skip_finishes_work_once_on_tokio_runtime() {
        let (handle, counter) = counted_handle(TestRuntime::Tokio, 1);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(FixedWorkCount::new(1));
        let transfer = MockTransfer::new(id, state.clone());
        let ctx = transfer.ctx().clone();
        handle.scheduler.enqueue_transfer(Box::new(transfer));
        let desc = registered_descriptor(&handle, id);
        assert!(!desc.is_idle(), "work item should be queued");

        ctx.set_cancelled();

        expect_descriptor_idle(&desc).await;
        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        assert_eq!(counter.completions(), 1);
        assert_eq!(state.completed_count(), 0, "terminal work must not execute");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Managed variant of [`terminal_skip_finishes_work_once_on_tokio_runtime`].
    ///
    /// A single managed thread is held by [`ThreadBlockingExecute`] so the
    /// target transfer's work stays queued while the transfer turns terminal.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn terminal_skip_finishes_work_once_on_managed_runtime() {
        let (handle, counter) = counted_handle(TestRuntime::Managed { threads: 1 }, 2);
        let (blocker, blocker_desc) = occupy_managed_thread(&handle).await;

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(FixedWorkCount::new(1));
        let transfer = MockTransfer::new(id, state.clone());
        let ctx = transfer.ctx().clone();
        handle.scheduler.enqueue_transfer(Box::new(transfer));
        let desc = registered_descriptor(&handle, id);
        assert!(!desc.is_idle(), "work item should be queued");

        ctx.set_cancelled();
        blocker.release();

        expect_descriptor_idle(&desc).await;
        expect_descriptor_idle(&blocker_desc).await;
        handle.scheduler.cancel_transfer(BLOCKER_ID);
        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        // One for the blocker's execute, one for the skipped item.
        assert_eq!(counter.completions(), 2);
        assert_eq!(state.completed_count(), 0, "terminal work must not execute");
        crate::runtime::test_util::shutdown(&handle).await;
    }

    async fn execute_panic_finishes_work_once(runtime: TestRuntime) {
        let (handle, counter) = counted_handle(runtime, 1);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(GatedSingleWork::panicking());
        let transfer = MockTransfer::new(id, state.clone());
        let ctx = transfer.ctx().clone();
        handle.scheduler.enqueue_transfer(Box::new(transfer));
        tokio::time::timeout(Duration::from_secs(5), state.started.notified())
            .await
            .expect("work did not enter execute");
        let desc = registered_descriptor(&handle, id);

        state.release.notify_one();

        expect_descriptor_idle(&desc).await;
        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        assert!(ctx.is_failed());
        assert_eq!(
            counter.completions(),
            0,
            "a panicked work item is reported by on_panic, not on_completion"
        );
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn execute_panic_finishes_work_once_on_tokio_runtime() {
        let _logs = show_test_logs();
        execute_panic_finishes_work_once(TestRuntime::Tokio).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn execute_panic_finishes_work_once_on_managed_runtime() {
        let _logs = show_test_logs();
        execute_panic_finishes_work_once(TestRuntime::Managed { threads: 4 }).await;
    }

    async fn cancel_while_executing_finishes_work_once(runtime: TestRuntime) {
        let (handle, counter) = counted_handle(runtime, 1);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(GatedSingleWork::succeeding());
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(id, state.clone())));
        tokio::time::timeout(Duration::from_secs(5), state.started.notified())
            .await
            .expect("work did not enter execute");
        let desc = registered_descriptor(&handle, id);

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            handle.scheduler.cancel_transfer(id).wait_for_idle(),
        )
        .await;
        if result.is_err() {
            state.release.notify_one();
            wait_for_scheduler_idle(&handle).await;
            crate::runtime::test_util::shutdown(&handle).await;
        }
        result.expect("cancellation did not interrupt executing transfer work");

        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        assert_eq!(counter.completions(), 1);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancel_while_executing_finishes_work_once_on_tokio_runtime() {
        cancel_while_executing_finishes_work_once(TestRuntime::Tokio).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancel_while_executing_finishes_work_once_on_managed_runtime() {
        cancel_while_executing_finishes_work_once(TestRuntime::Managed { threads: 4 }).await;
    }

    /// Cancelling a transfer whose work is still in the worker pool purges the
    /// item; no worker ever picks it up.
    ///
    /// The tokio variant relies on the current-thread test runtime: the worker
    /// spawned by the first dispatch cannot run until the test yields. A second
    /// transfer is then run to completion; the pool is FIFO with one worker, so
    /// its completion proves the worker drained past the purged slot.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancel_while_queued_finishes_work_once_on_tokio_runtime() {
        let (handle, counter) = counted_handle(TestRuntime::Tokio, 1);
        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(FixedWorkCount::new(1));
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(id, state.clone())));
        let desc = registered_descriptor(&handle, id);
        assert!(!desc.is_idle(), "work item should be queued");

        let cancellation = handle.scheduler.cancel_transfer(id);
        tokio::time::timeout(Duration::from_secs(5), cancellation.wait_for_idle())
            .await
            .expect("purging queued work did not reach idle");
        assert!(desc.is_idle());

        let follower_id = TransferId {
            id: 2,
            parent: None,
        };
        let follower = Arc::new(FixedWorkCount::new(1));
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(follower_id, follower.clone())));
        wait_for_scheduler_idle(&handle).await;
        assert!(follower.is_complete());

        assert!(desc.is_idle());
        assert_eq!(state.completed_count(), 0, "purged work must not execute");
        assert_eq!(
            counter.completions(),
            1,
            "only the follower's work item should report completion"
        );
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Managed variant of [`cancel_while_queued_finishes_work_once_on_tokio_runtime`].
    ///
    /// Managed dispatch spawns each item as a task, so cancellation purges
    /// nothing; the queued task completes through the terminal-skip path
    /// once the thread is released.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn cancel_while_queued_finishes_work_once_on_managed_runtime() {
        let (handle, counter) = counted_handle(TestRuntime::Managed { threads: 1 }, 2);
        let (blocker, blocker_desc) = occupy_managed_thread(&handle).await;

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let state = Arc::new(FixedWorkCount::new(1));
        handle
            .scheduler
            .enqueue_transfer(Box::new(MockTransfer::new(id, state.clone())));
        let desc = registered_descriptor(&handle, id);
        assert!(!desc.is_idle(), "work item should be queued");

        let cancellation = handle.scheduler.cancel_transfer(id);
        blocker.release();
        tokio::time::timeout(Duration::from_secs(5), cancellation.wait_for_idle())
            .await
            .expect("cancelled queued work never reported completion");

        expect_descriptor_idle(&blocker_desc).await;
        handle.scheduler.cancel_transfer(BLOCKER_ID);
        wait_for_scheduler_idle(&handle).await;
        assert!(desc.is_idle());
        assert_eq!(
            state.completed_count(),
            0,
            "cancelled work must not execute"
        );
        // One for the blocker's execute, one for the skipped item.
        assert_eq!(counter.completions(), 2);
        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Mock that generates infinite work and counts executions.
    /// Can be stopped by calling `set_done()`.
    #[derive(Debug)]
    struct CountingInfinite {
        executions: AtomicUsize,
        done: std::sync::atomic::AtomicBool,
    }

    impl CountingInfinite {
        fn new() -> Self {
            Self {
                executions: AtomicUsize::new(0),
                done: std::sync::atomic::AtomicBool::new(false),
            }
        }

        fn count(&self) -> usize {
            self.executions.load(Ordering::Relaxed)
        }

        fn set_done(&self) {
            self.done.store(true, Ordering::Release);
        }
    }

    impl MockStateMachine for CountingInfinite {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if self.done.load(Ordering::Acquire) {
                return PollWork::Done;
            }
            PollWork::ready(IoRequest { data: None })
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async move {
                self.executions.fetch_add(1, Ordering::Relaxed);
                // Yield to prevent starving other tasks on single-threaded runtimes
                tokio::task::yield_now().await;
                // No schedule_next - let generate_work() pull from ready set
                // where CFS priority ordering applies
                WorkOutcome::Success { data: None }
            })
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_priority_affects_work_distribution() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let high_id = TransferId {
            id: 1,
            parent: None,
        };
        let low_id = TransferId {
            id: 2,
            parent: None,
        };

        let high_mock = Arc::new(CountingInfinite::new());
        let low_mock = Arc::new(CountingInfinite::new());

        let high_transfer = Box::new(MockTransfer::new(high_id, high_mock.clone()));
        let low_transfer = Box::new(MockTransfer::new(low_id, low_mock.clone()));

        scheduler.enqueue_transfer(high_transfer);
        scheduler.enqueue_transfer(low_transfer);

        // Set priorities: high=255, low=64 (4x difference)
        scheduler.set_priority(high_id, 255);
        scheduler.set_priority(low_id, 64);

        // Wait until we have enough samples
        let target_total = 200;
        while high_mock.count() + low_mock.count() < target_total {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }

        // Stop generating work
        high_mock.set_done();
        low_mock.set_done();

        crate::runtime::test_util::shutdown(&handle).await;

        let high_count = high_mock.count();
        let low_count = low_mock.count();

        // 4x priority difference (255 vs 64) yields ~4x dispatch ratio
        // via the priority-scaled vruntime delta in `work_generated`.
        assert!(
            high_count > low_count,
            "high priority should execute more: high={}, low={}",
            high_count,
            low_count
        );

        let ratio = high_count as f64 / low_count.max(1) as f64;
        // Priority delta in `work_generated` is `(IO_WORK_COST * 256) / priority`,
        // so high (255) advances ~4x slower than low (64), giving ~4x more
        // dispatch share. Allow a generous lower bound of 3.0 to absorb
        // sampling noise from the 200-dispatch window; observed in
        // practice is ~4.0.
        assert!(
            ratio > 3.0,
            "expected ratio > 3.0, got {:.2} (high={}, low={})",
            ratio,
            high_count,
            low_count
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_priority_change_mid_flight() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let a_id = TransferId {
            id: 1,
            parent: None,
        };
        let b_id = TransferId {
            id: 2,
            parent: None,
        };

        let a_mock = Arc::new(CountingInfinite::new());
        let b_mock = Arc::new(CountingInfinite::new());

        scheduler.enqueue_transfer(Box::new(MockTransfer::new(a_id, a_mock.clone())));
        scheduler.enqueue_transfer(Box::new(MockTransfer::new(b_id, b_mock.clone())));

        // Both at default priority (128) - let them run equally
        while a_mock.count() + b_mock.count() < 100 {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }

        // Snapshot counts, then shift priority heavily
        let a_before = a_mock.count();
        let b_before = b_mock.count();
        scheduler.set_priority(a_id, 255);
        scheduler.set_priority(b_id, 1);

        // Let them run more
        while (a_mock.count() - a_before) + (b_mock.count() - b_before) < 200 {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }

        a_mock.set_done();
        b_mock.set_done();
        crate::runtime::test_util::shutdown(&handle).await;

        let a_after = a_mock.count() - a_before;
        let b_after = b_mock.count() - b_before;

        // 255:1 priority ratio - A should get the vast majority of work
        let ratio = a_after as f64 / b_after.max(1) as f64;
        assert!(
            ratio > 3.0,
            "after priority change (255 vs 1), expected ratio > 3.0, got {:.2} (a={}, b={})",
            ratio,
            a_after,
            b_after
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_failed_transfer_cleaned_up() {
        let _logs = show_test_logs();
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let sm = Arc::new(WithExecute::new(FixedWorkCount::new(1), |_| {
            WorkOutcome::Failed {
                classification: None,
            }
        }));
        scheduler.enqueue_transfer(Box::new(MockTransfer::new(id, sm)));

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after failed transfer");

        assert!(!scheduler.0.transfers.read().unwrap().contains_key(&id));
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[derive(Debug)]
    struct PanicAfterSignal {
        generated: AtomicBool,
        started: tokio::sync::Notify,
        release: tokio::sync::Notify,
    }

    impl PanicAfterSignal {
        fn new() -> Self {
            Self {
                generated: AtomicBool::new(false),
                started: tokio::sync::Notify::new(),
                release: tokio::sync::Notify::new(),
            }
        }
    }

    impl MockStateMachine for PanicAfterSignal {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            if self.generated.swap(true, Ordering::SeqCst) {
                PollWork::Done
            } else {
                PollWork::ready(IoRequest { data: None })
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            Box::pin(async move {
                self.started.notify_one();
                self.release.notified().await;
                panic!("intentional execute panic")
            })
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_panic_transfer_cleaned_up_and_error_propagated() {
        let _logs = show_test_logs();
        let handle = test_handle(1);
        let scheduler = &handle.scheduler;

        let panic_id = TransferId {
            id: 1,
            parent: None,
        };
        let panic_sm = Arc::new(PanicAfterSignal::new());
        let panic_mock = MockTransfer::new(panic_id, Arc::clone(&panic_sm));
        let panic_ctx = panic_mock.ctx().clone();
        scheduler.enqueue_transfer(Box::new(panic_mock));
        tokio::time::timeout(Duration::from_secs(5), panic_sm.started.notified())
            .await
            .expect("panicking work did not occupy the scheduler slot");

        let ok_id = TransferId {
            id: 2,
            parent: None,
        };
        let ok_sm = Arc::new(FixedWorkCount::new(3));
        scheduler.enqueue_transfer(Box::new(MockTransfer::new(ok_id, ok_sm.clone())));
        assert_eq!(scheduler.dispatched_for_test(), 1);
        assert_eq!(ok_sm.completed_count(), 0);

        panic_sm.release.notify_one();

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        assert!(panic_ctx.is_failed());
        assert_eq!(
            panic_ctx.error_kind(),
            Some(crate::error::ErrorKind::RuntimeError),
        );
        assert!(!scheduler
            .0
            .transfers
            .read()
            .unwrap()
            .contains_key(&panic_id));

        assert!(ok_sm.is_complete());
        assert_eq!(ok_sm.completed_count(), 3);

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_transfer_stops_work() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        // Use WithDelay to make work slow enough to cancel mid-flight
        let inner = FixedWorkCount::new(20);
        let sm = Arc::new(WithDelay::new(inner, Duration::from_millis(50)));
        let transfer = Box::new(MockTransfer::new(id, sm.clone()));
        scheduler.enqueue_transfer(transfer);

        // Let some work start
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Cancel the transfer - returns true on first call
        assert!(scheduler.cancel_transfer(id).target.is_some());
        assert!(scheduler.cancel_transfer(id).target.is_none());

        // Wait for scheduler to become idle
        tokio::time::timeout(Duration::from_secs(2), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancel");

        // Should have completed fewer than total (cancelled early)
        let completed = sm.inner().completed_count();
        assert!(
            completed < 20,
            "expected fewer than 20 completions, got {}",
            completed
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_parent_cascades_to_children() {
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        let child_ids: Vec<TransferId> = (2..=4)
            .map(|i| TransferId {
                id: i,
                parent: Some(1),
            })
            .collect();

        let parent_sm = Arc::new(WithDelay::new(
            FixedWorkCount::new(20),
            Duration::from_millis(50),
        ));
        let parent_transfer = MockTransfer::new(parent_id, parent_sm);
        let parent_ctx = parent_transfer.ctx().clone();
        scheduler.enqueue_transfer(Box::new(parent_transfer));

        let mut child_ctxs = Vec::new();
        for &cid in &child_ids {
            let sm = Arc::new(WithDelay::new(
                FixedWorkCount::new(20),
                Duration::from_millis(50),
            ));
            let transfer = MockTransfer::new(cid, sm);
            child_ctxs.push(transfer.ctx().clone());
            scheduler.enqueue_transfer(Box::new(transfer));
        }

        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(scheduler.cancel_transfer(parent_id).target.is_some());

        tokio::time::timeout(Duration::from_secs(2), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cascade cancel");

        assert!(!parent_ctx.is_active(), "parent should not be active");
        for (i, ctx) in child_ctxs.iter().enumerate() {
            assert!(!ctx.is_active(), "child {} should not be active", i + 2);
        }

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_parent_with_no_children_still_works() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let sm = Arc::new(WithDelay::new(
            FixedWorkCount::new(20),
            Duration::from_millis(50),
        ));
        let transfer = MockTransfer::new(id, sm);
        let ctx = transfer.ctx().clone();
        scheduler.enqueue_transfer(Box::new(transfer));

        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(scheduler.cancel_transfer(id).target.is_some());
        assert!(scheduler.cancel_transfer(id).target.is_none());

        tokio::time::timeout(Duration::from_secs(2), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancel");

        assert!(!ctx.is_active(), "parent should not be active");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_child_does_not_affect_siblings_or_parent() {
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        let child_a = TransferId {
            id: 2,
            parent: Some(1),
        };
        let child_b = TransferId {
            id: 3,
            parent: Some(1),
        };

        let parent_sm = Arc::new(WithDelay::new(
            FixedWorkCount::new(20),
            Duration::from_millis(50),
        ));
        let parent_transfer = MockTransfer::new(parent_id, parent_sm);
        let parent_ctx = parent_transfer.ctx().clone();
        scheduler.enqueue_transfer(Box::new(parent_transfer));

        let sm_a = Arc::new(WithDelay::new(
            FixedWorkCount::new(20),
            Duration::from_millis(50),
        ));
        let transfer_a = MockTransfer::new(child_a, sm_a);
        let ctx_a = transfer_a.ctx().clone();
        scheduler.enqueue_transfer(Box::new(transfer_a));

        let sm_b = Arc::new(WithDelay::new(
            FixedWorkCount::new(20),
            Duration::from_millis(50),
        ));
        let transfer_b = MockTransfer::new(child_b, sm_b);
        let ctx_b = transfer_b.ctx().clone();
        scheduler.enqueue_transfer(Box::new(transfer_b));

        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(scheduler.cancel_transfer(child_a).target.is_some());
        assert!(ctx_a.is_cancelled(), "child A should be cancelled");
        assert!(parent_ctx.is_active(), "parent should still be active");
        assert!(ctx_b.is_active(), "sibling B should still be active");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_nonexistent_transfer_returns_false() {
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let fake_id = TransferId {
            id: 999,
            parent: None,
        };
        assert!(scheduler.cancel_transfer(fake_id).target.is_none());

        crate::runtime::test_util::shutdown(&handle).await;
    }

    // =========================================================================
    // Hierarchical CFS integration tests
    //
    // These tests pin the fairness, memory-cap, priority, cancellation, and
    // panic-recovery behavior of the two-level (group + member) CFS scheduler.
    // =========================================================================

    use crate::scheduler::transfer::mock::{
        ChildMockTransfer, CompositeMock, CountedWork, DispatchCounter, DispatchTrace,
        PanickingCompositeMock, SingleTicketCompositeMock,
    };

    async fn impl_single_composite_uses_target_fully(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let id = TransferId {
            id: 1,
            parent: None,
        };

        let composite = CompositeMock::new(
            id,
            handle.clone(),
            200,   // total children
            1,     // work per child
            10000, // memory cap (won't be hit)
            counter.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        let start = tokio::time::Instant::now();
        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        let elapsed = start.elapsed();
        let total_dispatches = counter.count();
        assert_eq!(total_dispatches, 200, "all 200 children should complete");

        // Wall time check: generous bound for CI
        assert!(
            elapsed < Duration::from_secs(15),
            "took too long: {:?}",
            elapsed
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_composite_uses_target_fully() {
        let handle = test_handle(200);
        impl_single_composite_uses_target_fully(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_composite_uses_target_fully_managed_runtime() {
        // See note on test_composite_vs_single_fair_share_at_root_managed_runtime
        // for why target is lower under managed runtime.
        let handle = test_handle_managed(20);
        impl_single_composite_uses_target_fully(handle).await;
    }

    async fn impl_composite_vs_single_fair_share_at_root(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;

        // Composite C: 50 children, 1 work item each
        let c_counter = DispatchCounter::new();
        let c_id = TransferId {
            id: 1,
            parent: None,
        };
        let composite = CompositeMock::new(c_id, handle.clone(), 50, 1, 10000, c_counter.clone());
        scheduler.enqueue_transfer(Box::new(composite));

        // Single transfer S: 50 work items
        let s_counter = DispatchCounter::new();
        let s_id = TransferId {
            id: 2,
            parent: None,
        };
        let sm = Arc::new(CountedWork::new(50, s_counter.clone()));
        let transfer = MockTransfer::new_with_handle(s_id, sm, handle.clone());
        scheduler.enqueue_transfer(Box::new(transfer));

        // Wait for both to complete (100 total dispatches)
        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        let c_count = c_counter.count();
        let s_count = s_counter.count();
        let total = c_count + s_count;

        // Both completed equal workloads, so each tree should end with
        // roughly the fair share. Tolerance accounts for ordering effects
        // at the very tail; observed drift is ~0% in practice.
        let fair_share = total as f64 / 2.0;
        let tolerance = fair_share * 0.10;
        assert!(
            (c_count as f64 - fair_share).abs() < tolerance,
            "composite got {} dispatches, expected ~{} (tolerance {})",
            c_count,
            fair_share,
            tolerance
        );
        assert!(
            (s_count as f64 - fair_share).abs() < tolerance,
            "single got {} dispatches, expected ~{} (tolerance {})",
            s_count,
            fair_share,
            tolerance
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_composite_vs_single_fair_share_at_root() {
        let handle = test_handle(100);
        impl_composite_vs_single_fair_share_at_root(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_composite_vs_single_fair_share_at_root_managed_runtime() {
        // Lower target than the tokio variant. Under managed runtime with 4
        // worker threads, multiple producers race on the scheduler's
        // submission queue (capacity 64); dispatching ~100 zero-latency work
        // items concurrently triggers a high-contention path that has not
        // been root-caused. A lower target keeps in-flight pressure inside
        // the queue capacity and exercises the same fairness invariant.
        let handle = test_handle_managed(20);
        impl_composite_vs_single_fair_share_at_root(handle).await;
    }

    async fn impl_two_composites_fair_share_regardless_of_fan_out(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;

        // Two composites with equal spawn-cost (same number of children) but
        // different work-per-child. The hierarchical CFS gives each group
        // equal scheduling share based on group_vruntime (which advances
        // per-child-spawned). With equal spawn counts, both groups should
        // receive roughly equal dispatch share in any observation window.
        //
        // C1: 50 children, 20 work items each = 1000 total dispatches
        let c1_counter = DispatchCounter::new();
        let c1_id = TransferId {
            id: 1,
            parent: None,
        };
        let c1 = CompositeMock::new(c1_id, handle.clone(), 50, 20, 10000, c1_counter.clone());
        scheduler.enqueue_transfer(Box::new(c1));

        // C2: 50 children, 20 work items each = 1000 total dispatches
        let c2_counter = DispatchCounter::new();
        let c2_id = TransferId {
            id: 2,
            parent: None,
        };
        let c2 = CompositeMock::new(c2_id, handle.clone(), 50, 20, 10000, c2_counter.clone());
        scheduler.enqueue_transfer(Box::new(c2));

        // Measure fairness over a SETTLED window. CFS fairness is a steady-state
        // property: the first ~100 dispatches are a startup transient (whichever
        // composite's children win the initial ready-set race burst ahead before
        // vruntime accounting pulls them level). Skew decays monotonically —
        // empirically ~35% at N=50, ~4% by N=500, <2% by N=1200 — so sampling at
        // an early, arbitrary checkpoint (e.g. the first poll past 500) measures
        // the transient, not the steady state, and is flaky. Waiting for 1200
        // total dispatches (60x the per-completion granularity at target 20) puts
        // the sample well past the knee, where the gap is reliably small.
        let total_work = 2 * 50 * 20;
        tokio::time::timeout(Duration::from_secs(15), async {
            loop {
                let total = c1_counter.count() + c2_counter.count();
                // Stop at 1200, or early if the whole run finishes first.
                if total >= 1200 || total >= total_work {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("should reach the fairness sampling window");

        let c1_count = c1_counter.count();
        let c2_count = c2_counter.count();

        // Both groups have equal spawn-cost (50 children each), so hierarchical
        // CFS gives each equal dispatch share at steady state. 10% tolerance: the
        // worst observed skew at N>=1200 across hundreds of runs was ~4%, so 10%
        // is comfortably non-flaky while still catching a real fairness break.
        let total = c1_count + c2_count;
        let fair_share = total as f64 / 2.0;
        let tolerance = fair_share * 0.10;
        assert!(
            (c1_count as f64 - fair_share).abs() < tolerance,
            "C1 got {} dispatches, expected ~{} (tolerance {}), C2 got {}",
            c1_count,
            fair_share,
            tolerance,
            c2_count
        );
        assert!(
            (c2_count as f64 - fair_share).abs() < tolerance,
            "C2 got {} dispatches, expected ~{} (tolerance {}), C1 got {}",
            c2_count,
            fair_share,
            tolerance,
            c1_count
        );

        // The fairness sample can finish before the composite transfers do.
        // Drain their terminal polls before shutdown cancels remaining tasks.
        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("sampled composites should drain before shutdown");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_two_composites_fair_share_regardless_of_fan_out() {
        let handle = test_handle(100);
        impl_two_composites_fair_share_regardless_of_fan_out(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_two_composites_fair_share_regardless_of_fan_out_managed_runtime() {
        // See note on test_composite_vs_single_fair_share_at_root_managed_runtime
        // for why target is lower under managed runtime.
        let handle = test_handle_managed(20);
        impl_two_composites_fair_share_regardless_of_fan_out(handle).await;
    }

    async fn impl_heterogeneous_within_group_proportional_share(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;

        // We create a single group (parent id=1) with two children directly.
        // c_small: 1 work item, c_large: 50 work items.
        let small_counter = DispatchCounter::new();
        let large_counter = DispatchCounter::new();

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        // Register the group so children can be inserted
        scheduler.register_empty_group_for_test(parent_id.id);

        let small_id = TransferId {
            id: 2,
            parent: Some(1),
        };
        let large_id = TransferId {
            id: 3,
            parent: Some(1),
        };

        let sm_small = Arc::new(CountedWork::new(1, small_counter.clone()));
        let sm_large = Arc::new(CountedWork::new(100, large_counter.clone()));

        let t_small = MockTransfer::new_with_handle(small_id, sm_small.clone(), handle.clone());
        let t_large = MockTransfer::new_with_handle(large_id, sm_large.clone(), handle.clone());

        scheduler.enqueue_transfer(Box::new(t_small));
        scheduler.enqueue_transfer(Box::new(t_large));

        // Wait for both to complete
        tokio::time::timeout(Duration::from_secs(10), async {
            while !sm_small.is_complete() || !sm_large.is_complete() {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("both children should complete");

        // c_small should complete well before c_large
        assert_eq!(small_counter.count(), 1);
        assert_eq!(large_counter.count(), 100);

        // c_small's first dispatch should happen within the first 10 global dispatches.
        // Since c_small only has 1 item and both start at the same vruntime,
        // c_small will be scheduled early. We verify it completed (which means
        // it was dispatched) while c_large was still running.
        // The fact that c_small is complete and c_large needed 100 items proves
        // c_small finished well before c_large.
        assert!(
            sm_small.is_complete(),
            "c_small should complete before c_large finishes all 100 items"
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_heterogeneous_within_group_proportional_share() {
        let handle = test_handle(4);
        impl_heterogeneous_within_group_proportional_share(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_heterogeneous_within_group_proportional_share_managed_runtime() {
        let handle = test_handle_managed(4);
        impl_heterogeneous_within_group_proportional_share(handle).await;
    }

    async fn impl_memory_cap_returns_pending_at_limit(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let composite = CompositeMock::new_blocking(
            id,
            handle.clone(),
            100, // total children
            5,   // memory cap
            counter.clone(),
            notify.clone(),
        );

        scheduler.enqueue_transfer(Box::new(composite));

        // Give the scheduler time to spawn children up to the cap
        tokio::time::sleep(Duration::from_millis(200)).await;

        // The composite should have spawned exactly 5 children (memory cap).
        // Children are blocking, so none complete. The composite returns Pending.
        assert_eq!(
            counter.count(),
            0,
            "no children should have completed (they're blocking)"
        );

        // The scheduler should have the parent + children tracked.
        let transfer_count = scheduler.transfer_count();
        assert!(
            transfer_count >= 1,
            "at least the composite should be tracked, got {}",
            transfer_count
        );

        // Don't release the barrier - children stay blocked, composite stays at cap
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            counter.count(),
            0,
            "still no completions without releasing barrier"
        );

        // Clean up via cancellation
        scheduler.cancel_transfer(id);
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancellation");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_cap_returns_pending_at_limit() {
        let handle = test_handle(10);
        impl_memory_cap_returns_pending_at_limit(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_cap_returns_pending_at_limit_managed_runtime() {
        let handle = test_handle_managed(10);
        impl_memory_cap_returns_pending_at_limit(handle).await;
    }

    async fn impl_memory_cap_release_resumes_spawning(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let composite = CompositeMock::new_blocking(
            id,
            handle.clone(),
            20, // total children (smaller for test tractability)
            5,  // memory cap
            counter.clone(),
            notify.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        // Wait for initial batch to be spawned and dispatched
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(counter.count(), 0, "children should be blocking");

        // Release children one at a time and verify the composite resumes spawning.
        // notify_waiters() wakes all current waiters; we use it in a loop to
        // release one child at a time (only one should be waiting at a time
        // since the scheduler dispatches them sequentially with target=10).
        for iteration in 0..3u64 {
            // Release one child by notifying
            notify.notify_waiters();

            // Wait for the completion to propagate
            tokio::time::timeout(Duration::from_secs(3), async {
                loop {
                    if counter.count() > iteration {
                        break;
                    }
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            })
            .await
            .unwrap_or_else(|_| {
                panic!(
                    "iteration {}: expected >{} completions, got {}",
                    iteration,
                    iteration,
                    counter.count()
                )
            });
        }

        // Verify at least 3 completions happened (proving the cycle works)
        assert!(
            counter.count() >= 3,
            "expected at least 3 completions after 3 releases, got {}",
            counter.count()
        );

        // Clean up via cancellation
        scheduler.cancel_transfer(id);
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_cap_release_resumes_spawning() {
        let handle = test_handle(10);
        impl_memory_cap_release_resumes_spawning(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_cap_release_resumes_spawning_managed_runtime() {
        let handle = test_handle_managed(10);
        impl_memory_cap_release_resumes_spawning(handle).await;
    }

    async fn impl_priority_change_shifts_root_share(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;

        // Two single transfers with delayed work items. Adding a small delay
        // makes the scheduling observable: the high-priority transfer accumulates
        // vruntime slower, so it gets scheduled more often and completes first.
        let hi_counter = DispatchCounter::new();
        let lo_counter = DispatchCounter::new();

        let hi_id = TransferId {
            id: 1,
            parent: None,
        };
        let lo_id = TransferId {
            id: 2,
            parent: None,
        };

        // Use WithDelay to slow execution so priority differences are observable
        let sm_hi = Arc::new(WithDelay::new(
            CountedWork::new(1000, hi_counter.clone()),
            Duration::from_millis(1),
        ));
        let sm_lo = Arc::new(WithDelay::new(
            CountedWork::new(1000, lo_counter.clone()),
            Duration::from_millis(1),
        ));

        let t_hi = MockTransfer::new_with_handle(hi_id, sm_hi, handle.clone());
        let t_lo = MockTransfer::new_with_handle(lo_id, sm_lo, handle.clone());

        // Enqueue and set priorities
        scheduler.enqueue_transfer(Box::new(t_hi));
        scheduler.enqueue_transfer(Box::new(t_lo));
        scheduler.set_priority(hi_id, 255); // high priority = more share
        scheduler.set_priority(lo_id, 64); // low priority = less share

        // Wait for enough dispatches to observe the priority difference.
        // With 1000 items per transfer and concurrency=4, we get ~250+
        // scheduling rounds which is enough to converge on the expected ratio.
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let total = hi_counter.count() + lo_counter.count();
                if total >= 800 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("should reach 800 dispatches");

        let hi_count = hi_counter.count();
        let lo_count = lo_counter.count();

        // 4x priority difference (255 vs 64) yields ~4x dispatch ratio
        // via the priority-scaled vruntime delta. With serialized
        // generate_work (single-runner admission via GenerateWorkGate),
        // the ratio converges to the theoretical value on both runtimes.
        // Threshold of 3.5 provides margin for CI scheduling noise.
        let ratio = hi_count as f64 / lo_count.max(1) as f64;
        assert!(
            ratio > 3.5,
            "expected ratio > 3.5, got {:.2} (hi={}, lo={})",
            ratio,
            hi_count,
            lo_count
        );

        // Cancel both transfers so the registry drains before shutdown.
        // The test only consumed ~800 of 2000 enqueued work items; without
        // cancellation, the remaining transfers stay in the registry holding
        // Arc<Handle> references, forming a cycle the runtime shutdown
        // doesn't break. Visible to LeakSanitizer at process exit.
        scheduler.cancel_transfer(hi_id);
        scheduler.cancel_transfer(lo_id);
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancellation");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_priority_change_shifts_root_share() {
        let handle = test_handle(4);
        impl_priority_change_shifts_root_share(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_priority_change_shifts_root_share_managed_runtime() {
        let handle = test_handle_managed(4);
        impl_priority_change_shifts_root_share(handle).await;
    }

    async fn impl_cancellation_cascades_in_hierarchical_structure(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let c_id = TransferId {
            id: 1,
            parent: None,
        };
        // Use blocking children with a short timeout so they eventually drain
        // after cancellation. Memory cap = 100 to spawn all immediately.
        let composite = CompositeMock::new_blocking(
            c_id,
            handle.clone(),
            20, // total children (smaller for test speed)
            20, // memory cap (spawn all immediately)
            counter.clone(),
            notify.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        // Wait for children to be spawned and dispatched (they'll block in execute)
        tokio::time::sleep(Duration::from_millis(300)).await;

        // Cancel the composite - this cascades to children
        assert!(scheduler.cancel_transfer(c_id).target.is_some());

        // Wait for scheduler to become idle. The in-flight execute futures
        // will observe cancellation via is_cancelled() and return early.
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancellation");

        // Group should be removed
        assert_eq!(
            scheduler.group_member_count(c_id.id),
            None,
            "group should be removed after cancellation"
        );

        // All transfers should be purged
        assert_eq!(
            scheduler.transfer_count(),
            0,
            "all transfers should be purged"
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancellation_cascades_in_hierarchical_structure() {
        let handle = test_handle(10);
        impl_cancellation_cascades_in_hierarchical_structure(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancellation_cascades_in_hierarchical_structure_managed_runtime() {
        let handle = test_handle_managed(10);
        impl_cancellation_cascades_in_hierarchical_structure(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_panic_in_composite_poll_work() {
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;

        // Panicking composite
        let panic_id = TransferId {
            id: 1,
            parent: None,
        };
        let panicker = PanickingCompositeMock::new(panic_id, handle.clone());
        scheduler.enqueue_transfer(Box::new(panicker));

        // Peer transfer that should complete normally
        let s_counter = DispatchCounter::new();
        let s_id = TransferId {
            id: 2,
            parent: None,
        };
        let sm = Arc::new(CountedWork::new(10, s_counter.clone()));
        let peer = MockTransfer::new_with_handle(s_id, sm.clone(), handle.clone());
        scheduler.enqueue_transfer(Box::new(peer));

        // Wait for scheduler to become idle
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle despite panic");

        // Peer should have completed all its work
        assert_eq!(
            s_counter.count(),
            10,
            "peer transfer should complete all work"
        );

        // Panicking composite's group should be removed
        assert_eq!(
            scheduler.group_member_count(panic_id.id),
            None,
            "panicking composite's group should be removed"
        );

        // Scheduler should be fully idle
        assert!(scheduler.is_idle());

        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Regression test: a composite that violates the Transfer contract
    /// (returns `Done` while children are still alive) must not hang the
    /// scheduler. The Done branch in `generate_work` defensively cleans
    /// up orphaned children rather than leaving them in `transfers` with
    /// no parent group to schedule them.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_done_with_live_children_does_not_hang() {
        let _logs = show_test_logs();
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        let (mock, _terminals) = BuggyDoneMock::new(parent_id, handle.clone(), 3);
        scheduler.enqueue_transfer(Box::new(mock));

        // Without defensive cleanup, the orphaned children stay in the
        // transfers map and the scheduler never reaches idle. The
        // timeout asserts cleanup actually fired.
        tokio::time::timeout(Duration::from_secs(2), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should reach idle; orphaned children would hang it");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// Verifies the Done-branch defensive cleanup actually cancels the
    /// orphaned children (calls `cancel_descriptor`), not just removing
    /// them from the map. Each child's terminal receiver should fire so
    /// the children's handles resolve as cancelled rather than hanging.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_done_orphans_have_terminal_signaled() {
        let _logs = show_test_logs();
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        let (mock, terminals) = BuggyDoneMock::new(parent_id, handle.clone(), 3);
        scheduler.enqueue_transfer(Box::new(mock));

        // Wait for the parent to be polled (children get spawned and
        // terminals filled in during the same poll_work call).
        tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                if terminals.lock().unwrap().is_some()
                    && !terminals.lock().unwrap().as_ref().unwrap().is_empty()
                {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("BuggyDoneMock should populate child terminals during poll_work");

        let child_terminals = terminals
            .lock()
            .unwrap()
            .take()
            .expect("child terminals should be available");
        assert_eq!(child_terminals.len(), 3, "expected 3 child terminals");

        // Each child should be cancelled by the Done branch's defensive
        // cleanup; their terminal receivers fire when cancel_descriptor
        // calls signal_terminal.
        for term in child_terminals {
            tokio::time::timeout(Duration::from_secs(2), term)
                .await
                .expect("child terminal should fire (cancelled by Done branch)")
                .expect("terminal sender should not have been dropped");
        }

        crate::runtime::test_util::shutdown(&handle).await;
    }

    /// A transfer that becomes terminal without calling `signal_terminal`,
    /// while a child is still registered, is removed by `on_completion`'s
    /// terminal+idle path. The scheduler must signal the removed transfer's
    /// terminal so its owning handle's `join()` resolves rather than hanging.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_terminal_without_signal_does_not_strand_handle() {
        let _logs = show_test_logs();
        let handle = test_handle(2);
        let scheduler = &handle.scheduler;

        let parent_id = TransferId {
            id: 1,
            parent: None,
        };
        let (mock, completion_rx) = TerminalWithoutSignalMock::new(parent_id, handle.clone());
        scheduler.enqueue_transfer(Box::new(mock));

        // The parent goes terminal without signaling; the scheduler removes it
        // (terminal+idle) and must signal its completion. The handle's join
        // (modeled here by awaiting completion_rx) must resolve, not hang.
        tokio::time::timeout(Duration::from_secs(2), completion_rx)
            .await
            .expect("parent completion must be signaled on scheduler removal, not strand")
            .expect("terminal sender should not have been dropped");

        // And the scheduler drains (orphan child cleaned up).
        tokio::time::timeout(Duration::from_secs(2), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should reach idle");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    // =========================================================================
    // PollWork::Spawned integration tests
    //
    // These tests verify the single-ticket spawn variant: no dispatch increment,
    // re-poll semantics, CFS vruntime spin guard, and capacity bounding.
    // =========================================================================

    /// Mock that returns `Spawned` a fixed number of times then `Done`.
    /// Tracks the number of times `poll_work` is called.
    #[derive(Debug)]
    struct SpawnedThenDone {
        spawned_remaining: AtomicUsize,
        poll_count: AtomicUsize,
    }

    impl SpawnedThenDone {
        fn new(spawned_count: usize) -> Self {
            Self {
                spawned_remaining: AtomicUsize::new(spawned_count),
                poll_count: AtomicUsize::new(0),
            }
        }

        fn poll_count(&self) -> usize {
            self.poll_count.load(Ordering::SeqCst)
        }
    }

    impl MockStateMachine for SpawnedThenDone {
        fn poll_work(&self, _id: TransferId) -> PollWork {
            self.poll_count.fetch_add(1, Ordering::SeqCst);
            let prev = self.spawned_remaining.fetch_sub(1, Ordering::SeqCst);
            if prev == 0 {
                // Underflowed; we already returned all Spawned items.
                PollWork::Done
            } else {
                PollWork::Spawned
            }
        }

        fn execute<'a>(
            &'a self,
            _work: &'a mut IoRequest,
        ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
            unreachable!("SpawnedThenDone never returns PollWork::Ready")
        }
    }

    async fn impl_spawned_does_not_increment_dispatched(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        let sm = Arc::new(SpawnedThenDone::new(1));
        let transfer = Box::new(MockTransfer::new_with_handle(id, sm, handle.clone()));
        scheduler.enqueue_transfer(transfer);

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        // The Spawned arm must not have incremented dispatched. After the
        // transfer completes (Done), dispatched should be back to 0.
        assert_eq!(
            scheduler.dispatched_for_test(),
            0,
            "dispatched should be 0 after Spawned+Done (no work items dispatched)"
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_does_not_increment_dispatched() {
        let handle = test_handle(4);
        impl_spawned_does_not_increment_dispatched(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_does_not_increment_dispatched_managed_runtime() {
        let handle = test_handle_managed(4);
        impl_spawned_does_not_increment_dispatched(handle).await;
    }

    async fn impl_spawned_reinserts_and_repolls(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let id = TransferId {
            id: 1,
            parent: None,
        };

        let n = 5;
        let sm = Arc::new(SpawnedThenDone::new(n));
        let transfer = Box::new(MockTransfer::new_with_handle(
            id,
            sm.clone(),
            handle.clone(),
        ));
        scheduler.enqueue_transfer(transfer);

        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        // poll_work should have been called N+1 times (N Spawned + 1 Done).
        assert_eq!(
            sm.poll_count(),
            n + 1,
            "expected {} polls (N Spawned + 1 Done), got {}",
            n + 1,
            sm.poll_count()
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_reinserts_and_repolls() {
        let handle = test_handle(4);
        impl_spawned_reinserts_and_repolls(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_reinserts_and_repolls_managed_runtime() {
        let handle = test_handle_managed(4);
        impl_spawned_reinserts_and_repolls(handle).await;
    }

    async fn impl_single_ticket_caps_materialization_near_target(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let id = TransferId {
            id: 1,
            parent: None,
        };

        let target = 200;
        let total_children = 2000;
        let composite = SingleTicketCompositeMock::new_blocking(
            id,
            handle.clone(),
            total_children,
            100_000, // memory_cap is NOT the limiter
            counter.clone(),
            notify.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        // Sample dispatched repeatedly over a window and assert the max
        // observed stays bounded by the target. This approach is more
        // robust than a single sleep+sample (immune to scheduling jitter).
        let mut max_observed: usize = 0;
        let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
        while tokio::time::Instant::now() < deadline {
            let dispatched = scheduler.dispatched_for_test();
            if dispatched > max_observed {
                max_observed = dispatched;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        // `dispatched` is hard-capped at the target: `has_capacity`
        // (`dispatched < target`) gates the generate_work pop loop before the
        // single `fetch_add` in the Ready arm, and the gate serializes that
        // loop to one runner, so `dispatched` never exceeds `target`. Each
        // child increments it by 1 when its poll yields Ready; the parent's
        // Spawned arm never does. Assert the exact bound so a regression that
        // spawned in batches (overshooting by the batch size) is caught, not
        // just the gross "materialize all `total_children`" failure.
        assert!(
            max_observed <= target,
            "max dispatched ({}) must not exceed target ({})",
            max_observed,
            target
        );
        assert!(
            max_observed > 0,
            "at least some children should have been dispatched"
        );

        // Release all children and wait for idle.
        notify.notify_waiters();
        // Keep notifying to release children as they arrive.
        let notify_clone = notify.clone();
        let notifier = tokio::spawn(async move {
            loop {
                notify_clone.notify_waiters();
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        });

        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after releasing children");

        notifier.abort();
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_caps_materialization_near_target() {
        let handle = test_handle(200);
        impl_single_ticket_caps_materialization_near_target(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_caps_materialization_near_target_managed_runtime() {
        let handle = test_handle_managed(200);
        impl_single_ticket_caps_materialization_near_target(handle).await;
    }

    /// A fused `PollWork::Ready { spawned: true }` poll charges the descriptor
    /// BOTH the full IO work cost (for the dispatched reap io) and the reduced
    /// spawn cost (for the child spawned in the same poll). Deleting the fused
    /// `work_generated_spawn()` in the scheduler's `Ready` arm would leave only
    /// the IO charge; this pins that both are applied so that regression fails.
    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_fused_ready_spawned_charges_both_io_and_spawn_vruntime() {
        let handle = test_handle(4);
        let scheduler = &handle.scheduler;

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let sm = Arc::new(FusedReadySpawnedMock::new());
        let transfer = Box::new(MockTransfer::new_with_handle(id, sm, handle.clone()));

        // `enqueue_transfer` drives `generate_work` synchronously: the mock is
        // popped and polled once, returns `Ready { spawned: true }`, and the
        // scheduler charges both `work_generated` (IO) and `work_generated_spawn`
        // before returning. The mock returns `Pending` on any later poll, so no
        // further vruntime is charged.
        scheduler.enqueue_transfer(transfer);

        // At the default priority (128), the fused poll advances vruntime by the
        // IO delta plus the spawn delta. Compare against the real delta formula
        // so the assertion tracks the constants rather than a magic number.
        let expected = vruntime_delta_for_cost(IO_WORK_COST, 128)
            + vruntime_delta_for_cost(SPAWN_WORK_COST, 128);
        let observed = {
            let transfers = scheduler.0.transfers.read().unwrap();
            transfers
                .get(&id)
                .expect("transfer should still be present")
                .vruntime()
        };
        assert_eq!(
            observed,
            expected,
            "fused Ready{{spawned:true}} must charge IO ({}) + spawn ({}) = {}, got {}",
            vruntime_delta_for_cost(IO_WORK_COST, 128),
            vruntime_delta_for_cost(SPAWN_WORK_COST, 128),
            expected,
            observed
        );

        scheduler.cancel_transfer(id).wait_for_idle().await;
        crate::runtime::test_util::shutdown(&handle).await;
    }

    async fn impl_single_ticket_completes_all(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();

        let id = TransferId {
            id: 1,
            parent: None,
        };
        let total_children = 500;
        let composite = SingleTicketCompositeMock::new(
            id,
            handle.clone(),
            total_children,
            1,       // work_per_child
            100_000, // memory_cap (won't be hit)
            counter.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        assert_eq!(
            counter.count(),
            total_children,
            "all {} children should have been dispatched",
            total_children
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_completes_all() {
        let handle = test_handle(50);
        impl_single_ticket_completes_all(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_completes_all_managed_runtime() {
        let handle = test_handle_managed(50);
        impl_single_ticket_completes_all(handle).await;
    }

    async fn impl_single_ticket_two_composites_fair_share(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;

        const C1: u8 = 1;
        const C2: u8 = 2;
        // Two thousand dispatches per tree leave room for the fixed fairness
        // sample after asymmetric managed-runtime startup without reaching
        // either tree's finite-work tail.
        const TOTAL_CHILDREN: u64 = 400;
        const WORK_PER_CHILD: u64 = 5;
        const WARMUP_PER_COMPOSITE: usize = 100;
        const SAMPLE_DISPATCHES: usize = 1200;

        let work_per_composite = TOTAL_CHILDREN * WORK_PER_CHILD;
        let total_work = 2 * work_per_composite;
        let trace = DispatchTrace::new(total_work as usize);
        let c1_counter = trace.counter(C1);
        let c2_counter = trace.counter(C2);

        let c1_id = TransferId {
            id: 1,
            parent: None,
        };
        let c2_id = TransferId {
            id: 2,
            parent: None,
        };

        let c1 = SingleTicketCompositeMock::new(
            c1_id,
            handle.clone(),
            TOTAL_CHILDREN,
            WORK_PER_CHILD,
            100_000, // memory_cap
            c1_counter.clone(),
        );
        let c2 = SingleTicketCompositeMock::new(
            c2_id,
            handle.clone(),
            TOTAL_CHILDREN,
            WORK_PER_CHILD,
            100_000, // memory_cap
            c2_counter.clone(),
        );

        scheduler.enqueue_transfer(Box::new(c1));
        scheduler.enqueue_transfer(Box::new(c2));

        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                let completed = c1_counter.count() + c2_counter.count();
                if completed >= total_work && scheduler.is_idle() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("both composites should complete");

        assert_eq!(c1_counter.count(), work_per_composite);
        assert_eq!(c2_counter.count(), work_per_composite);

        // The managed runtime can dispatch C1 while the test thread enqueues
        // C2. Locate the exact execution where both trees have completed the
        // warmup, then measure a fixed window after that one-sided prefix.
        let dispatches = trace.snapshot();
        assert_eq!(dispatches.len(), total_work as usize);
        let mut c1_seen = 0;
        let mut c2_seen = 0;
        let mut sample_start = None;
        let mut overlap_end = None;
        for (index, label) in dispatches.iter().copied().enumerate() {
            match label {
                C1 => c1_seen += 1,
                C2 => c2_seen += 1,
                other => panic!("unknown dispatch trace label {other}"),
            }
            if sample_start.is_none()
                && c1_seen >= WARMUP_PER_COMPOSITE
                && c2_seen >= WARMUP_PER_COMPOSITE
            {
                sample_start = Some(index + 1);
            }
            if overlap_end.is_none()
                && (c1_seen == work_per_composite as usize
                    || c2_seen == work_per_composite as usize)
            {
                // This dispatch consumed one tree's final work item. Later
                // entries cannot measure fair competition between two
                // runnable trees.
                overlap_end = Some(index + 1);
            }
        }

        let sample_start = sample_start.expect("both composites should reach the warmup");
        let overlap_end = overlap_end.expect("one composite should finish");
        let sample_end = sample_start + SAMPLE_DISPATCHES;
        assert!(
            sample_end <= overlap_end,
            "only {} jointly runnable dispatches remain after the warmup; expected \
             {SAMPLE_DISPATCHES}",
            overlap_end.saturating_sub(sample_start)
        );
        let sample = &dispatches[sample_start..sample_end];
        let c1_count = sample.iter().filter(|&&label| label == C1).count() as u64;
        let c2_count = sample.iter().filter(|&&label| label == C2).count() as u64;
        let total = SAMPLE_DISPATCHES as u64;
        let fair_share = total as f64 / 2.0;
        let tolerance = fair_share * 0.10;

        assert!(
            (c1_count as f64 - fair_share).abs() < tolerance,
            "C1 got {} dispatches, expected ~{} (tolerance {}), C2 got {}",
            c1_count,
            fair_share,
            tolerance,
            c2_count
        );
        assert!(
            (c2_count as f64 - fair_share).abs() < tolerance,
            "C2 got {} dispatches, expected ~{} (tolerance {}), C1 got {}",
            c2_count,
            fair_share,
            tolerance,
            c1_count
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_two_composites_fair_share() {
        let handle = test_handle(100);
        impl_single_ticket_two_composites_fair_share(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_two_composites_fair_share_managed_runtime() {
        let handle = test_handle_managed(20);
        impl_single_ticket_two_composites_fair_share(handle).await;
    }

    async fn impl_single_ticket_memory_cap_backstops(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let id = TransferId {
            id: 1,
            parent: None,
        };

        let memory_cap = 10; // Much less than target
        let total_children = 100;
        let composite = SingleTicketCompositeMock::new_blocking(
            id,
            handle.clone(),
            total_children,
            memory_cap,
            counter.clone(),
            notify.clone(),
        );
        scheduler.enqueue_transfer(Box::new(composite));

        // Wait for spawning to stabilize. Children block, so in-flight count
        // should never exceed memory_cap.
        tokio::time::sleep(Duration::from_millis(500)).await;

        // dispatched measures how many children are currently in-flight
        // (blocking in execute). This should be at most memory_cap.
        let dispatched = scheduler.dispatched_for_test();
        assert!(
            dispatched <= memory_cap as usize + 2, // small tolerance for timing
            "dispatched ({}) should not exceed memory_cap ({})",
            dispatched,
            memory_cap
        );

        // Clean up via cancellation.
        scheduler.cancel_transfer(id);
        tokio::time::timeout(Duration::from_secs(5), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after cancellation");

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_memory_cap_backstops() {
        let handle = test_handle(200);
        impl_single_ticket_memory_cap_backstops(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_single_ticket_memory_cap_backstops_managed_runtime() {
        let handle = test_handle_managed(200);
        impl_single_ticket_memory_cap_backstops(handle).await;
    }

    /// A composite returning Spawned repeatedly must yield to a concurrently-ready
    /// peer. The vruntime charge on the Spawned arm prevents monopolization.
    async fn impl_spawned_spin_guard_does_not_starve_peer(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let poll_log = Arc::new(std::sync::Mutex::new(Vec::new()));
        // Hold generation so both transfers enter the ready set before either is polled.
        let mut setup = scheduler
            .0
            .generate_work_gate
            .try_acquire()
            .expect("scheduler must be idle before setup");

        // Composite that spawns via Spawned: 200 children, 1 work each.
        let c_counter = DispatchCounter::new();
        let c_id = TransferId {
            id: 1,
            parent: None,
        };
        let composite = SingleTicketCompositeMock::new(
            c_id,
            handle.clone(),
            200,
            1,       // work_per_child
            100_000, // memory_cap (won't be hit)
            c_counter.clone(),
        )
        .with_poll_log(poll_log.clone());
        scheduler.enqueue_transfer(Box::new(composite));

        // Peer single transfer: 200 work items dispatched via Ready.
        let s_counter = DispatchCounter::new();
        let s_id = TransferId {
            id: 2,
            parent: None,
        };
        let peer = ChildMockTransfer::new(s_id, handle.clone(), 200, s_counter.clone())
            .with_poll_log(poll_log.clone());
        scheduler.enqueue_transfer(Box::new(peer));

        // Acknowledge the enqueue requests, release the gate, and drive both together.
        while !setup.try_release() {}
        scheduler.generate_work();

        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        crate::runtime::test_util::shutdown(&handle).await;

        // Observe scheduler selection, independent of execution order on runtime threads.
        let log = poll_log.lock().unwrap();
        assert_eq!(
            log.first(),
            Some(&c_id.id),
            "composite must be polled first"
        );
        let first_peer = log
            .iter()
            .position(|&id| id == s_id.id)
            .expect("peer must be polled");
        let composite_polls = log[..first_peer]
            .iter()
            .filter(|&&id| id == c_id.id)
            .count();
        assert!(
            composite_polls < 100,
            "peer must be polled before 100 composite polls (got {composite_polls}); spin guard may be broken"
        );
        assert_eq!(c_counter.count(), 200);
        assert_eq!(s_counter.count(), 200);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_spin_guard_does_not_starve_peer() {
        let handle = test_handle(50);
        impl_spawned_spin_guard_does_not_starve_peer(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawned_spin_guard_does_not_starve_peer_managed_runtime() {
        let handle = test_handle_managed(20);
        impl_spawned_spin_guard_does_not_starve_peer(handle).await;
    }

    // =========================================================================
    // Diagnostic: spawn model — alive-children vs dispatched under various
    // workload shapes.
    //
    // These tests measure BOTH max_dispatched AND max_alive (spawned - terminated)
    // to determine whether the scheduler bounds alive children at the concurrency
    // target or lets them run to memory_cap.
    // =========================================================================

    /// Shared implementation: drives a non-blocking SingleTicketCompositeMock,
    /// samples dispatched and alive over a window, then drains to idle.
    /// Returns (max_dispatched, max_alive).
    async fn impl_spawn_model_non_blocking(
        handle: Arc<Handle>,
        _target: usize,
        work_per_child: u64,
        total_children: u64,
    ) -> (usize, u64) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();

        let id = TransferId {
            id: 1,
            parent: None,
        };

        let composite = SingleTicketCompositeMock::new(
            id,
            handle.clone(),
            total_children,
            work_per_child,
            100_000, // memory_cap very high — not the limiter
            counter.clone(),
        );
        let (spawned_handle, terminated_handle) = composite.observer_handles();
        scheduler.enqueue_transfer(Box::new(composite));

        // Sample dispatched and alive over a window.
        let mut max_dispatched: usize = 0;
        let mut max_alive: u64 = 0;
        let deadline = tokio::time::Instant::now() + Duration::from_millis(800);
        while tokio::time::Instant::now() < deadline {
            let dispatched = scheduler.dispatched_for_test();
            let spawned = spawned_handle.load(Ordering::SeqCst);
            let terminated = terminated_handle.load(Ordering::SeqCst);
            let alive = spawned.saturating_sub(terminated);

            if dispatched > max_dispatched {
                max_dispatched = dispatched;
            }
            if alive > max_alive {
                max_alive = alive;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }

        // Wait for idle (all children complete).
        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after all children complete");

        crate::runtime::test_util::shutdown(&handle).await;
        (max_dispatched, max_alive)
    }

    // --- Test 1: small objects (work_per_child=1, non-blocking) ---

    async fn impl_test_spawn_model_small_objects(handle: Arc<Handle>) {
        let target: usize = 8;
        let (max_dispatched, max_alive) =
            impl_spawn_model_non_blocking(handle, target, 1, 160).await;

        // Dispatched should be bounded near target.
        assert!(
            max_dispatched <= target + 4,
            "DIAGNOSTIC small_objects: max_dispatched ({}) should be near target ({}); \
             max_alive={}",
            max_dispatched,
            target,
            max_alive,
        );

        // Diagnostic: report alive. If alive tracks target, assert it. If it runs
        // to memory_cap, document that finding.
        // With non-blocking children (work_per_child=1), each child dispatches then
        // frees its slot quickly but stays Active until a subsequent poll marks it
        // Done. We assert alive is bounded by something reasonable and print the
        // observed value. A tight bound is validated after the first run.
        println!(
            "DIAGNOSTIC small_objects: target={}, max_dispatched={}, max_alive={}",
            target, max_dispatched, max_alive
        );
        // Alive should stay bounded (not run to total_children=160 or memory_cap=100_000).
        // Based on observation we expect alive to stay near target (children terminate
        // quickly). Assert a generous upper bound and report the actual value.
        assert!(
            max_alive <= 100,
            "DIAGNOSTIC small_objects: max_alive ({}) ran well beyond expected bounds; \
             target={}, max_dispatched={}",
            max_alive,
            target,
            max_dispatched,
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_small_objects() {
        let _logs = show_test_logs();
        let handle = test_handle(8);
        impl_test_spawn_model_small_objects(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_small_objects_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(8);
        impl_test_spawn_model_small_objects(handle).await;
    }

    // --- Test 2: large objects (work_per_child=10, non-blocking) ---

    async fn impl_test_spawn_model_large_objects(handle: Arc<Handle>) {
        let target: usize = 8;
        let (max_dispatched, max_alive) =
            impl_spawn_model_non_blocking(handle, target, 10, 160).await;

        // Dispatched should be bounded near target.
        assert!(
            max_dispatched <= target + 4,
            "DIAGNOSTIC large_objects: max_dispatched ({}) should be near target ({}); \
             max_alive={}",
            max_dispatched,
            target,
            max_alive,
        );

        // With work_per_child=10, each child occupies multiple dispatched slots over
        // its lifetime.
        //
        // OBSERVED: With tokio runtime, alive stays well below target (~5) because
        // one child produces many work items that fill dispatched slots. With the
        // managed runtime (parallel threads), children complete work items faster,
        // allowing the composite to spawn more children before dispatched fills up —
        // alive can reach ~100+ even with target=8. This shows alive-children are
        // NOT tightly bounded by the concurrency target for multi-work-item children;
        // the dispatched counter gates new spawns but doesn't prevent alive from
        // growing when children free slots faster than the composite is throttled.
        println!(
            "DIAGNOSTIC large_objects: target={}, max_dispatched={}, max_alive={}",
            target, max_dispatched, max_alive
        );
        // Allow up to total_children since we observed alive can run high with
        // parallel runtimes. The key diagnostic: max_dispatched stays at target.
        assert!(
            max_alive <= 160,
            "DIAGNOSTIC large_objects: max_alive ({}) exceeded total_children; \
             target={}, max_dispatched={}",
            max_alive,
            target,
            max_dispatched,
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_large_objects() {
        let _logs = show_test_logs();
        let handle = test_handle(8);
        impl_test_spawn_model_large_objects(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_large_objects_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(8);
        impl_test_spawn_model_large_objects(handle).await;
    }

    // --- Test 3: blocking children (dispatched slot held) ---

    async fn impl_test_spawn_model_blocking_children(handle: Arc<Handle>) {
        let target: usize = 8;
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let notify = Arc::new(tokio::sync::Notify::new());

        let id = TransferId {
            id: 1,
            parent: None,
        };

        let composite = SingleTicketCompositeMock::new_blocking(
            id,
            handle.clone(),
            160,     // total_children
            100_000, // memory_cap very high
            counter.clone(),
            notify.clone(),
        );
        let (spawned_handle, terminated_handle) = composite.observer_handles();
        scheduler.enqueue_transfer(Box::new(composite));

        // Sample over a window.
        let mut max_dispatched: usize = 0;
        let mut max_alive: u64 = 0;
        let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
        while tokio::time::Instant::now() < deadline {
            let dispatched = scheduler.dispatched_for_test();
            let spawned = spawned_handle.load(Ordering::SeqCst);
            let terminated = terminated_handle.load(Ordering::SeqCst);
            let alive = spawned.saturating_sub(terminated);

            if dispatched > max_dispatched {
                max_dispatched = dispatched;
            }
            if alive > max_alive {
                max_alive = alive;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }

        println!(
            "DIAGNOSTIC blocking: target={}, max_dispatched={}, max_alive={}",
            target, max_dispatched, max_alive
        );

        // Blocking children hold their dispatched slot, so dispatched ~ alive ~ target.
        // OBSERVED: max_dispatched=8 (exactly target), max_alive=12. The overshoot in
        // alive (~target+4) comes from children spawned just before the dispatched
        // counter fills — they are alive but their work item hasn't been counted as
        // dispatched yet during the spawn-to-poll window.
        assert!(
            max_dispatched <= target + 4,
            "DIAGNOSTIC blocking: max_dispatched ({}) should be near target ({}); \
             max_alive={}",
            max_dispatched,
            target,
            max_alive,
        );
        assert!(
            max_alive <= (target as u64) + 8,
            "DIAGNOSTIC blocking: max_alive ({}) should be near target ({}); \
             max_dispatched={}",
            max_alive,
            target,
            max_dispatched,
        );
        assert!(
            max_dispatched > 0,
            "DIAGNOSTIC blocking: at least some children should be dispatched"
        );

        // Release all children and drain.
        notify.notify_waiters();
        let notify_clone = notify.clone();
        let notifier = tokio::spawn(async move {
            loop {
                notify_clone.notify_waiters();
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        });

        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle after releasing children");

        notifier.abort();
        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_blocking_children() {
        let _logs = show_test_logs();
        let handle = test_handle(8);
        impl_test_spawn_model_blocking_children(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_model_blocking_children_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(8);
        impl_test_spawn_model_blocking_children(handle).await;
    }

    // --- Test 4: target=1, non-blocking — proves child is polled before composite
    //     re-spawns unboundedly ---

    async fn impl_test_spawn_child_polled_before_composite_respawns(handle: Arc<Handle>) {
        let target: usize = 1;
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();

        let id = TransferId {
            id: 1,
            parent: None,
        };

        // With target=1 and work_per_child=1, the composite spawns a child (Spawned,
        // no dispatched increment). The child is polled -> Ready -> dispatched=1 -> execute
        // -> dispatched returns to 0. The composite can then spawn the next child. If the
        // scheduler correctly interleaves, dispatched never exceeds 1 and alive stays
        // tightly bounded.
        let composite = SingleTicketCompositeMock::new(
            id,
            handle.clone(),
            50, // total_children (enough to observe steady-state)
            1,  // work_per_child
            100_000,
            counter.clone(),
        );
        let (spawned_handle, terminated_handle) = composite.observer_handles();
        scheduler.enqueue_transfer(Box::new(composite));

        let mut max_dispatched: usize = 0;
        let mut max_alive: u64 = 0;
        let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
        while tokio::time::Instant::now() < deadline {
            let dispatched = scheduler.dispatched_for_test();
            let spawned = spawned_handle.load(Ordering::SeqCst);
            let terminated = terminated_handle.load(Ordering::SeqCst);
            let alive = spawned.saturating_sub(terminated);

            if dispatched > max_dispatched {
                max_dispatched = dispatched;
            }
            if alive > max_alive {
                max_alive = alive;
            }
            tokio::time::sleep(Duration::from_millis(2)).await;
        }

        // Wait for idle.
        tokio::time::timeout(Duration::from_secs(15), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        println!(
            "DIAGNOSTIC target=1: target={}, max_dispatched={}, max_alive={}",
            target, max_dispatched, max_alive
        );

        // The invariant: with target=1, dispatched never exceeds 1 (allow 2 for
        // the sample-race between reading dispatched and a completion). This is
        // the concurrency guarantee single-ticket spawn provides.
        //
        // `max_alive` (children spawned but not yet reaped) is printed as a
        // diagnostic but deliberately not asserted: on the managed runtime a
        // burst of parallel completions leaves children Active-but-unreaped
        // faster than the single parent retires them, so alive spikes well above
        // the target without any oversubscription (dispatched stays bounded).
        // A real runaway trips the dispatched bound; the at-scale materialization
        // bound is covered by `test_single_ticket_caps_materialization_near_target`.
        assert!(
            max_dispatched <= 2,
            "DIAGNOSTIC target=1: max_dispatched ({}) should be <=2; max_alive={}",
            max_dispatched,
            max_alive,
        );

        crate::runtime::test_util::shutdown(&handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_child_polled_before_composite_respawns() {
        let _logs = show_test_logs();
        let handle = test_handle(1);
        impl_test_spawn_child_polled_before_composite_respawns(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_spawn_child_polled_before_composite_respawns_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(1);
        impl_test_spawn_child_polled_before_composite_respawns(handle).await;
    }

    // --- Pop-sequence diagnostic: observe the ACTUAL parent/child poll order ---
    //
    // The count-based tests above show that alive-children can exceed the
    // concurrency target, but not *why*. This test records the exact order in
    // which the composite and its children are polled (each `poll_work` appends
    // its id to a shared log) so the interleaving is directly observable.
    //
    // Expected-correct behavior: after the composite spawns a child (returns
    // `Spawned`, which charges the composite's vruntime), the just-enqueued
    // child should out-rank the composite in the ready set and be polled before
    // the composite spawns again — producing an interleaved sequence
    // [composite, child, composite, child, ...], with the composite never
    // taking a long unbroken run of self-polls. A long leading run of the
    // composite id means it keeps winning the pop over its own children and
    // materializes many children before any of them run — the over-spawn.
    //
    // Uses target=2 on a single-threaded runtime so the initial spawn burst is
    // driven synchronously by one `generate_work` pass (deterministic order;
    // completion timing is irrelevant to the spawn-ordering question).
    async fn impl_test_composite_child_poll_interleaving(handle: Arc<Handle>) {
        let scheduler = &handle.scheduler;
        let counter = DispatchCounter::new();
        let poll_log = Arc::new(std::sync::Mutex::new(Vec::<u64>::new()));

        let composite_id = 1u64;
        let id = TransferId {
            id: composite_id,
            parent: None,
        };
        // work_per_child=1 (small objects), high memory_cap so only the
        // scheduler's capacity gate limits spawning, enough children to see the
        // steady-state pattern.
        let composite = SingleTicketCompositeMock::new(id, handle.clone(), 50, 1, 100_000, counter)
            .with_poll_log(poll_log.clone());
        scheduler.enqueue_transfer(Box::new(composite));

        tokio::time::timeout(Duration::from_secs(30), async {
            while !scheduler.is_idle() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("scheduler should become idle");

        let log = poll_log.lock().unwrap().clone();
        assert!(!log.is_empty(), "poll log should record polls");

        // Longest unbroken run of consecutive composite self-polls (no child
        // polled in between). 1 = perfect interleave; large = over-spawn.
        let mut longest_composite_run = 0usize;
        let mut current_run = 0usize;
        for &tid in &log {
            if tid == composite_id {
                current_run += 1;
                longest_composite_run = longest_composite_run.max(current_run);
            } else {
                current_run = 0;
            }
        }

        let composite_polls = log.iter().filter(|&&t| t == composite_id).count();
        let child_polls = log.len() - composite_polls;

        println!(
            "DIAGNOSTIC poll-interleaving: total_polls={}, composite_polls={}, \
             child_polls={}, longest_composite_run={}",
            log.len(),
            composite_polls,
            child_polls,
            longest_composite_run,
        );

        // Diagnostic assertion: the composite must eventually cede to children
        // (children do get polled and the transfer completes). The
        // longest_composite_run value is the finding — reported above. We assert
        // only that children are polled at all and the run is bounded by the
        // number spawned, so this test documents observed reality rather than
        // asserting a not-yet-decided tight interleave bound.
        assert!(child_polls > 0, "children must be polled");
        assert!(
            longest_composite_run <= log.len(),
            "run cannot exceed total polls"
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_composite_child_poll_interleaving() {
        let _logs = show_test_logs();
        let handle = test_handle(2);
        impl_test_composite_child_poll_interleaving(handle).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_composite_child_poll_interleaving_managed_runtime() {
        let _logs = show_test_logs();
        let handle = test_handle_managed(2);
        impl_test_composite_child_poll_interleaving(handle).await;
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    //! Loom verification of the scheduler's registry lock protocols.
    //!
    //! The first protocol coordinates enqueue and cancellation across the
    //! transfer registry and ready-set group registry. The second coordinates
    //! transfer registration with buffer-pool idle epochs so active work cannot
    //! leave reclamation armed.
    //! (The `generate_work` admission protocol is verified in
    //! [`super::super::gate`], co-located with its unit.)
    //!
    //! The protocol coordinates two independent locks:
    //!   - `Scheduler.transfers: RwLock<HashMap<TransferId, _>>`
    //!     — owned by `Scheduler`, tracks every alive transfer.
    //!   - `ReadySet.by_group: RwLock<HashMap<u64, _>>`
    //!     — owned by `ReadySet`, tracks which top-level transfers (groups)
    //!     have an entry in the root tree.
    //!
    //! The invariant the protocol must uphold: no entry remains in the
    //! transfers map whose parent group has been removed from the by_group
    //! map. A violation means a child has been orphaned in the scheduler,
    //! leaving its handle hung forever.
    //!
    //! Both locks are acquired in a consistent order in production:
    //! `transfers.write()` first, then `by_group` (read for enqueue,
    //! write for cancel), with cancel holding `transfers.write` across
    //! the `by_group.write` so the two map mutations are atomic from any
    //! observer's perspective.
    //!
    //! These tests exercise a faithful shim (`LoomScheduler`) whose
    //! `enqueue_transfer` and `cancel_transfer` methods mirror the
    //! production lock dance line-for-line. The shim drops the
    //! TransferDescriptor / Handle / runtime machinery (none of which
    //! participate in the lock-ordering protocol). When the production
    //! methods change, the shim must be kept in sync.

    use loom::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use loom::sync::{Arc, Mutex, RwLock};
    use loom::thread;
    use std::collections::HashMap;

    /// Mirrors `TransferId`: id + optional parent.
    #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
    struct TidShim {
        id: u64,
        parent: Option<u64>,
    }

    #[derive(Default)]
    struct IdleEpoch {
        activity: u64,
        deadline: Option<u64>,
        publications: usize,
    }

    /// Mirrors scheduler lifecycle publication without descriptor machinery.
    ///
    /// `transfers`, `dispatched`, and `idle_candidate` use the same operations
    /// and ordering as production. `idle` reduces the client callback and pool
    /// maintenance state to the epoch fields needed to detect stale or missing
    /// idle events.
    struct LoomIdleScheduler {
        transfers: RwLock<usize>,
        dispatched: AtomicUsize,
        idle_candidate: AtomicBool,
        idle: Mutex<IdleEpoch>,
    }

    impl LoomIdleScheduler {
        fn new(transfers: usize, dispatched: usize, idle_candidate: bool) -> Self {
            Self {
                transfers: RwLock::new(transfers),
                dispatched: AtomicUsize::new(dispatched),
                idle_candidate: AtomicBool::new(idle_candidate),
                idle: Mutex::new(IdleEpoch::default()),
            }
        }

        fn enqueue_transfer(&self) {
            let mut transfers = self.transfers.write().unwrap();
            *transfers += 1;
            self.idle_candidate.store(false, Ordering::SeqCst);

            let mut idle = self.idle.lock().unwrap();
            idle.activity = idle.activity.wrapping_add(1);
            idle.deadline = None;
        }

        fn remove_transfer(&self) {
            let mut transfers = self.transfers.write().unwrap();
            assert!(*transfers > 0);
            *transfers -= 1;
            let registry_became_empty = *transfers == 0;
            if registry_became_empty {
                self.idle_candidate.store(true, Ordering::SeqCst);
            }
            drop(transfers);
            if registry_became_empty {
                self.publish_global_idle_if_candidate();
            }
        }

        fn release_dispatch(&self) {
            let previous = self.dispatched.fetch_sub(1, Ordering::SeqCst);
            assert!(previous > 0);
            if previous == 1 {
                self.publish_global_idle_if_candidate();
            }
        }

        fn publish_global_idle_if_candidate(&self) {
            if !self.idle_candidate.load(Ordering::SeqCst) {
                return;
            }
            let transfers = self.transfers.read().unwrap();
            if *transfers == 0
                && self.dispatched.fetch_add(0, Ordering::SeqCst) == 0
                && self.idle_candidate.swap(false, Ordering::SeqCst)
            {
                let mut idle = self.idle.lock().unwrap();
                if idle.deadline.is_none() {
                    idle.deadline = Some(idle.activity);
                }
                idle.publications += 1;
            }
        }

        fn active_work_has_no_idle_deadline(&self) -> bool {
            let transfers = self.transfers.read().unwrap();
            let idle = self.idle.lock().unwrap();
            *transfers == 0 || idle.deadline.is_none()
        }

        fn idle_was_published_once(&self) -> bool {
            let transfers = self.transfers.read().unwrap();
            let dispatched = self.dispatched.load(Ordering::SeqCst);
            let idle = self.idle.lock().unwrap();
            *transfers == 0 && dispatched == 0 && idle.deadline.is_some() && idle.publications == 1
        }
    }

    /// Faithful shim of the FIXED `Scheduler` lock dance for loom
    /// verification. Lock acquires, drops, and conditional flow mirror
    /// the production code line-for-line; descriptor construction,
    /// Handle/runtime calls, and `cancel_descriptor` are stripped
    /// because they don't participate in the lock-ordering protocol.
    struct LoomScheduler {
        // Mirrors `Scheduler.transfers`. Value type stripped to () since
        // descriptors are irrelevant to the lock-ordering protocol.
        transfers: RwLock<HashMap<TidShim, ()>>,
        // Mirrors `ReadySet.by_group`. Value type stripped to () since
        // group internals (vruntime, queue) are irrelevant to the
        // existence-tracking protocol.
        by_group: RwLock<HashMap<u64, ()>>,
        // Mirrors `ReadySet.groups` (the root SkipMap of group entries).
        // Value type stripped to (). The phantom-group race lives in the
        // by_group/groups consistency: an entry can be left in `groups`
        // for a group_id no longer present in `by_group` if the inner
        // `ReadySet::insert_child` lock dance is wrong.
        groups: RwLock<HashMap<u64, ()>>,
    }

    impl LoomScheduler {
        fn new() -> Self {
            Self {
                transfers: RwLock::new(HashMap::new()),
                by_group: RwLock::new(HashMap::new()),
                groups: RwLock::new(HashMap::new()),
            }
        }

        /// Pre-register a top-level group for setup. Mirrors the state
        /// after a successful top-level enqueue: the parent is in
        /// `transfers`, `by_group`, AND `groups` (the root tree).
        fn register_group(&self, group_id: u64) {
            self.by_group.write().unwrap().insert(group_id, ());
            self.groups.write().unwrap().insert(group_id, ());
            self.transfers.write().unwrap().insert(
                TidShim {
                    id: group_id,
                    parent: None,
                },
                (),
            );
        }

        /// Mirror of FIXED `Scheduler::enqueue_transfer` lock dance,
        /// PLUS the inner `ReadySet::insert_child` lock dance via the
        /// `try_insert_into_existing_group` helper. Both protocols are
        /// held atomically with their respective lock guards.
        fn enqueue_transfer(&self, tid: TidShim) {
            // Outer protocol: resolve parent + insert into transfers
            // under transfers.write. Already verified by
            // fixed_dance_no_orphan and two_enqueues_one_cancel_no_orphan.
            let inserted = {
                let mut transfers = self.transfers.write().unwrap();
                let parent_exists = match tid.parent {
                    Some(p) => self.by_group.read().unwrap().contains_key(&p),
                    None => true,
                };
                if !parent_exists {
                    drop(transfers);
                    return;
                }
                transfers.insert(tid, ());
                true
            };
            let _ = inserted;

            // Inner protocol: ready_set.insert tail. Mirrors the FIXED
            // production helper: by_group.read held across groups.write.
            // A concurrent remove_group (which needs by_group.write) is
            // blocked until this scope exits.
            let group_id = tid.parent.unwrap_or(tid.id);
            let by_group = self.by_group.read().unwrap();
            if !by_group.contains_key(&group_id) {
                drop(by_group);
                self.transfers.write().unwrap().remove(&tid);
                return;
            }
            // by_group.read is held across the groups.write below.
            self.groups.write().unwrap().insert(group_id, ());
            drop(by_group);
        }

        /// Mirror of FIXED `Scheduler::cancel_transfer` lock dance,
        /// extended to also remove from `groups` (the production
        /// `ready_set.remove_group` removes from both `by_group` and
        /// `groups`).
        ///
        /// Single critical section: `transfers.write` held across
        /// `by_group.write` and `groups.write`.
        fn cancel_transfer(&self, id: TidShim) {
            let mut transfers = self.transfers.write().unwrap();
            let removed = transfers.remove(&id).is_some();
            let child_keys: Vec<TidShim> = transfers
                .keys()
                .filter(|t| t.parent == Some(id.id))
                .copied()
                .collect();
            for k in &child_keys {
                transfers.remove(k);
            }
            if removed && id.parent.is_none() {
                // Production `ReadySet::remove_group` removes from
                // by_group AND groups. Both happen under the outer
                // `transfers.write` so cancel is atomic from any
                // observer's perspective.
                self.by_group.write().unwrap().remove(&id.id);
                self.groups.write().unwrap().remove(&id.id);
            }
        }

        /// Outer-protocol invariant: no transfer remains whose parent
        /// group is gone from `by_group`.
        fn no_orphans(&self) -> bool {
            let t = self.transfers.read().unwrap();
            let bg = self.by_group.read().unwrap();
            t.keys().all(|tid| match tid.parent {
                Some(p) => bg.contains_key(&p),
                None => true,
            })
        }

        /// Inner-protocol invariant: no entry in `groups` (the root
        /// tree) without a matching entry in `by_group`. A phantom in
        /// `groups` indicates the inner ready_set lock dance dropped
        /// `by_group.read` before the `groups.insert`, allowing a
        /// concurrent `remove_group` to slip in.
        fn no_phantom_groups(&self) -> bool {
            let groups = self.groups.read().unwrap();
            let by_group = self.by_group.read().unwrap();
            groups.keys().all(|gid| by_group.contains_key(gid))
        }
    }

    /// Enqueue and final registry removal serialize through the transfer
    /// registry. After either order, registered work has invalidated any idle
    /// event removal could publish.
    #[test]
    fn enqueue_cannot_leave_a_stale_pool_idle_epoch() {
        loom::model(|| {
            let scheduler = Arc::new(LoomIdleScheduler::new(1, 0, false));

            let enqueueing = Arc::clone(&scheduler);
            let enqueue = thread::spawn(move || enqueueing.enqueue_transfer());
            let removing = Arc::clone(&scheduler);
            let remove = thread::spawn(move || removing.remove_transfer());

            enqueue.join().unwrap();
            remove.join().unwrap();

            assert!(
                scheduler.active_work_has_no_idle_deadline(),
                "active scheduler work retained a stale pool idle deadline"
            );
        });
    }

    /// Registry removal and final dispatch completion can reach zero in either
    /// order. Their handshake must publish exactly one global-idle event.
    #[test]
    fn registry_and_dispatch_zero_edges_cannot_lose_idle() {
        loom::model(|| {
            let scheduler = Arc::new(LoomIdleScheduler::new(1, 1, false));

            let removing = Arc::clone(&scheduler);
            let remove = thread::spawn(move || removing.remove_transfer());
            let completing = Arc::clone(&scheduler);
            let complete = thread::spawn(move || completing.release_dispatch());

            remove.join().unwrap();
            complete.join().unwrap();

            assert!(
                scheduler.idle_was_published_once(),
                "zero-edge race lost or duplicated scheduler-global idle"
            );
        });
    }

    /// New work racing the final dispatch from an already-empty registry must
    /// invalidate the pending candidate or supersede an idle event published
    /// immediately before registration.
    #[test]
    fn enqueue_cancels_a_pending_idle_candidate() {
        loom::model(|| {
            let scheduler = Arc::new(LoomIdleScheduler::new(0, 1, true));

            let enqueueing = Arc::clone(&scheduler);
            let enqueue = thread::spawn(move || enqueueing.enqueue_transfer());
            let completing = Arc::clone(&scheduler);
            let complete = thread::spawn(move || completing.release_dispatch());

            enqueue.join().unwrap();
            complete.join().unwrap();

            assert!(
                scheduler.active_work_has_no_idle_deadline(),
                "new scheduler work retained an idle event from the prior interval"
            );
        });
    }

    /// Verification test: the fixed dance produces no orphan in any
    /// interleaving. Loom panics on the first violation.
    #[test]
    fn fixed_dance_no_orphan() {
        loom::model(|| {
            let sched = Arc::new(LoomScheduler::new());
            sched.register_group(1);

            let s1 = sched.clone();
            let h1 = thread::spawn(move || {
                s1.enqueue_transfer(TidShim {
                    id: 100,
                    parent: Some(1),
                });
            });
            let s2 = sched.clone();
            let h2 = thread::spawn(move || {
                s2.cancel_transfer(TidShim {
                    id: 1,
                    parent: None,
                });
            });
            h1.join().unwrap();
            h2.join().unwrap();

            assert!(
                sched.no_orphans(),
                "fixed dance produced an orphan; lock-ordering bug regressed"
            );
        });
    }

    /// Verification: two concurrent child enqueues against a single
    /// concurrent cancel never leave an orphaned child. Exercises the
    /// protocol with three threads instead of two; verifies the lock
    /// dance scales beyond the minimal interleaving covered by
    /// `fixed_dance_no_orphan`.
    #[test]
    fn two_enqueues_one_cancel_no_orphan() {
        loom::model(|| {
            let sched = Arc::new(LoomScheduler::new());
            sched.register_group(1);

            let s1 = sched.clone();
            let h1 = thread::spawn(move || {
                s1.enqueue_transfer(TidShim {
                    id: 100,
                    parent: Some(1),
                });
            });
            let s2 = sched.clone();
            let h2 = thread::spawn(move || {
                s2.enqueue_transfer(TidShim {
                    id: 200,
                    parent: Some(1),
                });
            });
            let s3 = sched.clone();
            let h3 = thread::spawn(move || {
                s3.cancel_transfer(TidShim {
                    id: 1,
                    parent: None,
                });
            });
            h1.join().unwrap();
            h2.join().unwrap();
            h3.join().unwrap();

            assert!(
                sched.no_orphans(),
                "fixed dance produced an orphan with 2 enqueues + 1 cancel"
            );
        });
    }

    /// Verification: no phantom group entry in `groups` after a child
    /// enqueue races a parent cancel. Catches the inner-protocol bug
    /// landonxjames flagged: `insert_child` (and friends) drop
    /// `by_group.read` BEFORE writing to `groups`, so a concurrent
    /// `remove_group` can leave an entry in `groups` for a group_id no
    /// longer present in `by_group`.
    ///
    /// Expected to FAIL on the current shim (which mirrors the buggy
    /// production code) and PASS once the inner protocol is fixed
    /// (hold `by_group.read` across `groups.write`).
    #[test]
    fn child_insert_phantom_group() {
        loom::model(|| {
            let sched = Arc::new(LoomScheduler::new());
            sched.register_group(1);

            let s1 = sched.clone();
            let h1 = thread::spawn(move || {
                s1.enqueue_transfer(TidShim {
                    id: 100,
                    parent: Some(1),
                });
            });
            let s2 = sched.clone();
            let h2 = thread::spawn(move || {
                s2.cancel_transfer(TidShim {
                    id: 1,
                    parent: None,
                });
            });
            h1.join().unwrap();
            h2.join().unwrap();

            assert!(
                sched.no_phantom_groups(),
                "phantom group entry: groups contains a group_id not in by_group"
            );
        });
    }
}