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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Stable block geometry and carrier ownership.

use std::collections::TryReserveError;
use std::fmt;
use std::mem::MaybeUninit;
use std::num::NonZeroUsize;
use std::ptr::NonNull;

use super::geometry::PoolGeometry;
use super::virtual_memory::{VirtualMemoryError, VirtualRange};
use super::{invariant_violation, CarrierCount};
use crate::runtime::sync::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use crate::runtime::sync::sync::{Arc, Mutex};

#[cfg(test)]
use {super::virtual_memory::VirtualMemoryOperation, std::ops::Range};

/// Failure to construct, prepare, or claim from one block.
#[derive(Debug)]
pub(super) enum BlockError {
    /// A virtual-memory operation failed.
    VirtualMemory(VirtualMemoryError),
    /// Ownership metadata could not be allocated.
    Allocation(TryReserveError),
    /// The slot already contains prepared capacity.
    AlreadyPrepared,
    /// Adding the block would overflow prepared-capacity accounting.
    PreparedCapacityOverflow,
    /// A claim requested no carriers.
    InvalidClaimCount,
    /// A claim exceeds one block's carrier capacity.
    ClaimExceedsBlock {
        /// Requested carriers.
        requested: usize,
        /// Carriers in the block.
        capacity: usize,
    },
}

impl fmt::Display for BlockError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::VirtualMemory(error) => error.fmt(f),
            Self::Allocation(error) => write!(f, "block metadata allocation failed: {error}"),
            Self::AlreadyPrepared => f.write_str("block already has a prepared incarnation"),
            Self::PreparedCapacityOverflow => f.write_str("prepared carrier count would overflow"),
            Self::InvalidClaimCount => f.write_str("a carrier claim must be nonzero"),
            Self::ClaimExceedsBlock {
                requested,
                capacity,
            } => write!(
                f,
                "carrier claim {requested} exceeds block capacity {capacity}"
            ),
        }
    }
}

impl std::error::Error for BlockError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::VirtualMemory(error) => Some(error),
            Self::Allocation(error) => Some(error),
            Self::AlreadyPrepared
            | Self::PreparedCapacityOverflow
            | Self::InvalidClaimCount
            | Self::ClaimExceedsBlock { .. } => None,
        }
    }
}

impl From<VirtualMemoryError> for BlockError {
    fn from(error: VirtualMemoryError) -> Self {
        Self::VirtualMemory(error)
    }
}

impl From<TryReserveError> for BlockError {
    fn from(error: TryReserveError) -> Self {
        Self::Allocation(error)
    }
}

/// Reason one block cannot begin a trim.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum TrimBlocked {
    /// The slot has no prepared incarnation.
    NotPrepared,
    /// Removing the block would violate the caller's prepared-capacity floor.
    FloorViolation,
    /// A carrier claim won the claim-trim gate.
    Busy,
    /// A prior trim or failed deactivation still owns the slot.
    CleanupPending,
}

/// Failed cleanup work that remains safe to retry while the slot is inactive.
#[derive(Debug)]
pub(super) enum CleanupRetry {
    /// Whole-range deactivation failed and remains safe to retry.
    DeactivationPending(VirtualMemoryError),
    /// The range is inaccessible, but backing may remain resident.
    ReclaimPending(VirtualMemoryError),
}

/// Accessibility state for one stable virtual range.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum MappingState {
    /// The range is inaccessible and may need another discard attempt.
    Reserved {
        /// `true` when backing reclaim has not completed.
        reclaim_pending: bool,
    },
    /// The complete range is readable and writable.
    Prepared,
    /// Mapping preparation failed before an incarnation was published.
    ActivationRecoveryPending,
    /// Mapping deactivation failed while a draining incarnation remained.
    DeactivationRecoveryPending,
}

/// Claim-trim gate state for one block incarnation.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum IncarnationState {
    /// Carrier claims may proceed.
    Active = 0,
    /// Trim is confirming that no carrier is owned.
    Draining = 1,
    /// The incarnation's mapping is inaccessible.
    Dead = 2,
}

/// Atomic storage for [`IncarnationState`].
struct AtomicIncarnationState(AtomicU8);

impl AtomicIncarnationState {
    /// Creates an atomic state with `value`.
    fn new(value: IncarnationState) -> Self {
        Self(AtomicU8::new(value as u8))
    }

    /// Loads and validates the current state.
    fn load(&self, order: Ordering) -> IncarnationState {
        Self::decode(self.0.load(order))
    }

    /// Starts the claim-trim gate transition.
    fn try_start_trim(&self) -> Result<(), IncarnationState> {
        self.0
            .compare_exchange(
                IncarnationState::Active as u8,
                IncarnationState::Draining as u8,
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .map(|_| ())
            .map_err(Self::decode)
    }

    /// Restores a draining incarnation after trim is abandoned or reversed.
    fn restore_active(&self) {
        if self
            .0
            .compare_exchange(
                IncarnationState::Draining as u8,
                IncarnationState::Active as u8,
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .is_err()
        {
            invariant_violation("only a draining incarnation may return to active");
        }
    }

    /// Retires a draining incarnation after its mapping becomes inaccessible.
    fn retire(&self) {
        if self
            .0
            .compare_exchange(
                IncarnationState::Draining as u8,
                IncarnationState::Dead as u8,
                Ordering::Release,
                Ordering::Acquire,
            )
            .is_err()
        {
            invariant_violation("only a draining incarnation may retire");
        }
    }

    /// Converts a stored representation into a state.
    fn decode(value: u8) -> IncarnationState {
        match value {
            value if value == IncarnationState::Active as u8 => IncarnationState::Active,
            value if value == IncarnationState::Draining as u8 => IncarnationState::Draining,
            value if value == IncarnationState::Dead as u8 => IncarnationState::Dead,
            _ => invariant_violation("incarnation contains an invalid state"),
        }
    }
}

/// Stable identity of one carrier within an incarnation.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct CarrierId {
    /// Stable block-slot index.
    slot: u32,
    /// Carrier index within the slot.
    index: u32,
    /// Incarnation that owns the carrier bit.
    incarnation: IncarnationIdentity,
}

/// Stable physical location of one carrier within an arena.
///
/// The location orders carriers for run construction. It does not identify the
/// block incarnation that owns a live carrier bit.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct CarrierLocation {
    /// Pool-local block-slot index.
    slot_id: u32,
    /// Carrier index within the slot.
    carrier_index: u32,
}

impl CarrierLocation {
    /// Creates one arena location.
    pub(super) const fn new(slot_id: u32, carrier_index: u32) -> Self {
        Self {
            slot_id,
            carrier_index,
        }
    }

    /// Returns the pool-local block-slot index.
    pub(super) const fn slot_id(self) -> u32 {
        self.slot_id
    }

    /// Returns the carrier index within the slot.
    pub(super) const fn carrier_index(self) -> u32 {
        self.carrier_index
    }
}

/// Comparison-only identity for one block activation.
///
/// The live carrier bit, not this value, prevents incarnation replacement.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct IncarnationIdentity(NonZeroUsize);

/// Bits won by one bitmap operation.
#[derive(Clone, Copy, Debug)]
struct WonWord {
    /// Index into the incarnation bitmap.
    word_index: usize,
    /// Bits changed from clear to set by the operation.
    mask: u64,
}

/// Occupancy metadata for one activation of a stable block slot.
struct BlockIncarnation {
    /// Claim-trim gate state.
    state: AtomicIncarnationState,
    /// Fixed bitmap with one ownership bit per carrier.
    ///
    /// Each atomic word covers 64 carriers. Padding bits in the final word
    /// remain clear.
    in_use: Box<[AtomicU64]>,
}

impl BlockIncarnation {
    /// Allocates an active incarnation with every valid carrier free.
    fn try_new(bitmap_words: usize) -> Result<Self, TryReserveError> {
        let mut in_use = Vec::new();
        in_use.try_reserve_exact(bitmap_words)?;
        in_use.extend((0..bitmap_words).map(|_| AtomicU64::new(0)));
        Ok(Self {
            state: AtomicIncarnationState::new(IncarnationState::Active),
            in_use: in_use.into_boxed_slice(),
        })
    }

    /// Allocates an active incarnation with `count` low carriers owned.
    fn try_new_preclaimed(
        geometry: PoolGeometry,
        count: CarrierCount,
    ) -> Result<(Self, Vec<WonWord>), TryReserveError> {
        let incarnation = Self::try_new(geometry.bitmap_words())?;
        let mut won = Vec::new();
        won.try_reserve_exact(geometry.bitmap_words())?;

        let mut remaining = count.get();
        for (word_index, word) in incarnation.in_use.iter().enumerate() {
            if remaining == 0 {
                break;
            }
            let valid = bitmap_word_mask(geometry, word_index);
            let mask = take_lowest(valid, remaining);
            let taken = mask.count_ones() as usize;
            word.store(mask, Ordering::Relaxed);
            won.push(WonWord { word_index, mask });
            remaining -= taken;
        }
        if remaining != 0 {
            invariant_violation("preclaim exceeds valid block geometry");
        }
        Ok((incarnation, won))
    }

    /// Returns an opaque identity for diagnostic comparisons.
    fn identity(this: &Arc<Self>) -> IncarnationIdentity {
        let address = Arc::as_ptr(this).addr();
        IncarnationIdentity(
            NonZeroUsize::new(address).expect("an allocated incarnation has a nonzero address"),
        )
    }
}

#[cfg(not(all(test, s3_tm_loom)))]
mod incarnation_cell {
    //! Lock-free production publication for block incarnations.

    use arc_swap::{ArcSwapOption, Guard};

    use super::BlockIncarnation;
    use crate::runtime::sync::sync::Arc;

    /// Atomic publication for the current block incarnation.
    pub(super) struct IncarnationCell {
        inner: ArcSwapOption<BlockIncarnation>,
    }

    impl IncarnationCell {
        /// Creates an empty publication cell.
        pub(super) fn new() -> Self {
            Self {
                inner: ArcSwapOption::empty(),
            }
        }

        /// Protects the current incarnation from metadata reclamation.
        pub(super) fn load(&self) -> IncarnationGuard {
            IncarnationGuard {
                inner: self.inner.load(),
            }
        }

        /// Replaces the current incarnation and returns the previous value.
        pub(super) fn swap(
            &self,
            next: Option<Arc<BlockIncarnation>>,
        ) -> Option<Arc<BlockIncarnation>> {
            self.inner.swap(next)
        }
    }

    /// Protection for the incarnation loaded before a bitmap mutation.
    pub(super) struct IncarnationGuard {
        inner: Guard<Option<Arc<BlockIncarnation>>>,
    }

    impl IncarnationGuard {
        /// Returns the protected incarnation, or `None` for an inactive slot.
        pub(super) fn as_ref(&self) -> Option<&Arc<BlockIncarnation>> {
            self.inner.as_ref()
        }
    }
}

#[cfg(all(test, s3_tm_loom))]
mod incarnation_cell {
    //! Loom-instrumented publication with owned incarnation guards.

    use super::BlockIncarnation;
    use crate::runtime::sync::sync::{Arc, Mutex};

    /// Loom-instrumented publication for the current block incarnation.
    pub(super) struct IncarnationCell {
        inner: Mutex<Option<Arc<BlockIncarnation>>>,
    }

    impl IncarnationCell {
        /// Creates an empty publication cell.
        pub(super) fn new() -> Self {
            Self {
                inner: Mutex::new(None),
            }
        }

        /// Loads an owned reference to the current incarnation.
        pub(super) fn load(&self) -> IncarnationGuard {
            IncarnationGuard {
                inner: self.inner.lock().clone(),
            }
        }

        /// Replaces the current incarnation and returns the previous value.
        pub(super) fn swap(
            &self,
            next: Option<Arc<BlockIncarnation>>,
        ) -> Option<Arc<BlockIncarnation>> {
            std::mem::replace(&mut *self.inner.lock(), next)
        }
    }

    /// Owned protection for a Loom-loaded incarnation.
    pub(super) struct IncarnationGuard {
        inner: Option<Arc<BlockIncarnation>>,
    }

    impl IncarnationGuard {
        /// Returns the protected incarnation, or `None` for an inactive slot.
        pub(super) fn as_ref(&self) -> Option<&Arc<BlockIncarnation>> {
            self.inner.as_ref()
        }
    }
}

use incarnation_cell::{IncarnationCell, IncarnationGuard};

/// Stable block geometry, mapping, and replaceable ownership metadata.
///
/// Mapping state and the current incarnation remain separately synchronized
/// so carrier claims never take `mapping`. Their legal combinations are:
///
/// | Mapping state                 | Current incarnation                    |
/// |-------------------------------|----------------------------------------|
/// | `Reserved`                    | none                                   |
/// | `Prepared`                    | `Active` or trim-owned `Draining`      |
/// | `ActivationRecoveryPending`   | none                                   |
/// | `DeactivationRecoveryPending` | `Draining`                             |
pub(super) struct BlockSlot {
    /// Stable slot index.
    id: u32,
    /// Virtual range retained for the slot lifetime.
    range: VirtualRange,
    /// Checked carrier and bitmap dimensions.
    geometry: PoolGeometry,
    /// Serialized mapping and cleanup state.
    mapping: Mutex<MappingState>,
    /// Published claimable incarnation.
    current: IncarnationCell,
    /// Physical bitmap-return operations observed by tests.
    ///
    /// This counter is slot-local so tests can distinguish grouped publication
    /// from unrelated returns in other slots.
    #[cfg(test)]
    release_batches: AtomicU64,
}

impl BlockSlot {
    /// Reserves an inaccessible virtual range.
    ///
    /// Returns [`BlockError::VirtualMemory`] if the address range cannot be
    /// reserved.
    pub(super) fn new(id: u32, geometry: PoolGeometry) -> Result<Self, BlockError> {
        let range = VirtualRange::reserve(
            geometry.block_size(),
            NonZeroUsize::new(geometry.page_size()).expect("geometry has a nonzero page size"),
        )?;
        Ok(Self::from_range(id, geometry, range))
    }

    /// Reserves one block range with an inaccessible page on each side.
    #[cfg(test)]
    pub(super) fn new_guarded(id: u32, geometry: PoolGeometry) -> Result<Self, BlockError> {
        let range = VirtualRange::reserve_guarded(
            geometry.block_size(),
            NonZeroUsize::new(geometry.page_size()).expect("geometry has a nonzero page size"),
        )?;
        Ok(Self::from_range(id, geometry, range))
    }

    /// Constructs one stable slot around an already reserved block range.
    fn from_range(id: u32, geometry: PoolGeometry, range: VirtualRange) -> Self {
        Self {
            id,
            range,
            geometry,
            mapping: Mutex::new(MappingState::Reserved {
                reclaim_pending: false,
            }),
            current: IncarnationCell::new(),
            #[cfg(test)]
            release_batches: AtomicU64::new(0),
        }
    }

    /// Returns the number of carriers in this slot.
    pub(super) fn carrier_count(&self) -> CarrierCount {
        self.geometry.carriers_per_block()
    }

    /// Returns this slot's stable identifier.
    pub(super) fn id(&self) -> u32 {
        self.id
    }

    /// Returns the reservation base for integer comparison.
    pub(super) fn base_address(&self) -> usize {
        self.range.base_address()
    }

    /// Returns the stable virtual reservation length.
    pub(super) fn reserved_len(&self) -> usize {
        self.range.len()
    }

    /// Returns the complete virtual reservation retained for this slot.
    #[cfg(test)]
    pub(super) fn reservation_address_range(&self) -> std::ops::Range<usize> {
        self.range.reservation_address_range()
    }

    /// Derives a checked immutable pointer from this slot's provenance root.
    ///
    /// # Safety
    ///
    /// The caller must retain initialized immutable ownership over the
    /// complete subrange. That ownership must keep its carrier bits live so
    /// trim cannot deactivate the slot while the pointer is used.
    pub(super) unsafe fn ptr_for_immutable_range(
        &self,
        offset: usize,
        len: usize,
    ) -> Option<NonNull<u8>> {
        // SAFETY: the caller supplies the initialized owner and deactivation
        // exclusion required by `VirtualRange::ptr_for_range`.
        unsafe {
            self.range
                .ptr_for_range(offset, len)
                .map(NonNull::cast::<u8>)
        }
    }

    /// Debug-checks that every carrier intersecting `offset..offset + len`
    /// remains live.
    ///
    /// This detects violations of the immutable-owner contract. A set bit
    /// alone does not prove that a particular owner controls that bit.
    #[cfg(debug_assertions)]
    pub(super) fn debug_assert_immutable_range_live(&self, offset: usize, len: usize) {
        let end = offset.checked_add(len);
        debug_assert!(
            len != 0 && end.is_some_and(|end| end <= self.geometry.block_size()),
            "immutable range is outside its block slot"
        );
        let Some(end) = end.filter(|end| len != 0 && *end <= self.geometry.block_size()) else {
            return;
        };
        let current = self.current.load();
        let Some(incarnation) = current.as_ref() else {
            debug_assert!(false, "immutable range has no current incarnation");
            return;
        };
        let first = offset / self.geometry.carrier_size();
        let last = (end - 1) / self.geometry.carrier_size();
        for index in first..=last {
            let word_index = index / u64::BITS as usize;
            let mask = 1u64 << (index % u64::BITS as usize);
            let live = incarnation
                .in_use
                .get(word_index)
                .is_some_and(|word| word.load(Ordering::Acquire) & mask != 0);
            debug_assert!(
                live,
                "immutable range includes a carrier without a live bit"
            );
        }
    }

    /// Returns the reserved half-open address range.
    ///
    /// The integer range grants no access to the backing memory. `None`
    /// reports address arithmetic overflow.
    #[cfg(test)]
    pub(super) fn address_range(&self) -> Option<Range<usize>> {
        let start = self.base_address();
        start.checked_add(self.reserved_len()).map(|end| start..end)
    }

    /// Returns the number of ownership bitmap words.
    pub(super) fn bitmap_words(&self) -> usize {
        self.geometry.bitmap_words()
    }

    /// Prepares the range and makes one incarnation active.
    ///
    /// The caller holds the admission lock that protects the pool-wide
    /// `prepared` count and admission floor. The count is incremented before
    /// `Active` becomes visible. Protection failure leaves the slot
    /// nonclaimable and does not change `prepared`.
    pub(super) fn prepare(&self, prepared: &mut CarrierCount) -> Result<(), BlockError> {
        let mut mapping = self.mapping.lock();
        let current = self.current.load();
        let create_fresh = match *mapping {
            MappingState::Prepared => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("prepared mapping has no current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) == IncarnationState::Dead {
                    invariant_violation("prepared mapping has a dead current incarnation");
                }
                return Err(BlockError::AlreadyPrepared);
            }
            MappingState::Reserved { .. } | MappingState::ActivationRecoveryPending => {
                if current.as_ref().is_some() {
                    invariant_violation("inactive mapping retains a current incarnation");
                }
                true
            }
            MappingState::DeactivationRecoveryPending => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("deactivation recovery lost its current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) != IncarnationState::Draining {
                    invariant_violation(
                        "deactivation recovery retained a non-draining incarnation",
                    );
                }
                false
            }
        };

        let next_prepared = prepared
            .checked_add(self.carrier_count())
            .ok_or(BlockError::PreparedCapacityOverflow)?;
        let fresh = if create_fresh {
            Some(Arc::new(BlockIncarnation::try_new(
                self.geometry.bitmap_words(),
            )?))
        } else {
            None
        };

        if let Err(error) = self.range.prepare() {
            *mapping = if current.as_ref().is_some() {
                MappingState::DeactivationRecoveryPending
            } else {
                MappingState::ActivationRecoveryPending
            };
            return Err(error.into());
        }

        *mapping = MappingState::Prepared;
        *prepared = next_prepared;
        if let Some(incarnation) = current.as_ref() {
            incarnation.state.restore_active();
        } else if self.current.swap(fresh).is_some() {
            invariant_violation("preparation replaced a current incarnation");
        }
        Ok(())
    }

    /// Prepares a reusable inactive slot with `count` carriers already owned.
    ///
    /// Serialized arena fallback calls this after exhausting active capacity.
    /// The caller also serializes the pool-wide `prepared` count and admission
    /// floor.
    ///
    /// `None` reports an active slot or cleanup-pending incarnation. Success
    /// increments `prepared` before publishing `Active` and returns ownership
    /// of exactly `count` carrier bits. Failure publishes no new incarnation
    /// and leaves `prepared` unchanged. The private incarnation owns its bits
    /// before publication, so no claim-trim gate is required.
    pub(super) fn prepare_and_claim_if_inactive(
        slot: &Arc<Self>,
        prepared: &mut CarrierCount,
        count: CarrierCount,
    ) -> Result<Option<ProvisionalBits>, BlockError> {
        if count == CarrierCount::ZERO {
            return Err(BlockError::InvalidClaimCount);
        }
        if count > slot.carrier_count() {
            return Err(BlockError::ClaimExceedsBlock {
                requested: count.get(),
                capacity: slot.carrier_count().get(),
            });
        }

        let mut mapping = slot.mapping.lock();
        let current = slot.current.load();
        match *mapping {
            MappingState::Prepared => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("prepared mapping has no current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) == IncarnationState::Dead {
                    invariant_violation("prepared mapping has a dead current incarnation");
                }
                return Ok(None);
            }
            MappingState::DeactivationRecoveryPending => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("deactivation recovery lost its current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) != IncarnationState::Draining {
                    invariant_violation(
                        "deactivation recovery retained a non-draining incarnation",
                    );
                }
                return Ok(None);
            }
            MappingState::Reserved { .. } | MappingState::ActivationRecoveryPending => {
                if current.as_ref().is_some() {
                    invariant_violation("inactive mapping retains a current incarnation");
                }
            }
        }

        let next_prepared = prepared
            .checked_add(slot.carrier_count())
            .ok_or(BlockError::PreparedCapacityOverflow)?;
        let (fresh, won) = BlockIncarnation::try_new_preclaimed(slot.geometry, count)?;
        let fresh = Arc::new(fresh);
        let incarnation = BlockIncarnation::identity(&fresh);

        if let Err(error) = slot.range.prepare() {
            *mapping = MappingState::ActivationRecoveryPending;
            return Err(error.into());
        }

        *mapping = MappingState::Prepared;
        *prepared = next_prepared;
        if slot.current.swap(Some(fresh)).is_some() {
            invariant_violation("preclaimed activation replaced a current incarnation");
        }
        Ok(Some(ProvisionalBits {
            slot: Arc::clone(slot),
            incarnation,
            won,
        }))
    }

    /// Confirms that this block may be removed from prepared capacity.
    ///
    /// The caller holds the admission lock that protects the pool-wide
    /// `prepared` count and admission floor. Success subtracts the complete
    /// block and returns cleanup authority. A live bit restores `Active`
    /// without changing `prepared`.
    pub(super) fn start_trim(
        slot: &Arc<Self>,
        prepared: &mut CarrierCount,
        floor: CarrierCount,
    ) -> Result<TrimCleanup, TrimBlocked> {
        let mapping = slot.mapping.lock();
        match *mapping {
            MappingState::Prepared => {}
            MappingState::Reserved { .. } => return Err(TrimBlocked::NotPrepared),
            MappingState::ActivationRecoveryPending | MappingState::DeactivationRecoveryPending => {
                return Err(TrimBlocked::CleanupPending)
            }
        }

        let current = slot.current.load();
        let Some(incarnation) = current.as_ref() else {
            invariant_violation("prepared mapping has no current incarnation");
        };
        match incarnation.state.load(Ordering::Acquire) {
            IncarnationState::Active => {}
            IncarnationState::Draining => return Err(TrimBlocked::CleanupPending),
            IncarnationState::Dead => {
                invariant_violation("prepared mapping has a dead current incarnation")
            }
        }

        let Some(next_prepared) = prepared.checked_sub(slot.carrier_count()) else {
            invariant_violation("prepared capacity excludes an active block");
        };
        if next_prepared < floor {
            return Err(TrimBlocked::FloorViolation);
        }

        if incarnation.state.try_start_trim().is_err() {
            return Err(TrimBlocked::CleanupPending);
        }
        loom_seq_cst_fence();

        let busy = incarnation
            .in_use
            .iter()
            .enumerate()
            .any(|(word_index, word)| {
                let valid = bitmap_word_mask(slot.geometry, word_index);
                word.load(Ordering::SeqCst) & valid != 0
            });
        if busy {
            incarnation.state.restore_active();
            return Err(TrimBlocked::Busy);
        }

        *prepared = next_prepared;
        Ok(TrimCleanup {
            slot: Arc::clone(slot),
            incarnation: Arc::clone(incarnation),
            consumed: false,
        })
    }

    /// Retries pending whole-range protection or backing reclaim.
    ///
    /// Pool maintenance calls this after a cleanup operation records pending
    /// work. A slot with no pending work returns success without changing
    /// state. The result is `true` when this call attempted pending platform
    /// work. Failure leaves the slot nonclaimable and identifies the required
    /// retry.
    pub(super) fn retry_cleanup(&self) -> Result<bool, CleanupRetry> {
        let mut mapping = self.mapping.lock();
        match *mapping {
            MappingState::Prepared => {
                let current = self.current.load();
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("prepared mapping has no current incarnation");
                };
                match incarnation.state.load(Ordering::Acquire) {
                    IncarnationState::Active | IncarnationState::Draining => return Ok(false),
                    IncarnationState::Dead => {
                        invariant_violation("prepared mapping has a dead current incarnation")
                    }
                }
            }
            MappingState::Reserved {
                reclaim_pending: false,
            } => {
                if self.current.load().as_ref().is_some() {
                    invariant_violation("inactive mapping has a current incarnation");
                }
                return Ok(false);
            }
            MappingState::Reserved {
                reclaim_pending: true,
            } => {
                if self.current.load().as_ref().is_some() {
                    invariant_violation("inactive reclaim has a current incarnation");
                }
                return match self.range.discard() {
                    Ok(()) => {
                        *mapping = MappingState::Reserved {
                            reclaim_pending: false,
                        };
                        Ok(true)
                    }
                    Err(error) => Err(CleanupRetry::ReclaimPending(error)),
                };
            }
            MappingState::ActivationRecoveryPending => {
                if self.current.load().as_ref().is_some() {
                    invariant_violation("activation recovery retained a current incarnation");
                }
            }
            MappingState::DeactivationRecoveryPending => {
                let current = self.current.load();
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("deactivation recovery lost its current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) != IncarnationState::Draining {
                    invariant_violation(
                        "deactivation recovery retained a non-draining incarnation",
                    );
                }
            }
        }

        if let Err(error) = self.range.deactivate() {
            return Err(CleanupRetry::DeactivationPending(error));
        }
        *mapping = MappingState::Reserved {
            reclaim_pending: false,
        };
        self.finish_inactive_cleanup(&mut mapping).map(|()| true)
    }

    /// Retires a draining incarnation after the range becomes inaccessible.
    ///
    /// Discard failure still retires the incarnation and records pending
    /// reclaim in `mapping`.
    fn finish_inactive_cleanup(&self, mapping: &mut MappingState) -> Result<(), CleanupRetry> {
        let reclaim = self.range.discard();
        let reclaim_pending = reclaim.is_err();
        *mapping = MappingState::Reserved { reclaim_pending };

        if let Some(incarnation) = self.current.load().as_ref() {
            incarnation.state.retire();
            let removed = self
                .current
                .swap(None)
                .unwrap_or_else(|| invariant_violation("cleanup lost its current incarnation"));
            if !Arc::ptr_eq(&removed, incarnation) {
                invariant_violation("cleanup removed a different incarnation");
            }
        }

        match reclaim {
            Ok(()) => Ok(()),
            Err(error) => Err(CleanupRetry::ReclaimPending(error)),
        }
    }

    /// Claims up to `count` carriers from the current active incarnation.
    ///
    /// Returns `None` when no incarnation is published, no bit is free, or
    /// trim wins the state gate. Zero returns [`BlockError::InvalidClaimCount`].
    #[cfg(test)]
    pub(super) fn try_claim(
        slot: &Arc<Self>,
        count: CarrierCount,
    ) -> Result<Option<ProvisionalBits>, BlockError> {
        Ok(Self::try_claim_words(slot, 0, slot.bitmap_words(), count)?.into_provisional())
    }

    /// Exhaustively claims from the current active incarnation.
    ///
    /// Unlike the bounded optimistic path, this retries a bitmap word after a
    /// competing claimant takes selected candidates. It stops only after the
    /// request is complete or atomic observations find every remaining word
    /// full.
    pub(super) fn try_claim_exhaustive(
        slot: &Arc<Self>,
        count: CarrierCount,
    ) -> Result<Option<ProvisionalBits>, BlockError> {
        if count == CarrierCount::ZERO {
            return Err(BlockError::InvalidClaimCount);
        }

        let Some(mut attempt) = BlockClaimAttempt::begin(slot)? else {
            return Ok(None);
        };
        attempt.take_exhaustive(count.get());
        Ok(attempt.finish())
    }

    /// Claims from a bounded contiguous bitmap-word window.
    ///
    /// `start_word` beyond the bitmap and a zero `word_limit` inspect no
    /// words. `inspected_words` counts candidate positions even when the slot
    /// has no active incarnation.
    pub(super) fn try_claim_words(
        slot: &Arc<Self>,
        start_word: usize,
        word_limit: usize,
        count: CarrierCount,
    ) -> Result<BlockClaim, BlockError> {
        if count == CarrierCount::ZERO {
            return Err(BlockError::InvalidClaimCount);
        }

        let inspected_words = slot
            .bitmap_words()
            .saturating_sub(start_word)
            .min(word_limit);
        if inspected_words == 0 {
            return Ok(BlockClaim::empty());
        }

        let Some(mut attempt) = BlockClaimAttempt::begin_with_capacity(slot, inspected_words)?
        else {
            return Ok(BlockClaim {
                provisional: None,
                inspected_words,
            });
        };
        let (_, inspected_words) = attempt.take_words(start_word, inspected_words, count.get());
        Ok(BlockClaim {
            provisional: attempt.finish(),
            inspected_words,
        })
    }

    /// Claims one run of consecutive fully free bitmap words.
    ///
    /// Returns no ownership unless the complete run is won. A collision rolls
    /// back any word already won by this attempt.
    pub(super) fn try_claim_word_run(
        slot: &Arc<Self>,
        start_word: usize,
        word_limit: usize,
        word_count: usize,
    ) -> Result<BlockClaim, BlockError> {
        if word_count == 0 {
            return Err(BlockError::InvalidClaimCount);
        }

        let inspected_limit = slot
            .bitmap_words()
            .saturating_sub(start_word)
            .min(word_limit);
        if inspected_limit == 0 {
            return Ok(BlockClaim::empty());
        }
        let Some(mut attempt) = BlockClaimAttempt::begin_with_capacity(slot, word_count)? else {
            return Ok(BlockClaim {
                provisional: None,
                inspected_words: inspected_limit,
            });
        };
        let (complete, inspected_words) =
            attempt.take_word_run(start_word, inspected_limit, word_count);
        if !complete {
            drop(attempt);
            return Ok(BlockClaim {
                provisional: None,
                inspected_words,
            });
        }
        Ok(BlockClaim {
            provisional: attempt.finish(),
            inspected_words,
        })
    }

    /// Returns a set of bits from a gate-passed owner.
    ///
    /// Identity or ownership mismatch is fail-stop and clears no bits.
    fn release_won(&self, incarnation: IncarnationIdentity, won: &[WonWord]) {
        if won.iter().all(|word| word.mask == 0) {
            return;
        }
        #[cfg(test)]
        self.release_batches.fetch_add(1, Ordering::AcqRel);
        let current = self.current.load();
        let Some(current) = current.as_ref() else {
            invariant_violation("owned carriers have no current incarnation");
        };
        if BlockIncarnation::identity(current) != incarnation {
            invariant_violation("owned carriers name a different incarnation");
        }
        match current.state.load(Ordering::Acquire) {
            IncarnationState::Active | IncarnationState::Draining => {}
            IncarnationState::Dead => invariant_violation("owned carriers name a dead incarnation"),
        }

        for word in won {
            clear_owned_bits(&current.in_use[word.word_index], word.mask);
        }
    }

    /// Returns one carrier identified by slot, index, and incarnation.
    fn release_one(&self, id: CarrierId) {
        if id.slot != self.id {
            invariant_violation("carrier returned to a different block slot");
        }
        let index = id.index as usize;
        self.release_won(
            id.incarnation,
            &[WonWord {
                word_index: index / u64::BITS as usize,
                mask: 1u64 << (index % u64::BITS as usize),
            }],
        );
    }

    /// Returns physical bitmap-return operations observed by this slot.
    #[cfg(test)]
    pub(super) fn test_release_batches(&self) -> u64 {
        self.release_batches.load(Ordering::Acquire)
    }

    /// Returns `true` when the current active incarnation appears all-free.
    ///
    /// This is only a trim-selection hint. A concurrent claim may change the
    /// result immediately; [`BlockSlot::start_trim`] performs the authoritative
    /// lifecycle, bitmap, and capacity checks.
    pub(super) fn appears_free(&self) -> bool {
        let current = self.current.load();
        let Some(incarnation) = current.as_ref() else {
            return false;
        };
        if incarnation.state.load(Ordering::Acquire) != IncarnationState::Active {
            return false;
        }
        incarnation
            .in_use
            .iter()
            .enumerate()
            .all(|(word_index, word)| {
                let valid = bitmap_word_mask(self.geometry, word_index);
                word.load(Ordering::Acquire) & valid == 0
            })
    }

    /// Returns whether the active bitmap contains `word_count` complete free words.
    ///
    /// The caller must externally quiesce claims and returns. This is a
    /// test/fuzz oracle, not an allocation hint: it reads the bitmap with an
    /// implementation-independent linear scan and does not mutate ownership.
    #[cfg(any(test, s3_tm_fuzz))]
    pub(super) fn has_free_word_run_quiescent(&self, word_count: usize) -> bool {
        if word_count == 0 {
            return false;
        }
        let current = self.current.load();
        let Some(incarnation) = current.as_ref() else {
            return false;
        };
        if incarnation.state.load(Ordering::Acquire) != IncarnationState::Active {
            return false;
        }

        let mut free_words = 0;
        for (word_index, word) in incarnation.in_use.iter().enumerate() {
            let valid = bitmap_word_mask(self.geometry, word_index);
            if valid == u64::MAX && word.load(Ordering::Acquire) & valid == 0 {
                free_words += 1;
                if free_words == word_count {
                    return true;
                }
            } else {
                free_words = 0;
            }
        }
        false
    }

    /// Counts set valid bits in the current incarnation.
    #[cfg(test)]
    pub(super) fn live_carriers(&self) -> usize {
        self.current
            .load()
            .as_ref()
            .map(|incarnation| {
                incarnation
                    .in_use
                    .iter()
                    .enumerate()
                    .map(|(word_index, word)| {
                        let valid = bitmap_word_mask(self.geometry, word_index);
                        (word.load(Ordering::Acquire) & valid).count_ones() as usize
                    })
                    .sum()
            })
            .unwrap_or(0)
    }

    /// Injects one virtual-memory transition failure.
    #[cfg(test)]
    pub(super) fn inject_failure_once(&self, operation: VirtualMemoryOperation) {
        self.range.inject_failure_once(operation);
    }

    /// Samples this slot's mapping, cleanup, and bitmap state.
    ///
    /// The mapping lock stabilizes lifecycle transitions, but claims and
    /// returns may change bitmap ownership while it is counted. Consumers may
    /// treat the result as authoritative only when the pool is externally
    /// quiescent.
    pub(super) fn sample_lifecycle(&self) -> BlockLifecycleSample {
        let mapping = self.mapping.lock();
        let current = self.current.load();
        let live_carriers = current
            .as_ref()
            .map(|incarnation| {
                incarnation
                    .in_use
                    .iter()
                    .enumerate()
                    .map(|(word_index, word)| {
                        let valid = bitmap_word_mask(self.geometry, word_index);
                        CarrierCount::new(
                            (word.load(Ordering::Acquire) & valid).count_ones() as usize
                        )
                    })
                    .fold(CarrierCount::ZERO, |total, count| {
                        total.checked_add(count).unwrap_or_else(|| {
                            invariant_violation("block live-carrier diagnostic overflow")
                        })
                    })
            })
            .unwrap_or(CarrierCount::ZERO);

        let (prepared_capacity, cleanup_pending) = match *mapping {
            MappingState::Prepared => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("prepared mapping has no current incarnation");
                };
                match incarnation.state.load(Ordering::Acquire) {
                    IncarnationState::Active => (self.carrier_count(), false),
                    IncarnationState::Draining => (CarrierCount::ZERO, true),
                    IncarnationState::Dead => {
                        invariant_violation("prepared mapping has a dead incarnation")
                    }
                }
            }
            MappingState::Reserved { reclaim_pending } => {
                if current.as_ref().is_some() {
                    invariant_violation("reserved mapping retains a current incarnation");
                }
                (CarrierCount::ZERO, reclaim_pending)
            }
            MappingState::ActivationRecoveryPending => {
                if current.as_ref().is_some() {
                    invariant_violation("activation recovery retains a current incarnation");
                }
                (CarrierCount::ZERO, true)
            }
            MappingState::DeactivationRecoveryPending => {
                let Some(incarnation) = current.as_ref() else {
                    invariant_violation("deactivation recovery lost its current incarnation");
                };
                if incarnation.state.load(Ordering::Acquire) != IncarnationState::Draining {
                    invariant_violation("deactivation recovery has a non-draining incarnation");
                }
                (CarrierCount::ZERO, true)
            }
        };

        BlockLifecycleSample {
            prepared_capacity,
            live_carriers,
            cleanup_pending,
        }
    }
}

/// Independently reconstructed lifecycle state for one block slot.
pub(super) struct BlockLifecycleSample {
    /// Capacity represented by a prepared active incarnation.
    pub(super) prepared_capacity: CarrierCount,
    /// Valid bitmap bits currently owned by claims or carrier guards.
    pub(super) live_carriers: CarrierCount,
    /// Whether trim or mapping recovery keeps the slot nonclaimable.
    pub(super) cleanup_pending: bool,
}

/// Result of one bounded block claim.
pub(super) struct BlockClaim {
    /// Gate-passed bits won from the inspected window.
    provisional: Option<ProvisionalBits>,
    /// Candidate bitmap positions charged to the scan budget.
    inspected_words: usize,
}

impl BlockClaim {
    /// Returns an empty result that inspected no words.
    fn empty() -> Self {
        Self {
            provisional: None,
            inspected_words: 0,
        }
    }

    /// Returns the number of bitmap positions inspected.
    pub(super) fn inspected_words(&self) -> usize {
        self.inspected_words
    }

    /// Consumes the result and returns any won bits.
    pub(super) fn into_provisional(self) -> Option<ProvisionalBits> {
        self.provisional
    }
}

/// Single-owner cleanup token for a confirmed trim.
///
/// Dropping an unfinished token performs the same cleanup attempt as
/// [`TrimCleanup::finish`].
#[must_use = "confirmed trim cleanup must be completed or dropped"]
pub(super) struct TrimCleanup {
    /// Slot whose prepared capacity was removed.
    slot: Arc<BlockSlot>,
    /// Draining incarnation confirmed free by trim.
    incarnation: Arc<BlockIncarnation>,
    /// `true` after cleanup has been attempted.
    consumed: bool,
}

impl TrimCleanup {
    /// Returns the number of carriers already removed from prepared capacity.
    pub(super) fn carrier_count(&self) -> CarrierCount {
        self.slot.carrier_count()
    }

    /// Makes the confirmed block inaccessible and reclaims its backing.
    ///
    /// Protection failure leaves the draining incarnation published.
    /// Discard failure retires it and records pending reclaim.
    pub(super) fn finish(mut self) -> Result<(), CleanupRetry> {
        self.consumed = true;
        self.finish_inner()
    }

    /// Performs the cleanup attempt after marking the token consumed.
    fn finish_inner(&self) -> Result<(), CleanupRetry> {
        let mut mapping = self.slot.mapping.lock();
        if !matches!(*mapping, MappingState::Prepared) {
            invariant_violation("trim cleanup started from a non-prepared mapping");
        }

        let current = self.slot.current.load();
        let Some(incarnation) = current.as_ref() else {
            invariant_violation("trim cleanup lost its current incarnation");
        };
        if !Arc::ptr_eq(incarnation, &self.incarnation)
            || incarnation.state.load(Ordering::Acquire) != IncarnationState::Draining
        {
            invariant_violation("trim cleanup no longer owns the draining incarnation");
        }

        if let Err(error) = self.slot.range.deactivate() {
            *mapping = MappingState::DeactivationRecoveryPending;
            return Err(CleanupRetry::DeactivationPending(error));
        }

        *mapping = MappingState::Reserved {
            reclaim_pending: false,
        };
        self.slot.finish_inactive_cleanup(&mut mapping)
    }
}

impl Drop for TrimCleanup {
    fn drop(&mut self) {
        if !self.consumed {
            self.consumed = true;
            let _ = self.finish_inner();
        }
    }
}

/// Claim state retained through the `Active` gate.
struct BlockClaimAttempt {
    /// Slot whose bitmap is being claimed.
    slot: Arc<BlockSlot>,
    /// Incarnation protected before the first bitmap mutation.
    incarnation: IncarnationGuard,
    /// Bits won by this attempt.
    won: Vec<WonWord>,
}

impl BlockClaimAttempt {
    /// Starts a claim against the current incarnation.
    ///
    /// Returns `None` when the slot has no published incarnation.
    fn begin(slot: &Arc<BlockSlot>) -> Result<Option<Self>, TryReserveError> {
        Self::begin_with_capacity(slot, slot.geometry.bitmap_words())
    }

    /// Starts a claim with storage for at most `won_capacity` bitmap words.
    fn begin_with_capacity(
        slot: &Arc<BlockSlot>,
        won_capacity: usize,
    ) -> Result<Option<Self>, TryReserveError> {
        let incarnation = slot.current.load();
        if incarnation.as_ref().is_none() {
            return Ok(None);
        }

        let mut won = Vec::new();
        won.try_reserve_exact(won_capacity)?;
        Ok(Some(Self {
            slot: Arc::clone(slot),
            incarnation,
            won,
        }))
    }

    /// Claims up to `count` free bits and returns the number won.
    ///
    /// A competing claim may take a candidate after the relaxed load:
    ///
    /// ```text
    /// this claim loads       0b0010  // bit 1 is occupied
    /// this claim selects     0b0101  // free bits 0 and 2
    /// another claim sets     0b0100  // competitor wins bit 2
    /// fetch_or returns       0b0110  // occupancy before this fetch_or
    /// this claim wins        0b0001  // candidate & !previous
    /// ```
    #[cfg(test)]
    fn take(&mut self, count: usize) -> usize {
        self.take_words(0, self.slot.geometry.bitmap_words(), count)
            .0
    }

    /// Claims from `word_count` words beginning at `start_word`.
    ///
    /// Returns carriers won and bitmap words inspected.
    fn take_words(
        &mut self,
        start_word: usize,
        word_count: usize,
        mut count: usize,
    ) -> (usize, usize) {
        let incarnation = self
            .incarnation
            .as_ref()
            .expect("a claim attempt protects one incarnation");
        let mut taken = 0;
        let mut inspected = 0;
        let end_word = start_word
            .saturating_add(word_count)
            .min(incarnation.in_use.len());

        let start_word = start_word.min(end_word);
        for word_index in start_word..end_word {
            if count == 0 {
                break;
            }
            inspected += 1;
            let word = &incarnation.in_use[word_index];
            let valid = bitmap_word_mask(self.slot.geometry, word_index);
            let observed = word.load(Ordering::Relaxed);
            let candidate = take_lowest(!observed & valid, count);
            if candidate == 0 {
                continue;
            }
            let previous = word.fetch_or(candidate, Ordering::SeqCst);
            let won = candidate & !previous;
            if won != 0 {
                let won_count = won.count_ones() as usize;
                record_won(&mut self.won, word_index, won);
                count -= won_count;
                taken += won_count;
            }
        }
        (taken, inspected)
    }

    /// Claims `word_count` consecutive fully free bitmap words.
    ///
    /// A false result may retain words in this attempt; the caller must roll
    /// the complete attempt back.
    fn take_word_run(
        &mut self,
        start_word: usize,
        word_limit: usize,
        word_count: usize,
    ) -> (bool, usize) {
        let incarnation = self
            .incarnation
            .as_ref()
            .expect("a claim attempt protects one incarnation");
        let end_word = start_word
            .saturating_add(word_limit)
            .min(incarnation.in_use.len());
        let scan_start = start_word.min(end_word);
        let mut run_start = scan_start;
        let mut inspected = 0;

        for word_index in scan_start..end_word {
            inspected += 1;
            let fully_free = bitmap_word_mask(self.slot.geometry, word_index) == u64::MAX
                && incarnation.in_use[word_index].load(Ordering::Relaxed) == 0;
            if !fully_free {
                run_start = word_index + 1;
                continue;
            }
            if word_index + 1 - run_start < word_count {
                continue;
            }
            for index in run_start..=word_index {
                if incarnation.in_use[index]
                    .compare_exchange(0, u64::MAX, Ordering::SeqCst, Ordering::Relaxed)
                    .is_err()
                {
                    return (false, inspected);
                }
                record_won(&mut self.won, index, u64::MAX);
            }
            return (true, inspected);
        }
        (false, inspected)
    }

    /// Claims until each word is observed full or `count` carriers are won.
    fn take_exhaustive(&mut self, mut count: usize) -> usize {
        let incarnation = self
            .incarnation
            .as_ref()
            .expect("a claim attempt protects one incarnation");
        let mut taken = 0;

        for (word_index, word) in incarnation.in_use.iter().enumerate() {
            let mut observed = word.load(Ordering::Relaxed);
            while count != 0 {
                let valid = bitmap_word_mask(self.slot.geometry, word_index);
                let candidate = take_lowest(!observed & valid, count);
                if candidate == 0 {
                    break;
                }
                let previous = word.fetch_or(candidate, Ordering::SeqCst);
                // Each collision enters the local occupancy view. The loop
                // therefore retries at most once per valid carrier bit.
                observed = previous | candidate;
                let won = candidate & !previous;
                if won != 0 {
                    let won_count = won.count_ones() as usize;
                    record_won(&mut self.won, word_index, won);
                    count -= won_count;
                    taken += won_count;
                }
            }
            if count == 0 {
                break;
            }
        }
        taken
    }

    /// Passes the state gate or rolls back every bit won by this attempt.
    fn finish(mut self) -> Option<ProvisionalBits> {
        if self.won.is_empty() {
            return None;
        }
        let incarnation = self
            .incarnation
            .as_ref()
            .expect("a claim attempt protects one incarnation");
        loom_seq_cst_fence();
        match incarnation.state.load(Ordering::SeqCst) {
            IncarnationState::Active => {}
            IncarnationState::Draining | IncarnationState::Dead => {
                self.rollback_original();
                return None;
            }
        }

        let incarnation = BlockIncarnation::identity(incarnation);
        let won = std::mem::take(&mut self.won);
        Some(ProvisionalBits {
            slot: Arc::clone(&self.slot),
            incarnation,
            won,
        })
    }

    /// Clears remaining bits through the originally protected incarnation.
    fn rollback_original(&mut self) {
        let Some(incarnation) = self.incarnation.as_ref() else {
            return;
        };
        for word in self.won.drain(..) {
            clear_owned_bits(&incarnation.in_use[word.word_index], word.mask);
        }
    }
}

impl Drop for BlockClaimAttempt {
    fn drop(&mut self) {
        self.rollback_original();
    }
}

/// Single-owner set of gate-passed bits not yet converted to carriers.
pub(super) struct ProvisionalBits {
    /// Slot containing the owned bits.
    slot: Arc<BlockSlot>,
    /// Incarnation containing the owned bits.
    incarnation: IncarnationIdentity,
    /// Bits returned if this owner is dropped.
    won: Vec<WonWord>,
}

impl ProvisionalBits {
    /// Returns the number of provisionally owned carriers.
    pub(super) fn len(&self) -> CarrierCount {
        CarrierCount::new(
            self.won
                .iter()
                .map(|word| word.mask.count_ones() as usize)
                .sum(),
        )
    }

    /// Converts every provisional bit into one carrier owner.
    ///
    /// Allocation failure returns every provisional bit on drop.
    /// A carrier index is `word_index * 64 + bit_index`. Bitmap word 1 bits 1
    /// and 3 therefore become carrier indices 65 and 67.
    pub(super) fn into_carriers(mut self) -> Result<Vec<CarrierAllocation>, BlockError> {
        let mut carriers = Vec::new();
        carriers.try_reserve_exact(self.len().get())?;

        for word in &mut self.won {
            while word.mask != 0 {
                let bit = word.mask.trailing_zeros() as usize;
                let mask = 1u64 << bit;
                let index = word.word_index * u64::BITS as usize + bit;
                let index = u32::try_from(index)
                    .unwrap_or_else(|_| invariant_violation("carrier index exceeds geometry"));
                let carrier = CarrierAllocation {
                    slot: Arc::clone(&self.slot),
                    id: Some(CarrierId {
                        slot: self.slot.id,
                        index,
                        incarnation: self.incarnation,
                    }),
                };

                // Move ownership before push so unwinding leaves each bit with
                // exactly one drop path.
                word.mask &= !mask;
                carriers.push(carrier);
            }
        }
        Ok(carriers)
    }
}

impl Drop for ProvisionalBits {
    fn drop(&mut self) {
        self.slot.release_won(self.incarnation, &self.won);
    }
}

/// Single-owner physical allocation for one carrier.
pub(super) struct CarrierAllocation {
    /// Slot that retains the carrier address.
    slot: Arc<BlockSlot>,
    /// Stable carrier and incarnation identity.
    id: Option<CarrierId>,
}

impl CarrierAllocation {
    /// Returns this allocation's live carrier identity.
    fn id(&self) -> CarrierId {
        self.id
            .unwrap_or_else(|| invariant_violation("carrier allocation returned its bit twice"))
    }

    /// Returns the concrete slot that roots this carrier's pointer provenance.
    pub(super) fn slot(&self) -> &Arc<BlockSlot> {
        &self.slot
    }

    /// Returns this carrier's stable physical location within the arena.
    pub(super) fn location(&self) -> CarrierLocation {
        let id = self.id();
        CarrierLocation::new(id.slot, id.index)
    }

    /// Returns the stable block-slot identifier.
    pub(super) fn slot_id(&self) -> u32 {
        self.location().slot_id()
    }

    /// Returns the carrier index within its block.
    pub(super) fn carrier_index(&self) -> u32 {
        self.location().carrier_index()
    }

    /// Returns the carrier capacity in bytes.
    pub(super) fn capacity(&self) -> usize {
        self.slot.geometry.carrier_size()
    }

    /// Returns the first byte of this carrier.
    ///
    /// The range remains prepared and exclusively owned while `self` lives.
    /// Dereferencing the pointer must still obey initialization rules.
    pub(super) fn ptr(&self) -> NonNull<MaybeUninit<u8>> {
        let index = self.id().index as usize;
        let offset = self
            .slot
            .geometry
            .carrier_offset(index)
            .unwrap_or_else(|| invariant_violation("carrier index is outside block geometry"));
        // SAFETY: this allocation owns the carrier bit after passing the
        // `Active` gate, and its Arc retains the slot for the pointer lifetime.
        unsafe {
            self.slot
                .range
                .ptr_for_range(offset, self.capacity())
                .unwrap_or_else(|| invariant_violation("carrier range is outside its reservation"))
        }
    }
}

impl Drop for CarrierAllocation {
    fn drop(&mut self) {
        if let Some(id) = self.id.take() {
            self.slot.release_one(id);
        }
    }
}

/// Consecutive physical returns accumulated for one bitmap word.
struct CarrierWordReturn {
    /// Stable slot whose current incarnation owns the returned bits.
    slot: Arc<BlockSlot>,
    /// Incarnation that issued every carrier in `mask`.
    incarnation: IncarnationIdentity,
    /// Bitmap word containing every returned carrier.
    word_index: usize,
    /// Bits returned together when this group drops.
    mask: u64,
}

impl Drop for CarrierWordReturn {
    fn drop(&mut self) {
        self.slot.release_won(
            self.incarnation,
            &[WonWord {
                word_index: self.word_index,
                mask: self.mask,
            }],
        );
    }
}

/// Physical-first return accumulator for adjacent bitmap-word owners.
pub(super) struct CarrierAllocationBatch {
    /// Current homogeneous bitmap-word group.
    current: Option<CarrierWordReturn>,
}

impl CarrierAllocationBatch {
    /// Creates an empty physical return batch.
    pub(super) fn new() -> Self {
        Self { current: None }
    }

    /// Transfers one owner into its consecutive bitmap-word group.
    pub(super) fn push(&mut self, allocation: &mut CarrierAllocation) {
        let id = allocation.id();
        let word_index = id.index as usize / u64::BITS as usize;
        let mask = 1u64 << (id.index as usize % u64::BITS as usize);
        let can_extend = self.current.as_ref().is_some_and(|word| {
            Arc::ptr_eq(&word.slot, &allocation.slot)
                && word.incarnation == id.incarnation
                && word.word_index == word_index
        });
        if can_extend {
            self.current
                .as_mut()
                .unwrap_or_else(|| invariant_violation("carrier return group disappeared"))
                .mask |= mask;
        } else {
            drop(self.current.take());
            self.current = Some(CarrierWordReturn {
                slot: Arc::clone(&allocation.slot),
                incarnation: id.incarnation,
                word_index,
                mask,
            });
        }
        allocation.id = None;
    }
}

/// Clears `mask` after verifying that every bit is owned.
fn clear_owned_bits(word: &AtomicU64, mask: u64) {
    if mask == 0 {
        return;
    }
    let mut observed = word.load(Ordering::Acquire);
    loop {
        if observed & mask != mask {
            invariant_violation("bitmap release does not own every cleared bit");
        }
        match word.compare_exchange_weak(
            observed,
            observed & !mask,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(_) => return,
            Err(actual) => observed = actual,
        }
    }
}

/// Returns valid bits for a checked bitmap word.
fn bitmap_word_mask(geometry: PoolGeometry, word_index: usize) -> u64 {
    geometry
        .bitmap_word_mask(word_index)
        .unwrap_or_else(|| invariant_violation("incarnation bitmap exceeds block geometry"))
}

/// Selects at most `count` least-significant bits from `available`.
///
/// The loop executes at most `min(count, available.count_ones())` times and
/// never more than 64 times.
fn take_lowest(available: u64, count: usize) -> u64 {
    let mut remaining = available;
    for _ in 0..count.min(u64::BITS as usize) {
        if remaining == 0 {
            break;
        }
        remaining &= remaining - 1;
    }
    available ^ remaining
}

/// Records disjoint bits while retaining at most one entry per word.
fn record_won(won: &mut Vec<WonWord>, word_index: usize, mask: u64) {
    if let Some(word) = won.last_mut().filter(|word| word.word_index == word_index) {
        word.mask |= mask;
    } else {
        won.push(WonWord { word_index, mask });
    }
}

/// Supplies the store-load edge missing from Loom's atomic model.
///
/// Production `SeqCst` operations already provide the required global order.
/// Loom 0.7 treats those accesses as `AcqRel`, but models a `SeqCst` fence.
#[inline]
fn loom_seq_cst_fence() {
    #[cfg(all(test, s3_tm_loom))]
    loom::sync::atomic::fence(Ordering::SeqCst);
}

#[cfg(all(test, not(s3_tm_loom)))]
mod tests {
    use std::panic::{catch_unwind, AssertUnwindSafe};

    use super::super::virtual_memory::{page_size, VirtualMemoryOperation};
    use super::*;

    fn geometry(carriers: usize) -> PoolGeometry {
        let page_size = page_size().unwrap().get();
        PoolGeometry::new(page_size, page_size * carriers, page_size).unwrap()
    }

    fn prepared_slot(carriers: usize) -> (Arc<BlockSlot>, CarrierCount) {
        let slot = Arc::new(BlockSlot::new(7, geometry(carriers)).unwrap());
        let mut prepared = CarrierCount::ZERO;
        slot.prepare(&mut prepared).unwrap();
        (slot, prepared)
    }

    fn current_identity(slot: &BlockSlot) -> Option<IncarnationIdentity> {
        slot.current.load().as_ref().map(BlockIncarnation::identity)
    }

    fn assert_mapping(slot: &BlockSlot, expected: MappingState) {
        assert_eq!(*slot.mapping.lock(), expected);
    }

    #[test]
    fn incarnation_transitions_enforce_their_predecessors() {
        let state = AtomicIncarnationState::new(IncarnationState::Active);

        assert_eq!(state.try_start_trim(), Ok(()));
        assert_eq!(state.load(Ordering::Acquire), IncarnationState::Draining);
        assert_eq!(state.try_start_trim(), Err(IncarnationState::Draining));
        state.restore_active();
        assert_eq!(state.load(Ordering::Acquire), IncarnationState::Active);

        let invalid_retire = catch_unwind(AssertUnwindSafe(|| state.retire()));
        assert!(invalid_retire.is_err());
        assert_eq!(state.load(Ordering::Acquire), IncarnationState::Active);

        state.try_start_trim().unwrap();
        state.retire();
        assert_eq!(state.load(Ordering::Acquire), IncarnationState::Dead);

        let invalid_restore = catch_unwind(AssertUnwindSafe(|| state.restore_active()));
        assert!(invalid_restore.is_err());
        assert_eq!(state.load(Ordering::Acquire), IncarnationState::Dead);
    }

    #[test]
    fn preparation_publishes_claimable_capacity() {
        let (slot, prepared) = prepared_slot(3);

        assert_eq!(prepared, CarrierCount::new(3));
        let claimed = BlockSlot::try_claim(&slot, CarrierCount::new(3))
            .unwrap()
            .unwrap();
        assert_eq!(claimed.len(), CarrierCount::new(3));
        assert_eq!(slot.live_carriers(), 3);

        drop(claimed);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[cfg(debug_assertions)]
    #[test]
    fn test_immutable_range_live_check_covers_each_intersecting_carrier() {
        let (slot, _) = prepared_slot(3);
        let carrier_size = slot.geometry.carrier_size();
        let claimed = BlockSlot::try_claim(&slot, CarrierCount::new(2))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();

        slot.debug_assert_immutable_range_live(carrier_size - 1, 2);
        drop(claimed);

        let missing_live_bit = catch_unwind(AssertUnwindSafe(|| {
            slot.debug_assert_immutable_range_live(carrier_size - 1, 2);
        }));
        assert!(missing_live_bit.is_err());
    }

    #[test]
    fn preclaimed_activation_publishes_owned_bits() {
        let slot = Arc::new(BlockSlot::new(7, geometry(4)).unwrap());
        let mut prepared = CarrierCount::ZERO;

        let preclaimed =
            BlockSlot::prepare_and_claim_if_inactive(&slot, &mut prepared, CarrierCount::new(2))
                .unwrap()
                .expect("fresh slot should activate");

        assert_eq!(prepared, CarrierCount::new(4));
        assert_eq!(preclaimed.len(), CarrierCount::new(2));
        assert_eq!(slot.live_carriers(), 2);
        let preclaimed = preclaimed.into_carriers().unwrap();
        assert_eq!(
            preclaimed
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![0, 1]
        );

        let remaining = BlockSlot::try_claim(&slot, CarrierCount::new(4))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        assert_eq!(
            remaining
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![2, 3]
        );

        drop(preclaimed);
        drop(remaining);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn preclaimed_activation_crosses_bitmap_words_without_padding() {
        let slot = Arc::new(BlockSlot::new(7, geometry(70)).unwrap());
        let mut prepared = CarrierCount::ZERO;

        let preclaimed =
            BlockSlot::prepare_and_claim_if_inactive(&slot, &mut prepared, CarrierCount::new(67))
                .unwrap()
                .expect("fresh slot should activate")
                .into_carriers()
                .unwrap();

        assert_eq!(prepared, CarrierCount::new(70));
        assert_eq!(preclaimed.len(), 67);
        assert_eq!(preclaimed.first().unwrap().carrier_index(), 0);
        assert_eq!(preclaimed.last().unwrap().carrier_index(), 66);

        let remaining = BlockSlot::try_claim(&slot, CarrierCount::new(70))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        assert_eq!(
            remaining
                .iter()
                .map(CarrierAllocation::carrier_index)
                .collect::<Vec<_>>(),
            vec![67, 68, 69]
        );
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());

        drop(preclaimed);
        drop(remaining);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn failed_preclaimed_activation_publishes_no_ownership() {
        let slot = Arc::new(BlockSlot::new(7, geometry(2)).unwrap());
        let mut prepared = CarrierCount::ZERO;
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Prepare);

        let error = match BlockSlot::prepare_and_claim_if_inactive(
            &slot,
            &mut prepared,
            CarrierCount::new(1),
        ) {
            Ok(_) => panic!("injected preparation failure must reject activation"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            BlockError::VirtualMemory(ref error)
                if error.operation() == VirtualMemoryOperation::Prepare
        ));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_eq!(slot.live_carriers(), 0);
        assert!(current_identity(&slot).is_none());
        assert_mapping(&slot, MappingState::ActivationRecoveryPending);
    }

    #[test]
    fn preclaimed_activation_rejects_invalid_counts_without_mutation() {
        let slot = Arc::new(BlockSlot::new(7, geometry(2)).unwrap());
        let mut prepared = CarrierCount::ZERO;

        assert!(matches!(
            BlockSlot::prepare_and_claim_if_inactive(&slot, &mut prepared, CarrierCount::ZERO),
            Err(BlockError::InvalidClaimCount)
        ));
        assert!(matches!(
            BlockSlot::prepare_and_claim_if_inactive(&slot, &mut prepared, CarrierCount::new(3)),
            Err(BlockError::ClaimExceedsBlock {
                requested: 3,
                capacity: 2
            })
        ));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_eq!(slot.live_carriers(), 0);
        assert!(current_identity(&slot).is_none());
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
    }

    #[test]
    fn preclaimed_activation_does_not_replace_retained_metadata() {
        let (slot, mut prepared) = prepared_slot(1);
        let identity = current_identity(&slot).unwrap();
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Deactivate);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();
        assert!(matches!(
            cleanup.finish(),
            Err(CleanupRetry::DeactivationPending(_))
        ));

        assert!(BlockSlot::prepare_and_claim_if_inactive(
            &slot,
            &mut prepared,
            CarrierCount::new(1)
        )
        .unwrap()
        .is_none());
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_eq!(current_identity(&slot), Some(identity));
        assert_eq!(slot.live_carriers(), 0);

        slot.prepare(&mut prepared).unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        assert_eq!(current_identity(&slot), Some(identity));
    }

    #[test]
    fn preparation_rejects_a_current_incarnation() {
        let (slot, mut prepared) = prepared_slot(1);

        assert!(matches!(
            slot.prepare(&mut prepared),
            Err(BlockError::AlreadyPrepared)
        ));
        assert_eq!(prepared, CarrierCount::new(1));
    }

    #[test]
    fn failed_prepare_stays_nonclaimable_until_recovery() {
        let slot = Arc::new(BlockSlot::new(7, geometry(1)).unwrap());
        let mut prepared = CarrierCount::ZERO;
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Prepare);

        let error = slot.prepare(&mut prepared).unwrap_err();

        assert!(matches!(
            error,
            BlockError::VirtualMemory(ref error)
                if error.operation() == VirtualMemoryOperation::Prepare
        ));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(&slot, MappingState::ActivationRecoveryPending);
        assert!(current_identity(&slot).is_none());
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());

        slot.prepare(&mut prepared).unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        assert_mapping(&slot, MappingState::Prepared);
        assert!(current_identity(&slot).is_some());
    }

    #[test]
    fn cleanup_retry_restores_reserved_state_after_initial_prepare_failure() {
        let slot = Arc::new(BlockSlot::new(7, geometry(1)).unwrap());
        let mut prepared = CarrierCount::ZERO;
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Prepare);
        assert!(slot.prepare(&mut prepared).is_err());
        assert_mapping(&slot, MappingState::ActivationRecoveryPending);
        assert!(current_identity(&slot).is_none());

        slot.retry_cleanup().unwrap();

        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
        assert!(current_identity(&slot).is_none());

        slot.prepare(&mut prepared).unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        let carrier = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .expect("cleaned slot is claimable");
        drop(carrier);
    }

    #[test]
    fn cleanup_retry_is_a_noop_without_pending_work() {
        let slot = Arc::new(BlockSlot::new(7, geometry(1)).unwrap());
        let mut prepared = CarrierCount::ZERO;

        slot.retry_cleanup().unwrap();
        assert!(matches!(
            BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO),
            Err(TrimBlocked::NotPrepared)
        ));

        slot.prepare(&mut prepared).unwrap();
        slot.retry_cleanup().unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        assert_mapping(&slot, MappingState::Prepared);
    }

    #[test]
    fn carrier_pointer_is_derived_from_live_ownership() {
        let (slot, _) = prepared_slot(1);
        let mut carriers = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        let carrier = carriers.pop().unwrap();

        assert_eq!(carrier.capacity(), geometry(1).carrier_size());
        // SAFETY: the carrier allocation owns this complete writable byte.
        unsafe { carrier.ptr().as_ptr().write(MaybeUninit::new(0x5a)) };
        // SAFETY: the preceding write initialized the byte.
        assert_eq!(unsafe { carrier.ptr().as_ptr().read().assume_init() }, 0x5a);

        drop(carrier);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn bounded_claim_inspects_only_its_word_window() {
        let (slot, _) = prepared_slot(130);

        let claim = BlockSlot::try_claim_words(&slot, 1, 1, CarrierCount::new(2)).unwrap();
        assert_eq!(claim.inspected_words(), 1);
        let carriers = claim.into_provisional().unwrap().into_carriers().unwrap();
        assert_eq!(
            carriers
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![64, 65]
        );
        drop(carriers);

        let final_word =
            BlockSlot::try_claim_words(&slot, 2, usize::MAX, CarrierCount::new(8)).unwrap();
        assert_eq!(final_word.inspected_words(), 1);
        let carriers = final_word
            .into_provisional()
            .unwrap()
            .into_carriers()
            .unwrap();
        assert_eq!(
            carriers
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![128, 129]
        );
        drop(carriers);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn word_run_claim_skips_fragmented_prefix() {
        let (slot, _) = prepared_slot(192);
        let mut occupied = BlockSlot::try_claim(&slot, CarrierCount::new(192))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        drop(occupied.drain(64..128).collect::<Vec<_>>());

        let claim = BlockSlot::try_claim_word_run(&slot, 0, 3, 1).unwrap();

        assert_eq!(claim.inspected_words(), 2);
        let run = claim.into_provisional().unwrap().into_carriers().unwrap();
        assert_eq!(run.len(), 64);
        assert_eq!(run.first().unwrap().carrier_index(), 64);
        assert_eq!(run.last().unwrap().carrier_index(), 127);

        drop(run);
        drop(occupied);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn word_run_miss_leaves_fragmented_capacity_available() {
        let (slot, _) = prepared_slot(192);
        let mut occupied = BlockSlot::try_claim(&slot, CarrierCount::new(192))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        drop(occupied.drain(128..192).collect::<Vec<_>>());
        drop(occupied.drain(0..64).collect::<Vec<_>>());

        let claim = BlockSlot::try_claim_word_run(&slot, 0, 3, 2).unwrap();

        assert_eq!(claim.inspected_words(), 3);
        assert!(claim.into_provisional().is_none());
        let fragmented = BlockSlot::try_claim(&slot, CarrierCount::new(128))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        assert_eq!(fragmented.len(), 128);

        drop(fragmented);
        drop(occupied);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn empty_claim_windows_do_not_mutate_ownership() {
        let (slot, _) = prepared_slot(65);

        let zero_budget = BlockSlot::try_claim_words(&slot, 0, 0, CarrierCount::new(1)).unwrap();
        assert_eq!(zero_budget.inspected_words(), 0);
        assert!(zero_budget.into_provisional().is_none());

        let past_end =
            BlockSlot::try_claim_words(&slot, slot.bitmap_words(), 1, CarrierCount::new(1))
                .unwrap();
        assert_eq!(past_end.inspected_words(), 0);
        assert!(past_end.into_provisional().is_none());
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn inactive_window_consumes_scan_positions_without_claiming() {
        let slot = Arc::new(BlockSlot::new(7, geometry(65)).unwrap());

        let claim = BlockSlot::try_claim_words(&slot, 0, usize::MAX, CarrierCount::new(1)).unwrap();

        assert_eq!(claim.inspected_words(), 2);
        assert!(claim.into_provisional().is_none());
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn claim_never_wins_padding_bits() {
        let (slot, _) = prepared_slot(65);
        let carriers = BlockSlot::try_claim(&slot, CarrierCount::new(65))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();

        assert_eq!(carriers.len(), 65);
        assert_eq!(carriers.last().unwrap().id().index, 64);
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());

        drop(carriers);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn dropping_provisional_bits_returns_every_word() {
        let (slot, _) = prepared_slot(65);
        let provisional = BlockSlot::try_claim(&slot, CarrierCount::new(65))
            .unwrap()
            .unwrap();

        assert_eq!(slot.live_carriers(), 65);
        drop(provisional);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn concurrent_attempts_clear_only_their_won_bits() {
        let (slot, _) = prepared_slot(3);
        let mut first = BlockClaimAttempt::begin(&slot).unwrap().unwrap();
        let mut second = BlockClaimAttempt::begin(&slot).unwrap().unwrap();

        assert_eq!(first.take(1), 1);
        assert_eq!(second.take(2), 2);
        let first = first.finish().unwrap();
        let second = second.finish().unwrap();
        assert_eq!(slot.live_carriers(), 3);

        drop(first);
        assert_eq!(slot.live_carriers(), 2);
        drop(second);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn partial_claim_crosses_a_bitmap_word_boundary() {
        let (slot, _) = prepared_slot(66);
        let first = BlockSlot::try_claim(&slot, CarrierCount::new(63))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();

        let second = BlockSlot::try_claim(&slot, CarrierCount::new(3))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();

        assert_eq!(first.last().unwrap().id().index, 62);
        assert_eq!(
            second
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![63, 64, 65]
        );
        drop(first);
        drop(second);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn provisional_word_bits_map_to_carrier_indices() {
        let (slot, _) = prepared_slot(68);
        let incarnation = {
            let current = slot.current.load();
            let incarnation = current.as_ref().expect("slot is prepared");
            incarnation.in_use[1].store(0b1010, Ordering::Release);
            BlockIncarnation::identity(incarnation)
        };
        let provisional = ProvisionalBits {
            slot: Arc::clone(&slot),
            incarnation,
            won: vec![WonWord {
                word_index: 1,
                mask: 0b1010,
            }],
        };

        let carriers = provisional.into_carriers().unwrap();

        assert_eq!(
            carriers
                .iter()
                .map(|carrier| carrier.id().index)
                .collect::<Vec<_>>(),
            vec![65, 67]
        );
        drop(carriers);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn dropping_unfinished_attempt_returns_original_bits() {
        let (slot, _) = prepared_slot(2);
        let mut attempt = BlockClaimAttempt::begin(&slot).unwrap().unwrap();

        assert_eq!(attempt.take(2), 2);
        assert_eq!(slot.live_carriers(), 2);
        drop(attempt);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn trim_preserves_floor_and_abandons_for_live_ownership() {
        let (slot, mut prepared) = prepared_slot(2);

        assert!(matches!(
            BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::new(1)),
            Err(TrimBlocked::FloorViolation)
        ));
        assert_eq!(prepared, CarrierCount::new(2));

        let carriers = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        assert!(matches!(
            BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO),
            Err(TrimBlocked::Busy)
        ));
        assert_eq!(prepared, CarrierCount::new(2));
        assert_mapping(&slot, MappingState::Prepared);

        drop(carriers);
    }

    #[test]
    fn successful_trim_revives_with_fresh_metadata_at_the_same_address() {
        let (slot, mut prepared) = prepared_slot(1);
        let original_incarnation =
            Arc::clone(slot.current.load().as_ref().expect("slot is prepared"));
        let original_address = slot.range.base_address();

        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();
        assert_eq!(cleanup.carrier_count(), CarrierCount::new(1));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());
        cleanup.finish().unwrap();

        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
        assert!(current_identity(&slot).is_none());

        slot.prepare(&mut prepared).unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        assert_eq!(slot.range.base_address(), original_address);
        let revived = slot.current.load();
        assert!(!Arc::ptr_eq(
            revived.as_ref().expect("slot was revived"),
            &original_incarnation
        ));
    }

    #[test]
    fn stale_failed_gate_rolls_back_only_retired_metadata() {
        let (slot, mut prepared) = prepared_slot(1);
        let mut stale = BlockClaimAttempt::begin(&slot).unwrap().unwrap();

        BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO)
            .unwrap()
            .finish()
            .unwrap();
        slot.prepare(&mut prepared).unwrap();
        let current = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();

        assert_eq!(stale.take(1), 1);
        assert!(stale.finish().is_none());
        assert_eq!(slot.live_carriers(), 1);

        drop(current);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn failed_deactivation_can_restore_the_draining_incarnation() {
        let (slot, mut prepared) = prepared_slot(1);
        let original_identity = current_identity(&slot).unwrap();
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Deactivate);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();

        let error = cleanup.finish().unwrap_err();

        assert!(matches!(
            error,
            CleanupRetry::DeactivationPending(ref error)
                if error.operation() == VirtualMemoryOperation::Deactivate
        ));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(&slot, MappingState::DeactivationRecoveryPending);
        assert_eq!(current_identity(&slot), Some(original_identity));
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());
        assert!(matches!(
            BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO),
            Err(TrimBlocked::CleanupPending)
        ));

        slot.prepare(&mut prepared).unwrap();
        assert_eq!(prepared, CarrierCount::new(1));
        assert_mapping(&slot, MappingState::Prepared);
        assert_eq!(current_identity(&slot), Some(original_identity));
        let carrier = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap();
        drop(carrier);
    }

    #[test]
    fn protection_retry_finishes_inactive_cleanup() {
        let (slot, mut prepared) = prepared_slot(1);
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Deactivate);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();
        assert!(matches!(
            cleanup.finish(),
            Err(CleanupRetry::DeactivationPending(_))
        ));

        slot.retry_cleanup().unwrap();

        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
        assert!(current_identity(&slot).is_none());
    }

    #[test]
    fn failed_discard_retires_the_incarnation_and_retries_inactive() {
        let (slot, mut prepared) = prepared_slot(1);
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Discard);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();

        let error = cleanup.finish().unwrap_err();

        assert!(matches!(
            error,
            CleanupRetry::ReclaimPending(ref error)
                if error.operation() == VirtualMemoryOperation::Discard
        ));
        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: true,
            },
        );
        assert!(current_identity(&slot).is_none());

        slot.retry_cleanup().unwrap();
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
    }

    #[test]
    fn revival_clears_pending_reclaim_before_publication() {
        let (slot, mut prepared) = prepared_slot(1);
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Discard);
        BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO)
            .unwrap()
            .finish()
            .unwrap_err();

        slot.prepare(&mut prepared).unwrap();
        slot.retry_cleanup().unwrap();

        assert_eq!(prepared, CarrierCount::new(1));
        assert_mapping(&slot, MappingState::Prepared);
        let carrier = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap();
        drop(carrier);
    }

    #[test]
    fn dropped_cleanup_completes_the_confirmed_trim() {
        let (slot, mut prepared) = prepared_slot(1);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();

        drop(cleanup);

        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(
            &slot,
            MappingState::Reserved {
                reclaim_pending: false,
            },
        );
        assert!(current_identity(&slot).is_none());
    }

    #[test]
    fn dropped_cleanup_leaves_failed_protection_nonclaimable() {
        let (slot, mut prepared) = prepared_slot(1);
        slot.range
            .inject_failure_once(VirtualMemoryOperation::Deactivate);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();

        drop(cleanup);

        assert_eq!(prepared, CarrierCount::ZERO);
        assert_mapping(&slot, MappingState::DeactivationRecoveryPending);
        assert!(current_identity(&slot).is_some());
        assert!(BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .is_none());
    }

    #[test]
    fn identity_mismatch_stops_before_clearing() {
        let (slot, _) = prepared_slot(1);
        let mut carriers = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        let carrier = carriers.pop().unwrap();
        let wrong = CarrierId {
            incarnation: IncarnationIdentity(
                NonZeroUsize::new(carrier.id().incarnation.0.get().wrapping_add(1))
                    .unwrap_or(NonZeroUsize::MIN),
            ),
            ..carrier.id()
        };

        let result = catch_unwind(AssertUnwindSafe(|| slot.release_one(wrong)));

        assert!(result.is_err());
        assert_eq!(slot.live_carriers(), 1);
        drop(carrier);
        assert_eq!(slot.live_carriers(), 0);
    }

    #[test]
    fn slot_mismatch_stops_before_clearing() {
        let (slot, _) = prepared_slot(1);
        let mut carriers = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        let carrier = carriers.pop().unwrap();
        let wrong = CarrierId {
            slot: carrier.id().slot + 1,
            ..carrier.id()
        };

        let result = catch_unwind(AssertUnwindSafe(|| slot.release_one(wrong)));

        assert!(result.is_err());
        assert_eq!(slot.live_carriers(), 1);
        drop(carrier);
        assert_eq!(slot.live_carriers(), 0);
    }

    /// Covers selection against a fixed occupancy pattern.
    ///
    /// A set bit is a free carrier, so `0b1011_0100` offers four at positions
    /// 2, 4, 5, and 7. Selection consumes them upward from position 2, and a
    /// request larger than the free count stops at every free bit.
    #[test]
    fn selects_only_the_requested_low_bits() {
        assert_eq!(take_lowest(0, 8), 0);
        assert_eq!(take_lowest(0b1011_0100, 0), 0);
        assert_eq!(take_lowest(0b1011_0100, 1), 0b0000_0100);
        assert_eq!(take_lowest(0b1011_0100, 3), 0b0011_0100);
        assert_eq!(take_lowest(0b1011_0100, usize::MAX), 0b1011_0100);
        assert_eq!(take_lowest(u64::MAX, usize::MAX), u64::MAX);
    }

    #[test]
    fn repeated_wins_in_one_word_share_one_record() {
        let mut won = Vec::new();

        record_won(&mut won, 1, 0b0001);
        record_won(&mut won, 1, 0b0100);
        record_won(&mut won, 2, 0b0010);

        assert_eq!(won.len(), 2);
        assert_eq!(won[0].word_index, 1);
        assert_eq!(won[0].mask, 0b0101);
        assert_eq!(won[1].word_index, 2);
        assert_eq!(won[1].mask, 0b0010);
    }

    /// Covers every occupancy pattern in the low bytes plus full-width cases.
    ///
    /// Selection must satisfy three properties: it selects only free bits, it
    /// selects the requested count or every free bit when fewer are available,
    /// and the bits it selects are the lowest free ones. The sweep covers bit
    /// arrangements; the listed patterns cover positions and counts a 16-bit
    /// sweep cannot reach.
    #[test]
    #[cfg_attr(
        miri,
        ignore = "exhaustive pure-integer sweep adds no Miri-specific coverage"
    )]
    fn take_lowest_returns_exact_lowest_subset() {
        fn assert_lowest_subset(available: u64, count: usize) {
            let selected = take_lowest(available, count);
            assert_eq!(
                selected & !available,
                0,
                "selected unavailable bits from {available:#018x} with count {count}"
            );
            // A request larger than the free count saturates.
            assert_eq!(
                selected.count_ones() as usize,
                count.min(available.count_ones() as usize),
                "selected the wrong number of bits from {available:#018x} with count {count}"
            );

            // `leading_zeros` returns 64 for zero, which underflows the
            // position arithmetic below.
            let remaining = available & !selected;
            if selected != 0 && remaining != 0 {
                // A correctly sized subset is lowest iff no remaining bit is
                // below a selected bit.
                let highest_selected = u64::BITS - 1 - selected.leading_zeros();
                let lowest_remaining = remaining.trailing_zeros();
                assert!(
                    highest_selected < lowest_remaining,
                    "selected {selected:#018x} from {available:#018x} with count {count}"
                );
            }
        }

        for available in 0..=u16::MAX as u64 {
            for count in 0..=(u16::BITS as usize + 1) {
                assert_lowest_subset(available, count);
            }
        }

        // The top bit alone, the two most distant bits, a high bit above a
        // sparse low cluster, both alternating phases, and a fully free word.
        // Counts run past `u64::BITS` to cover the loop bound.
        for available in [
            1 << 63,
            (1 << 63) | 1,
            0x8000_0000_0000_00a5,
            0xaaaa_aaaa_aaaa_aaaa,
            0x5555_5555_5555_5555,
            u64::MAX,
        ] {
            for count in 0..=(u64::BITS as usize + 1) {
                assert_lowest_subset(available, count);
            }
        }
    }

    #[test]
    fn zero_claim_is_rejected_without_mutation() {
        let (slot, _) = prepared_slot(1);

        assert!(matches!(
            BlockSlot::try_claim(&slot, CarrierCount::ZERO),
            Err(BlockError::InvalidClaimCount)
        ));
        assert_eq!(slot.live_carriers(), 0);
    }

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn ownership_spine_is_send_and_sync() {
        assert_send_sync::<BlockSlot>();
        assert_send_sync::<CarrierAllocation>();
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use super::super::virtual_memory::VirtualMemoryOperation;
    use super::*;
    use crate::runtime::sync::sync::atomic::{AtomicBool, Ordering};
    use crate::runtime::sync::thread;

    fn prepared_slot() -> (Arc<BlockSlot>, CarrierCount) {
        let geometry = PoolGeometry::new(4096, 4096, 4096).unwrap();
        let slot = Arc::new(BlockSlot::new(0, geometry).unwrap());
        let mut prepared = CarrierCount::ZERO;
        slot.prepare(&mut prepared).unwrap();
        (slot, prepared)
    }

    #[test]
    fn stale_claim_cannot_clear_a_revived_claim() {
        loom::model(|| {
            let (slot, initial_prepared) = prepared_slot();
            let loaded = Arc::new(AtomicBool::new(false));
            let revived = Arc::new(AtomicBool::new(false));

            let stale_slot = Arc::clone(&slot);
            let stale_loaded = Arc::clone(&loaded);
            let stale_revived = Arc::clone(&revived);
            let stale = thread::spawn(move || {
                let mut attempt = BlockClaimAttempt::begin(&stale_slot).unwrap().unwrap();
                stale_loaded.store(true, Ordering::Release);
                while !stale_revived.load(Ordering::Acquire) {
                    loom::thread::yield_now();
                }
                assert_eq!(attempt.take(1), 1);
                assert!(attempt.finish().is_none());
            });

            let current_slot = Arc::clone(&slot);
            let current_loaded = Arc::clone(&loaded);
            let current_revived = Arc::clone(&revived);
            let current = thread::spawn(move || {
                while !current_loaded.load(Ordering::Acquire) {
                    loom::thread::yield_now();
                }
                let mut prepared = initial_prepared;
                BlockSlot::start_trim(&current_slot, &mut prepared, CarrierCount::ZERO)
                    .unwrap()
                    .finish()
                    .unwrap();
                current_slot.prepare(&mut prepared).unwrap();
                let carrier = BlockSlot::try_claim(&current_slot, CarrierCount::new(1))
                    .unwrap()
                    .unwrap()
                    .into_carriers()
                    .unwrap()
                    .pop()
                    .unwrap();
                current_revived.store(true, Ordering::Release);
                carrier
            });

            stale.join().unwrap();
            let carrier = current.join().unwrap();
            assert_eq!(slot.live_carriers(), 1);
            drop(carrier);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn claim_and_protection_recovery_preserve_single_ownership() {
        loom::model(|| {
            let (slot, mut prepared) = prepared_slot();
            let original = Arc::clone(slot.current.load().as_ref().expect("slot is prepared"));

            let mut attempt = BlockClaimAttempt::begin(&slot).unwrap().unwrap();
            slot.range
                .inject_failure_once(VirtualMemoryOperation::Deactivate);
            let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();
            assert!(matches!(
                cleanup.finish(),
                Err(CleanupRetry::DeactivationPending(_))
            ));
            assert_eq!(attempt.take(1), 1);

            let stale = thread::spawn(move || attempt.finish());
            let recovery_slot = Arc::clone(&slot);
            let recovery = thread::spawn(move || {
                recovery_slot.prepare(&mut prepared).unwrap();
                let current = BlockSlot::try_claim(&recovery_slot, CarrierCount::new(1)).unwrap();
                (prepared, current)
            });

            let stale = stale.join().unwrap();
            let (prepared, current) = recovery.join().unwrap();
            let owned = stale
                .as_ref()
                .map_or(0, |claim| claim.len().get())
                .checked_add(current.as_ref().map_or(0, |claim| claim.len().get()))
                .unwrap();

            assert_eq!(prepared, CarrierCount::new(1));
            assert!(matches!(*slot.mapping.lock(), MappingState::Prepared));
            let restored = slot.current.load();
            assert!(Arc::ptr_eq(
                restored.as_ref().expect("incarnation was restored"),
                &original
            ));
            assert!(owned <= 1);
            assert_eq!(slot.live_carriers(), owned);

            drop(stale);
            drop(current);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn claim_and_trim_cannot_both_pass_the_gate() {
        loom::model(|| {
            let (slot, initial_prepared) = prepared_slot();
            let prepared = Arc::new(Mutex::new(initial_prepared));

            let claim_slot = Arc::clone(&slot);
            let claim = thread::spawn(move || {
                BlockSlot::try_claim(&claim_slot, CarrierCount::new(1))
                    .unwrap()
                    .map(ProvisionalBits::into_carriers)
                    .transpose()
                    .unwrap()
            });

            let trim_slot = Arc::clone(&slot);
            let trim_prepared = Arc::clone(&prepared);
            let trim = thread::spawn(move || {
                let start = {
                    let mut prepared = trim_prepared.lock();
                    BlockSlot::start_trim(&trim_slot, &mut prepared, CarrierCount::ZERO)
                };
                match start {
                    Ok(cleanup) => {
                        cleanup.finish().unwrap();
                        true
                    }
                    Err(TrimBlocked::Busy) => false,
                    Err(other) => panic!("unexpected trim result: {other:?}"),
                }
            });

            let carriers = claim.join().unwrap();
            let trimmed = trim.join().unwrap();
            if let Some(carriers) = carriers {
                assert!(!trimmed);
                drop(carriers);
            }

            let active = slot
                .current
                .load()
                .as_ref()
                .map(|incarnation| {
                    incarnation.state.load(Ordering::Acquire) == IncarnationState::Active
                })
                .unwrap_or(false);
            if active {
                let mut prepared = prepared.lock();
                BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO)
                    .unwrap()
                    .finish()
                    .unwrap();
            }

            assert!(slot.current.load().as_ref().is_none());
            assert_eq!(
                *slot.mapping.lock(),
                MappingState::Reserved {
                    reclaim_pending: false
                }
            );
        });
    }

    #[test]
    fn preclaimed_activation_publishes_owned_bits_before_fast_claim() {
        loom::model(|| {
            let geometry = PoolGeometry::new(4096, 8192, 4096).unwrap();
            let slot = Arc::new(BlockSlot::new(0, geometry).unwrap());

            let prepare_slot = Arc::clone(&slot);
            let prepare = thread::spawn(move || {
                let mut prepared = CarrierCount::ZERO;
                let carriers = BlockSlot::prepare_and_claim_if_inactive(
                    &prepare_slot,
                    &mut prepared,
                    CarrierCount::new(1),
                )
                .unwrap()
                .expect("fresh slot should activate")
                .into_carriers()
                .unwrap();
                (prepared, carriers)
            });

            let claim_slot = Arc::clone(&slot);
            let claim = thread::spawn(move || {
                BlockSlot::try_claim(&claim_slot, CarrierCount::new(1))
                    .unwrap()
                    .map(ProvisionalBits::into_carriers)
                    .transpose()
                    .unwrap()
            });

            let (prepared, preclaimed) = prepare.join().unwrap();
            let claimed = claim.join().unwrap();

            assert_eq!(prepared, CarrierCount::new(2));
            assert_eq!(preclaimed.len(), 1);
            assert_eq!(preclaimed[0].id().index, 0);
            if let Some(claimed) = &claimed {
                assert_eq!(claimed.len(), 1);
                assert_eq!(claimed[0].id().index, 1);
            }
            let expected_live = 1 + claimed.as_ref().map_or(0, Vec::len);
            assert_eq!(slot.live_carriers(), expected_live);

            drop(preclaimed);
            drop(claimed);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn exhaustive_claim_retries_after_an_optimistic_collision() {
        loom::model(|| {
            let geometry = PoolGeometry::new(4096, 8192, 4096).unwrap();
            let slot = Arc::new(BlockSlot::new(0, geometry).unwrap());
            let mut prepared = CarrierCount::ZERO;
            slot.prepare(&mut prepared).unwrap();

            let exhaustive_slot = Arc::clone(&slot);
            let exhaustive = thread::spawn(move || {
                BlockSlot::try_claim_exhaustive(&exhaustive_slot, CarrierCount::new(1))
                    .unwrap()
                    .expect("exhaustive claim must find one of two carriers")
                    .into_carriers()
                    .unwrap()
            });
            let optimistic_slot = Arc::clone(&slot);
            let optimistic = thread::spawn(move || {
                BlockSlot::try_claim(&optimistic_slot, CarrierCount::new(1))
                    .unwrap()
                    .map(ProvisionalBits::into_carriers)
                    .transpose()
                    .unwrap()
            });

            let exhaustive = exhaustive.join().unwrap();
            let optimistic = optimistic.join().unwrap();
            if let Some(optimistic) = &optimistic {
                assert_ne!(exhaustive[0].carrier_index(), optimistic[0].carrier_index());
            }
            assert_eq!(
                slot.live_carriers(),
                1 + optimistic.as_ref().map_or(0, Vec::len)
            );

            drop(exhaustive);
            drop(optimistic);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn two_claimants_cannot_own_one_carrier() {
        loom::model(|| {
            let (slot, _) = prepared_slot();

            let first_slot = Arc::clone(&slot);
            let first = thread::spawn(move || {
                BlockSlot::try_claim(&first_slot, CarrierCount::new(1)).unwrap()
            });
            let second_slot = Arc::clone(&slot);
            let second = thread::spawn(move || {
                BlockSlot::try_claim(&second_slot, CarrierCount::new(1)).unwrap()
            });

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            let owned = first.as_ref().map_or(0, |claim| claim.len().get())
                + second.as_ref().map_or(0, |claim| claim.len().get());

            assert_eq!(owned, 1);
            assert_eq!(slot.live_carriers(), 1);
            drop(first);
            drop(second);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn word_run_collision_rolls_back_every_partial_win() {
        loom::model(|| {
            let geometry = PoolGeometry::new(4096, 128 * 4096, 4096).unwrap();
            let slot = Arc::new(BlockSlot::new(0, geometry).unwrap());
            let mut prepared = CarrierCount::ZERO;
            slot.prepare(&mut prepared).unwrap();

            let run_slot = Arc::clone(&slot);
            let run = thread::spawn(move || {
                BlockSlot::try_claim_word_run(&run_slot, 0, 2, 2)
                    .unwrap()
                    .into_provisional()
                    .map(ProvisionalBits::into_carriers)
                    .transpose()
                    .unwrap()
            });
            let tail_slot = Arc::clone(&slot);
            let tail = thread::spawn(move || {
                BlockSlot::try_claim_words(&tail_slot, 1, 1, CarrierCount::new(64))
                    .unwrap()
                    .into_provisional()
                    .map(ProvisionalBits::into_carriers)
                    .transpose()
                    .unwrap()
            });

            let run = run.join().unwrap();
            let tail = tail.join().unwrap();
            match (&run, &tail) {
                (Some(run), None) => {
                    assert_eq!(run.len(), 128);
                    assert_eq!(slot.live_carriers(), 128);
                }
                (None, Some(tail)) => {
                    assert_eq!(tail.len(), 64);
                    assert!(tail.iter().all(|carrier| carrier.carrier_index() >= 64));
                    assert_eq!(slot.live_carriers(), 64);
                }
                _ => panic!("overlapping whole-word claims published an invalid result"),
            }

            drop(run);
            drop(tail);
            assert_eq!(slot.live_carriers(), 0);
        });
    }

    #[test]
    fn concurrent_returns_clear_disjoint_bits_in_one_word() {
        loom::model(|| {
            let geometry = PoolGeometry::new(4096, 8192, 4096).unwrap();
            let slot = Arc::new(BlockSlot::new(0, geometry).unwrap());
            let mut prepared = CarrierCount::ZERO;
            slot.prepare(&mut prepared).unwrap();
            let carriers = BlockSlot::try_claim(&slot, CarrierCount::new(2))
                .unwrap()
                .unwrap()
                .into_carriers()
                .unwrap();
            let mut carriers = carriers.into_iter();
            let first = carriers.next().unwrap();
            let second = carriers.next().unwrap();
            assert!(carriers.next().is_none());

            let first = thread::spawn(move || drop(first));
            let second = thread::spawn(move || drop(second));
            first.join().unwrap();
            second.join().unwrap();

            assert_eq!(slot.live_carriers(), 0);
        });
    }
}