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

//! Multi-block carrier acquisition and stable-range lookup.
//!
//! [`Arena`] publishes immutable registry generations for lock-free optimistic
//! scans and address classification. A miss enters serialized fallback, which
//! exhausts reusable capacity before preparing another block. The arena owns
//! physical topology and claims; admission policy and byte presentation remain
//! in higher layers.

use std::collections::TryReserveError;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering as DiagnosticOrdering};

use super::admission::AdmissionGuard;
use super::block::{
    BlockError, BlockSlot, CarrierAllocation, ProvisionalBits, TrimBlocked, TrimCleanup,
};
use super::geometry::PoolGeometry;
use super::virtual_memory::VirtualMemoryOperation;
use super::{invariant_violation, CarrierCount};
use crate::runtime::sync::sync::atomic::{AtomicUsize, Ordering};
use crate::runtime::sync::sync::{Arc, Mutex};

/// Stable slots and their atomically published lookup index.
pub(super) struct Arena {
    /// Shared block geometry.
    geometry: PoolGeometry,
    /// Maximum bitmap words inspected by one optimistic claim.
    optimistic_scan_words: usize,
    /// Rotating flattened bitmap-word origin.
    scan_origin: AtomicUsize,
    /// Internal scan, growth, and rollback counters.
    diagnostics: Arc<ArenaDiagnostics>,
    /// Lock-free registry publication.
    registry: BlockRegistry,
    /// Serialized slot creation and registry rebuilding.
    state: Mutex<ArenaState>,
    /// Whether test slots retain inaccessible pages around each block.
    #[cfg(test)]
    enable_guard_pages: bool,
}

/// Construction policy for one arena.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct ArenaOptions {
    /// Maximum bitmap words inspected by one optimistic claim.
    optimistic_scan_words: usize,
    /// Whether successful optimistic claims update per-acquisition counters.
    enable_detailed_counters: bool,
    /// Whether test slots retain inaccessible pages around each block.
    #[cfg(test)]
    enable_guard_pages: bool,
}

impl ArenaOptions {
    /// Creates allocator options with an explicit diagnostic cost level.
    pub(super) fn new(optimistic_scan_words: usize, enable_detailed_counters: bool) -> Self {
        Self {
            optimistic_scan_words,
            enable_detailed_counters,
            #[cfg(test)]
            enable_guard_pages: false,
        }
    }

    /// Returns the maximum bitmap words inspected optimistically.
    pub(super) fn optimistic_scan_words(self) -> usize {
        self.optimistic_scan_words
    }

    /// Enables inaccessible pages around each test block range.
    #[cfg(test)]
    pub(super) fn enable_guard_pages(mut self) -> Self {
        self.enable_guard_pages = true;
        self
    }
}

impl Arena {
    /// Creates an empty arena with fixed geometry and allocator policy.
    pub(super) fn new(geometry: PoolGeometry, options: ArenaOptions) -> Result<Self, ArenaError> {
        let optimistic_scan_words = options.optimistic_scan_words;
        if optimistic_scan_words == 0 {
            return Err(ArenaError::InvalidScanBudget);
        }
        Ok(Self {
            geometry,
            optimistic_scan_words,
            scan_origin: AtomicUsize::new(0),
            diagnostics: Arc::new(ArenaDiagnostics::new(options.enable_detailed_counters)),
            registry: BlockRegistry::new(),
            state: Mutex::new(ArenaState {
                slots: Vec::new(),
                next_slot: Some(0),
            }),
            #[cfg(test)]
            enable_guard_pages: options.enable_guard_pages,
        })
    }

    /// Reserves and publishes one inactive stable block slot.
    ///
    /// Failure leaves the registry and slot identifier unchanged.
    #[cfg(test)]
    pub(super) fn reserve_slot(&self) -> Result<Arc<BlockSlot>, ArenaError> {
        let mut state = self.state.lock();
        self.reserve_slot_locked(&mut state)
    }

    /// Reserves and publishes one slot while holding arena serialization.
    ///
    /// The mutable state reference proves exclusive access without reacquiring
    /// the mutex. Failure leaves the state and registry generation unchanged.
    fn reserve_slot_locked(&self, state: &mut ArenaState) -> Result<Arc<BlockSlot>, ArenaError> {
        let slot_id = state.next_slot.ok_or(ArenaError::SlotIdExhausted)?;

        state.slots.try_reserve(1)?;
        let slot = Arc::new(self.new_slot(slot_id)?);
        let generation = RegistryGeneration::try_with_slot(&state.slots, &slot)?;

        state.slots.push(Arc::clone(&slot));
        state.next_slot = slot_id.checked_add(1);
        self.registry.publish(generation);
        self.diagnostics.record_block_range_reserved();
        Ok(slot)
    }

    /// Reserves one block using the configured test storage layout.
    fn new_slot(&self, slot_id: u32) -> Result<BlockSlot, BlockError> {
        #[cfg(test)]
        if self.enable_guard_pages {
            return BlockSlot::new_guarded(slot_id, self.geometry);
        }
        BlockSlot::new(slot_id, self.geometry)
    }

    /// Classifies a complete nonempty range within one stable block slot.
    ///
    /// Integer addresses are used only for comparison. This method does not
    /// construct a pointer or authorize access to the classified range.
    pub(super) fn classify_range(&self, start: usize, len: usize) -> Option<ClassifiedRange> {
        self.registry.load().classify_range(start, len)
    }

    /// Selects one block observed active and free.
    ///
    /// Selection is a lock-free hint. A claim may race this scan, so the
    /// caller must use [`BlockSlot::start_trim`] to recheck the lifecycle,
    /// bitmap, and prepared-capacity floor under admission serialization.
    pub(super) fn select_trim_candidate(&self) -> Option<Arc<BlockSlot>> {
        let generation = self.registry_generation();
        let mut scanned = 0;
        let candidate = generation.slots_in_claim_order().iter().find_map(|slot| {
            scanned += 1;
            slot.appears_free().then(|| Arc::clone(slot))
        });
        self.diagnostics.record_trim_slots_scanned(scanned);
        candidate
    }

    /// Starts cleanup for one free block without crossing `floor`.
    ///
    /// Selection remains a hint. Each candidate is rechecked through the
    /// claim-trim gate while admission owns prepared-capacity serialization.
    pub(super) fn start_trim(
        &self,
        admission: &mut AdmissionGuard<'_>,
        floor: CarrierCount,
    ) -> ArenaTrim {
        let generation = self.registry_generation();
        let mut scanned = 0;
        let mut result = ArenaTrim::Blocked;
        for slot in generation.slots_in_claim_order() {
            scanned += 1;
            if !slot.appears_free() {
                continue;
            }
            match BlockSlot::start_trim(slot, admission.prepared_capacity_mut(), floor) {
                Ok(cleanup) => {
                    result = ArenaTrim::Started(cleanup);
                    break;
                }
                Err(TrimBlocked::FloorViolation) => break,
                Err(TrimBlocked::NotPrepared | TrimBlocked::Busy | TrimBlocked::CleanupPending) => {
                }
            }
        }
        self.diagnostics.record_trim_slots_scanned(scanned);
        result
    }

    /// Retries pending cleanup in the current registry generation.
    ///
    /// Returns `true` only when every slot reports no remaining cleanup work.
    pub(super) fn retry_cleanup(&self) -> bool {
        let generation = self.registry_generation();
        let mut complete = true;
        for slot in generation.slots_in_claim_order() {
            match slot.retry_cleanup() {
                Ok(false) => {}
                Ok(true) => self.diagnostics.record_cleanup_retry(),
                Err(error) => {
                    self.diagnostics.record_cleanup_retry();
                    self.diagnostics.record_cleanup_failure();
                    tracing::warn!(
                        target: crate::telemetry::TARGET_MEMORY,
                        slot_id = slot.id(),
                        error = ?error,
                        "buffer-pool mapping cleanup retry failed"
                    );
                    complete = false;
                }
            }
        }
        complete
    }

    /// Records one block whose prepared capacity and backing were reclaimed.
    pub(super) fn record_block_reclaimed(&self) {
        self.diagnostics.record_block_reclaimed();
    }

    /// Returns one private arena diagnostic sample.
    pub(super) fn diagnostics(&self) -> ArenaDiagnosticSnapshot {
        self.diagnostics.snapshot()
    }

    /// Reconstructs lifecycle state across the current registry generation.
    ///
    /// Concurrent claims and returns may span individual slot samples.
    /// Operational diagnostics therefore use this as a best-effort view;
    /// externally quiescent tests may use it for exact reconciliation.
    pub(super) fn sample_lifecycle(&self) -> ArenaLifecycleSample {
        let generation = self.registry_generation();
        let mut sample = ArenaLifecycleSample::default();
        for slot in generation.slots_in_claim_order() {
            let block = slot.sample_lifecycle();
            sample.prepared_capacity = sample
                .prepared_capacity
                .checked_add(block.prepared_capacity)
                .unwrap_or_else(|| invariant_violation("arena prepared diagnostic overflow"));
            sample.live_carriers = sample
                .live_carriers
                .checked_add(block.live_carriers)
                .unwrap_or_else(|| invariant_violation("arena live diagnostic overflow"));
            if block.cleanup_pending {
                sample.cleanup_pending_blocks = sample
                    .cleanup_pending_blocks
                    .checked_add(1)
                    .unwrap_or_else(|| invariant_violation("arena cleanup diagnostic overflow"));
            }
        }
        sample
    }

    /// Returns whether one prepared slot contains a complete free word run.
    ///
    /// The caller must externally quiesce claims and returns. Unlike the
    /// allocator's cursor-bounded and serialized searches, this test/fuzz
    /// oracle examines every current slot and performs no bitmap mutation.
    #[cfg(any(test, s3_tm_fuzz))]
    pub(super) fn has_free_word_run_quiescent(&self, word_count: usize) -> bool {
        let generation = self.registry_generation();
        generation
            .slots_in_claim_order()
            .iter()
            .any(|slot| slot.has_free_word_run_quiescent(word_count))
    }

    /// Prepares capacity through `target` under admission serialization.
    ///
    /// Whole-block preparation may raise prepared capacity above `target`.
    /// Stable slots remain in the arena after trim. This operation scans those
    /// slots, skips capacity that is already prepared, and revives inactive or
    /// recovery-pending slots before reserving another virtual range. A failure
    /// retains capacity prepared by earlier iterations but publishes no
    /// admission grant.
    pub(super) fn prepare_to(
        &self,
        admission: &mut AdmissionGuard<'_>,
        target: CarrierCount,
    ) -> Result<(), ArenaError> {
        if admission.prepared_capacity() >= target {
            return Ok(());
        }

        let mut state = self.state.lock();
        for slot in &state.slots {
            if admission.prepared_capacity() >= target {
                return Ok(());
            }
            match slot.prepare(admission.prepared_capacity_mut()) {
                Ok(()) => self.diagnostics.record_block_prepared(),
                Err(BlockError::AlreadyPrepared) => {}
                Err(error) => return Err(error.into()),
            }
        }

        while admission.prepared_capacity() < target {
            let slot = self.reserve_slot_locked(&mut state)?;
            slot.prepare(admission.prepared_capacity_mut())?;
            self.diagnostics.record_block_prepared();
        }
        Ok(())
    }

    /// Claims a complete or partial batch within the optimistic scan budget.
    ///
    /// The returned batch retains every gate-passed bit. A complete batch may
    /// be converted to carrier owners. A partial batch remains suitable for
    /// serialized fallback and returns its bits if dropped.
    pub(super) fn claim_optimistic(
        &self,
        required: CarrierCount,
    ) -> Result<ClaimBatch, ArenaError> {
        if required == CarrierCount::ZERO {
            return Err(ArenaError::InvalidClaimCount);
        }

        let generation = self.registry_generation();
        let slots = generation.slots_in_claim_order();
        let words_per_slot = self.geometry.bitmap_words();
        let total_positions =
            slots
                .len()
                .checked_mul(words_per_slot)
                .ok_or(ArenaError::ScanSpaceOverflow {
                    slots: slots.len(),
                    words_per_slot,
                })?;
        let mut batch = ClaimBatch::new(required, Arc::clone(&self.diagnostics));
        if total_positions == 0 {
            self.diagnostics.record_optimistic_scan(0, true);
            return Ok(batch);
        }

        let budget = self.optimistic_scan_words.min(total_positions);
        // Partial scans advance by one charged window. A full-space window
        // would wrap to the same origin, so rotate it by one word instead.
        let origin_stride = if budget == total_positions { 1 } else { budget };
        let origin = self.scan_origin.fetch_add(origin_stride, Ordering::Relaxed) % total_positions;
        if let Some(word_count) = self.contiguous_word_count(required) {
            if word_count > budget {
                self.diagnostics.record_optimistic_scan(0, true);
                return Ok(batch);
            }
            while batch.inspected_words < budget && !batch.is_complete() {
                let position = wrapped_position(origin, batch.inspected_words, total_positions);
                let slot_index = position / words_per_slot;
                let start_word = position % words_per_slot;
                let word_limit = (words_per_slot - start_word).min(budget - batch.inspected_words);
                let claim = BlockSlot::try_claim_word_run(
                    &slots[slot_index],
                    start_word,
                    word_limit,
                    word_count,
                )?;
                let inspected = claim.inspected_words();
                if inspected == 0 || inspected > word_limit {
                    invariant_violation("contiguous block claim reported invalid scan work");
                }
                batch.inspected_words += inspected;
                if let Some(provisional) = claim.into_provisional() {
                    batch.push(provisional)?;
                }
            }
            self.diagnostics
                .record_optimistic_scan(batch.inspected_words, !batch.is_complete());
            return Ok(batch);
        }

        while batch.inspected_words < budget && !batch.is_complete() {
            let position = wrapped_position(origin, batch.inspected_words, total_positions);
            let slot_index = position / words_per_slot;
            let start_word = position % words_per_slot;
            let word_limit = (words_per_slot - start_word).min(budget - batch.inspected_words);
            let claim = BlockSlot::try_claim_words(
                &slots[slot_index],
                start_word,
                word_limit,
                batch.remaining(),
            )?;
            let inspected = claim.inspected_words();
            if inspected == 0 || inspected > word_limit {
                invariant_violation("bounded block claim reported invalid scan work");
            }
            batch.inspected_words += inspected;
            if let Some(provisional) = claim.into_provisional() {
                batch.push(provisional)?;
            }
        }
        self.diagnostics
            .record_optimistic_scan(batch.inspected_words, !batch.is_complete());
        Ok(batch)
    }

    /// Completes a partial batch through exhaustive reuse and private growth.
    ///
    /// `admission` proves that the caller owns the prepared-capacity floor.
    /// This method holds arena serialization through the full registry recheck
    /// and every preparation. Existing inactive slots are reused before
    /// another stable range is reserved.
    pub(super) fn complete_claim_serialized(
        &self,
        admission: &mut AdmissionGuard<'_>,
        batch: &mut ClaimBatch,
    ) -> Result<(), ArenaError> {
        if batch.is_complete() {
            return Ok(());
        }
        self.diagnostics.record_serialized_fallback();
        let mut tracker = SerializedFallbackTracker::new(self.diagnostics.as_ref());

        let mut state = self.state.lock();
        if batch.claimed() == CarrierCount::ZERO {
            if let Some(word_count) = self.contiguous_word_count(batch.required) {
                let slot_count = state.slots.len();
                if slot_count != 0 {
                    let words_per_slot = self.geometry.bitmap_words();
                    let start_slot =
                        (self.scan_origin.load(Ordering::Relaxed) / words_per_slot) % slot_count;
                    for offset in 0..slot_count {
                        let slot = &state.slots[(start_slot + offset) % slot_count];
                        tracker.record_slot_inspected();
                        let claim =
                            BlockSlot::try_claim_word_run(slot, 0, words_per_slot, word_count)?;
                        if let Some(provisional) = claim.into_provisional() {
                            batch.push(provisional)?;
                            return Ok(());
                        }
                    }
                }
            }
        }

        for slot in &state.slots {
            if batch.is_complete() {
                return Ok(());
            }
            tracker.record_slot_inspected();
            if let Some(provisional) = BlockSlot::try_claim_exhaustive(slot, batch.remaining())? {
                batch.push(provisional)?;
            }
        }

        for slot in &state.slots {
            if batch.is_complete() {
                return Ok(());
            }
            tracker.record_slot_inspected();
            let count = std::cmp::min(batch.remaining(), slot.carrier_count());
            if let Some(provisional) = BlockSlot::prepare_and_claim_if_inactive(
                slot,
                admission.prepared_capacity_mut(),
                count,
            )? {
                self.diagnostics.record_block_prepared();
                batch.push(provisional)?;
            }
        }

        while !batch.is_complete() {
            let slot = self.reserve_slot_locked(&mut state)?;
            let count = std::cmp::min(batch.remaining(), slot.carrier_count());
            let provisional = BlockSlot::prepare_and_claim_if_inactive(
                &slot,
                admission.prepared_capacity_mut(),
                count,
            )?
            .unwrap_or_else(|| {
                invariant_violation("new arena slot was not reusable for private growth")
            });
            self.diagnostics.record_block_prepared();
            batch.push(provisional)?;
        }
        Ok(())
    }

    /// Returns the whole-word run required for a preferred contiguous claim.
    fn contiguous_word_count(&self, count: CarrierCount) -> Option<usize> {
        if count == CarrierCount::ZERO
            || count > self.geometry.carriers_per_block()
            || !count.get().is_multiple_of(u64::BITS as usize)
        {
            return None;
        }
        Some(count.get() / u64::BITS as usize)
    }

    /// Protects the current immutable registry generation.
    fn registry_generation(&self) -> RegistryGenerationGuard {
        self.registry.load()
    }
}

/// Failure to configure, claim, reserve, or publish arena storage.
#[derive(Debug)]
pub(super) enum ArenaError {
    /// A block operation failed.
    Block(BlockError),
    /// Registry metadata could not be allocated.
    Allocation(TryReserveError),
    /// The optimistic bitmap-word budget is zero.
    InvalidScanBudget,
    /// A batch claim requested no carriers.
    InvalidClaimCount,
    /// The flattened registry scan space cannot be represented.
    ScanSpaceOverflow {
        /// Slots in the registry generation.
        slots: usize,
        /// Bitmap words in each slot.
        words_per_slot: usize,
    },
    /// Conversion was requested before the complete batch was owned.
    IncompleteClaim {
        /// Carriers required by the batch.
        required: usize,
        /// Carriers provisionally owned by the batch.
        claimed: usize,
    },
    /// No stable block identifier remains.
    SlotIdExhausted,
    /// The registry cannot represent another slot.
    RegistryCapacityOverflow,
    /// A stable virtual range overflows address representation.
    AddressOverflow {
        /// Slot containing the invalid range.
        slot_id: u32,
        /// First byte of the range.
        start: usize,
        /// Reserved range length.
        len: usize,
    },
    /// Two stable virtual ranges overlap.
    AddressOverlap {
        /// First overlapping range start.
        first_start: usize,
        /// First overlapping range end.
        first_end: usize,
        /// Second overlapping range start.
        second_start: usize,
        /// Second overlapping range end.
        second_end: usize,
    },
}

impl ArenaError {
    /// Returns whether this failure left an inactive slot needing recovery.
    pub(super) fn cleanup_required(&self) -> bool {
        matches!(
            self,
            Self::Block(BlockError::VirtualMemory(error))
                if error.operation() == VirtualMemoryOperation::Prepare
        )
    }
}

impl fmt::Display for ArenaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Block(error) => error.fmt(f),
            Self::Allocation(error) => write!(f, "arena metadata allocation failed: {error}"),
            Self::InvalidScanBudget => f.write_str("arena optimistic scan budget must be nonzero"),
            Self::InvalidClaimCount => f.write_str("an arena claim must request carriers"),
            Self::ScanSpaceOverflow {
                slots,
                words_per_slot,
            } => write!(
                f,
                "arena scan space {slots} slots by {words_per_slot} words overflows"
            ),
            Self::IncompleteClaim { required, claimed } => write!(
                f,
                "cannot finish incomplete arena claim: required {required}, claimed {claimed}"
            ),
            Self::SlotIdExhausted => f.write_str("arena block identifier space is exhausted"),
            Self::RegistryCapacityOverflow => f.write_str("arena registry capacity would overflow"),
            Self::AddressOverflow {
                slot_id,
                start,
                len,
            } => write!(
                f,
                "block slot {slot_id} address range {start:#x}+{len:#x} overflows"
            ),
            Self::AddressOverlap {
                first_start,
                first_end,
                second_start,
                second_end,
            } => write!(
                f,
                "block ranges {first_start:#x}..{first_end:#x} and \
                 {second_start:#x}..{second_end:#x} overlap"
            ),
        }
    }
}

impl std::error::Error for ArenaError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Block(error) => Some(error),
            Self::Allocation(error) => Some(error),
            Self::InvalidScanBudget
            | Self::InvalidClaimCount
            | Self::ScanSpaceOverflow { .. }
            | Self::IncompleteClaim { .. }
            | Self::SlotIdExhausted
            | Self::RegistryCapacityOverflow
            | Self::AddressOverflow { .. }
            | Self::AddressOverlap { .. } => None,
        }
    }
}

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

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

/// Gate-passed carrier bits retained across one arena acquisition.
#[must_use = "dropping a claim batch returns its provisional carrier bits"]
pub(super) struct ClaimBatch {
    /// Carriers required for a complete acquisition.
    required: CarrierCount,
    /// Carriers currently owned by `blocks`.
    claimed: CarrierCount,
    /// Bitmap-word positions charged to the optimistic scan.
    inspected_words: usize,
    /// Per-incarnation provisional ownership.
    blocks: Vec<ProvisionalBits>,
    /// Counters updated if provisional ownership rolls back.
    diagnostics: Arc<ArenaDiagnostics>,
}

impl ClaimBatch {
    /// Creates an empty batch for `required` carriers.
    fn new(required: CarrierCount, diagnostics: Arc<ArenaDiagnostics>) -> Self {
        Self {
            required,
            claimed: CarrierCount::ZERO,
            inspected_words: 0,
            blocks: Vec::new(),
            diagnostics,
        }
    }

    /// Returns the required carrier count.
    #[cfg(test)]
    pub(super) fn required(&self) -> CarrierCount {
        self.required
    }

    /// Returns the provisionally owned carrier count.
    pub(super) fn claimed(&self) -> CarrierCount {
        self.claimed
    }

    /// Returns the carrier count still needed.
    pub(super) fn remaining(&self) -> CarrierCount {
        self.required
            .checked_sub(self.claimed)
            .unwrap_or_else(|| invariant_violation("arena claim exceeds its required count"))
    }

    /// Returns bitmap-word positions charged to the optimistic scan.
    pub(super) fn inspected_words(&self) -> usize {
        self.inspected_words
    }

    /// Returns `true` when the complete requested batch is owned.
    pub(super) fn is_complete(&self) -> bool {
        self.claimed == self.required
    }

    /// Retains another block's provisional ownership.
    fn push(&mut self, provisional: ProvisionalBits) -> Result<(), ArenaError> {
        let next_claimed = self
            .claimed
            .checked_add(provisional.len())
            .unwrap_or_else(|| invariant_violation("arena claim count overflowed"));
        if next_claimed > self.required {
            invariant_violation("arena claim won more carriers than requested");
        }

        if let Err(error) = self.blocks.try_reserve(1) {
            self.diagnostics
                .record_rolled_back_carriers(provisional.len().get());
            return Err(error.into());
        }
        self.blocks.push(provisional);
        self.claimed = next_claimed;
        Ok(())
    }

    /// Converts one complete provisional batch into carrier owners.
    ///
    /// An incomplete batch returns an error and releases its provisional bits.
    /// Allocation failure drops converted owners and remaining provisional
    /// ownership, returning every bit exactly once.
    pub(super) fn finish(mut self) -> Result<Vec<CarrierAllocation>, ArenaError> {
        if !self.is_complete() {
            return Err(ArenaError::IncompleteClaim {
                required: self.required.get(),
                claimed: self.claimed.get(),
            });
        }

        let mut carriers = Vec::new();
        carriers.try_reserve_exact(self.required.get())?;
        for provisional in self.blocks.drain(..) {
            let mut block = provisional.into_carriers()?;
            carriers.append(&mut block);
        }
        if carriers.len() != self.required.get() {
            invariant_violation("complete arena claim converted the wrong carrier count");
        }
        self.claimed = CarrierCount::ZERO;
        Ok(carriers)
    }
}

impl Drop for ClaimBatch {
    fn drop(&mut self) {
        self.diagnostics
            .record_rolled_back_carriers(self.claimed.get());
    }
}

/// Cumulative allocator-work observations that never authorize allocator decisions.
///
/// Basic counters update only on misses, fallback, lifecycle work, rollback, or
/// failure. Detailed counters add relaxed atomic updates to every optimistic
/// acquisition when enabled. Counters saturate at `u64::MAX`; fields loaded in
/// one snapshot are individually valid but need not describe one atomic instant.
struct ArenaDiagnostics {
    /// Optimistic scans that returned incomplete ownership.
    optimistic_misses: AtomicU64,
    /// Partial batches that entered serialized fallback.
    serialized_fallbacks: AtomicU64,
    /// Existing slots inspected while serialized fallback searched for reuse.
    serialized_slots_inspected: AtomicU64,
    /// Successful whole-block preparation operations in fallback.
    blocks_prepared: AtomicU64,
    /// Stable virtual ranges added to the registry.
    block_ranges_reserved: AtomicU64,
    /// Carriers returned because a claim batch ended without publication.
    rolled_back_carriers: AtomicU64,
    /// Slots inspected while selecting trim candidates.
    trim_slots_scanned: AtomicU64,
    /// Blocks removed from prepared capacity and successfully reclaimed.
    blocks_reclaimed: AtomicU64,
    /// Pending mapping-cleanup operations retried.
    cleanup_retries: AtomicU64,
    /// Mapping-cleanup attempts that remain pending.
    cleanup_failures: AtomicU64,
    /// Per-acquisition work counters enabled only for detailed diagnostics.
    detailed: Option<DetailedScanCounters>,
}

/// Work charged to every optimistic acquisition when detailed diagnostics are enabled.
#[derive(Default)]
struct DetailedScanCounters {
    /// Completed optimistic acquisition attempts.
    optimistic_scans: AtomicU64,
    /// Bitmap words charged to completed optimistic scans.
    optimistic_scan_words: AtomicU64,
}

impl ArenaDiagnostics {
    /// Creates counters with optional per-acquisition scan accounting.
    fn new(enable_detailed_counters: bool) -> Self {
        Self {
            optimistic_misses: AtomicU64::new(0),
            serialized_fallbacks: AtomicU64::new(0),
            serialized_slots_inspected: AtomicU64::new(0),
            blocks_prepared: AtomicU64::new(0),
            block_ranges_reserved: AtomicU64::new(0),
            rolled_back_carriers: AtomicU64::new(0),
            trim_slots_scanned: AtomicU64::new(0),
            blocks_reclaimed: AtomicU64::new(0),
            cleanup_retries: AtomicU64::new(0),
            cleanup_failures: AtomicU64::new(0),
            detailed: enable_detailed_counters.then(DetailedScanCounters::default),
        }
    }

    /// Records one completed optimistic scan.
    fn record_optimistic_scan(&self, words: usize, missed: bool) {
        if let Some(detailed) = &self.detailed {
            saturating_add(&detailed.optimistic_scans, 1);
            saturating_add(&detailed.optimistic_scan_words, diagnostic_count(words));
        }
        if missed {
            saturating_add(&self.optimistic_misses, 1);
        }
    }

    /// Records one serialized fallback entry.
    fn record_serialized_fallback(&self) {
        saturating_add(&self.serialized_fallbacks, 1);
    }

    /// Records existing-slot work completed by one serialized fallback.
    fn record_serialized_slots_inspected(&self, slots: usize) {
        saturating_add(&self.serialized_slots_inspected, diagnostic_count(slots));
    }

    /// Records one successful block preparation.
    fn record_block_prepared(&self) {
        saturating_add(&self.blocks_prepared, 1);
    }

    /// Records one stable virtual-range reservation.
    fn record_block_range_reserved(&self) {
        saturating_add(&self.block_ranges_reserved, 1);
    }

    /// Records carriers returned when a claim batch ends without publication.
    fn record_rolled_back_carriers(&self, carriers: usize) {
        saturating_add(&self.rolled_back_carriers, diagnostic_count(carriers));
    }

    /// Records work spent selecting one trim candidate.
    fn record_trim_slots_scanned(&self, slots: usize) {
        saturating_add(&self.trim_slots_scanned, diagnostic_count(slots));
    }

    /// Records one successfully reclaimed block.
    fn record_block_reclaimed(&self) {
        saturating_add(&self.blocks_reclaimed, 1);
    }

    /// Records one pending cleanup operation attempted by recovery.
    fn record_cleanup_retry(&self) {
        saturating_add(&self.cleanup_retries, 1);
    }

    /// Records one cleanup attempt that remains pending.
    fn record_cleanup_failure(&self) {
        saturating_add(&self.cleanup_failures, 1);
    }

    /// Loads one relaxed diagnostic sample.
    fn snapshot(&self) -> ArenaDiagnosticSnapshot {
        ArenaDiagnosticSnapshot {
            optimistic_misses: self.optimistic_misses.load(DiagnosticOrdering::Relaxed),
            serialized_fallbacks: self.serialized_fallbacks.load(DiagnosticOrdering::Relaxed),
            serialized_slots_inspected: self
                .serialized_slots_inspected
                .load(DiagnosticOrdering::Relaxed),
            blocks_prepared: self.blocks_prepared.load(DiagnosticOrdering::Relaxed),
            block_ranges_reserved: self.block_ranges_reserved.load(DiagnosticOrdering::Relaxed),
            rolled_back_carriers: self.rolled_back_carriers.load(DiagnosticOrdering::Relaxed),
            trim_slots_scanned: self.trim_slots_scanned.load(DiagnosticOrdering::Relaxed),
            blocks_reclaimed: self.blocks_reclaimed.load(DiagnosticOrdering::Relaxed),
            cleanup_retries: self.cleanup_retries.load(DiagnosticOrdering::Relaxed),
            cleanup_failures: self.cleanup_failures.load(DiagnosticOrdering::Relaxed),
            detailed: self.detailed.as_ref().map(DetailedScanCounters::snapshot),
        }
    }
}

impl DetailedScanCounters {
    /// Loads one relaxed per-acquisition work sample.
    fn snapshot(&self) -> DetailedScanSnapshot {
        DetailedScanSnapshot {
            optimistic_scans: self.optimistic_scans.load(DiagnosticOrdering::Relaxed),
            optimistic_scan_words: self.optimistic_scan_words.load(DiagnosticOrdering::Relaxed),
        }
    }
}

/// Private snapshot of arena work and fallback behavior.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct ArenaDiagnosticSnapshot {
    /// Optimistic scans that returned incomplete ownership.
    pub(super) optimistic_misses: u64,
    /// Partial batches that entered serialized fallback.
    pub(super) serialized_fallbacks: u64,
    /// Existing slots inspected while serialized fallback searched for reuse.
    pub(super) serialized_slots_inspected: u64,
    /// Successful whole-block preparation operations in fallback.
    pub(super) blocks_prepared: u64,
    /// Stable virtual ranges added to the registry.
    pub(super) block_ranges_reserved: u64,
    /// Carriers returned because a claim batch ended without publication.
    pub(super) rolled_back_carriers: u64,
    /// Slots inspected while selecting trim candidates.
    pub(super) trim_slots_scanned: u64,
    /// Blocks removed from prepared capacity and successfully reclaimed.
    pub(super) blocks_reclaimed: u64,
    /// Pending mapping-cleanup operations retried.
    pub(super) cleanup_retries: u64,
    /// Mapping-cleanup attempts that remain pending.
    pub(super) cleanup_failures: u64,
    /// Per-acquisition work omitted unless detailed diagnostics were enabled.
    pub(super) detailed: Option<DetailedScanSnapshot>,
}

/// Per-acquisition allocator work collected only in detailed diagnostic mode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct DetailedScanSnapshot {
    /// Completed optimistic acquisition attempts.
    pub(super) optimistic_scans: u64,
    /// Bitmap words charged to completed optimistic scans.
    pub(super) optimistic_scan_words: u64,
}

/// Publishes aggregate serialized work on every completion or error path.
struct SerializedFallbackTracker<'a> {
    diagnostics: &'a ArenaDiagnostics,
    slots_inspected: usize,
}

impl<'a> SerializedFallbackTracker<'a> {
    /// Starts one fallback work sample.
    fn new(diagnostics: &'a ArenaDiagnostics) -> SerializedFallbackTracker<'a> {
        Self {
            diagnostics,
            slots_inspected: 0,
        }
    }

    /// Records one existing slot visited while fallback searches for reuse.
    fn record_slot_inspected(&mut self) {
        self.slots_inspected = self
            .slots_inspected
            .checked_add(1)
            .unwrap_or_else(|| invariant_violation("serialized slot count overflowed"));
    }
}

impl Drop for SerializedFallbackTracker<'_> {
    fn drop(&mut self) {
        self.diagnostics
            .record_serialized_slots_inspected(self.slots_inspected);
    }
}

/// Lifecycle state reconstructed across one arena registry generation.
///
/// Individual block samples need not represent one atomic instant while the
/// pool is active.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(super) struct ArenaLifecycleSample {
    /// Capacity represented by prepared active incarnations.
    pub(super) prepared_capacity: CarrierCount,
    /// Valid bitmap bits owned by claims or carrier guards.
    pub(super) live_carriers: CarrierCount,
    /// Slots blocked by trim or mapping recovery.
    pub(super) cleanup_pending_blocks: usize,
}

/// Result of scanning the registry for one trim candidate.
pub(super) enum ArenaTrim {
    /// One block passed the claim-trim gate and owns cleanup authority.
    Started(TrimCleanup),
    /// No block could be removed without waiting for state to change.
    Blocked,
}

/// Adds a diagnostic value without wrapping.
fn saturating_add(counter: &AtomicU64, value: u64) {
    if value == 0 {
        return;
    }
    // TODO(msrv): `fetch_update` is deprecated from Rust 1.99 in favour of `try_update`,
    // which is stable from 1.95. Switch to `try_update` once the MSRV is 1.95 or later.
    #[allow(deprecated)]
    let _ = counter.fetch_update(
        DiagnosticOrdering::Relaxed,
        DiagnosticOrdering::Relaxed,
        |current| Some(current.saturating_add(value)),
    );
}

/// Converts a platform-sized work count into a saturating diagnostic count.
fn diagnostic_count(value: usize) -> u64 {
    u64::try_from(value).unwrap_or(u64::MAX)
}

/// Adds a bounded offset to an origin and wraps at `len` without overflow.
fn wrapped_position(origin: usize, offset: usize, len: usize) -> usize {
    let tail = len - origin;
    if offset < tail {
        origin + offset
    } else {
        offset - tail
    }
}

/// Slot state protected by arena serialization.
struct ArenaState {
    /// Slots in stable claim order.
    slots: Vec<Arc<BlockSlot>>,
    /// Identifier assigned to the next slot, or `None` after exhaustion.
    next_slot: Option<u32>,
}

/// Atomic publication for one coherent registry generation.
struct BlockRegistry {
    current: registry_cell::RegistryCell,
}

impl BlockRegistry {
    /// Creates a registry containing no slots.
    fn new() -> Self {
        Self {
            current: registry_cell::RegistryCell::new(Arc::new(RegistryGeneration::empty())),
        }
    }

    /// Protects the current registry generation.
    fn load(&self) -> RegistryGenerationGuard {
        RegistryGenerationGuard {
            inner: self.current.load(),
        }
    }

    /// Publishes a complete registry generation.
    fn publish(&self, generation: RegistryGeneration) {
        self.current.store(Arc::new(generation));
    }
}

/// Protected access to one immutable registry generation.
struct RegistryGenerationGuard {
    inner: registry_cell::RegistryCellGuard,
}

impl RegistryGenerationGuard {
    /// Returns slots in stable physical-claim order.
    fn slots_in_claim_order(&self) -> &[Arc<BlockSlot>] {
        &self.inner.as_ref().slots_in_claim_order
    }

    /// Classifies a complete nonempty range within one slot.
    fn classify_range(&self, start: usize, len: usize) -> Option<ClassifiedRange> {
        self.inner.as_ref().classify_range(start, len)
    }
}

/// Immutable claim and address indexes published as one generation.
struct RegistryGeneration {
    /// Stable scan order for physical acquisition.
    slots_in_claim_order: Box<[Arc<BlockSlot>]>,
    /// Non-overlapping virtual ranges sorted by address.
    address_ranges: Box<[AddressRange]>,
}

impl RegistryGeneration {
    /// Creates an empty registry generation.
    fn empty() -> Self {
        Self {
            slots_in_claim_order: Box::default(),
            address_ranges: Box::default(),
        }
    }

    /// Builds a generation containing `slots` followed by `slot`.
    fn try_with_slot(slots: &[Arc<BlockSlot>], slot: &Arc<BlockSlot>) -> Result<Self, ArenaError> {
        let new_len = slots
            .len()
            .checked_add(1)
            .ok_or(ArenaError::RegistryCapacityOverflow)?;

        let mut slots_in_claim_order = Vec::new();
        slots_in_claim_order.try_reserve_exact(new_len)?;
        slots_in_claim_order.extend(slots.iter().cloned());
        slots_in_claim_order.push(Arc::clone(slot));

        let mut address_ranges = Vec::new();
        address_ranges.try_reserve_exact(new_len)?;
        for (slot_index, slot) in slots_in_claim_order.iter().enumerate() {
            address_ranges.push(AddressRange::for_slot(slot, slot_index)?);
        }
        address_ranges.sort_unstable_by_key(|range| range.start);
        validate_address_ranges(&address_ranges)?;

        Ok(Self {
            slots_in_claim_order: slots_in_claim_order.into_boxed_slice(),
            address_ranges: address_ranges.into_boxed_slice(),
        })
    }

    /// Classifies a complete nonempty range within one slot.
    fn classify_range(&self, start: usize, len: usize) -> Option<ClassifiedRange> {
        if len == 0 {
            return None;
        }
        let end = start.checked_add(len)?;
        let candidate = self
            .address_ranges
            .partition_point(|range| range.start <= start)
            .checked_sub(1)?;
        let range = self.address_ranges.get(candidate)?;
        if end > range.end {
            return None;
        }
        let slot = Arc::clone(
            self.slots_in_claim_order
                .get(range.slot_index)
                .unwrap_or_else(|| invariant_violation("registry range has an invalid slot index")),
        );
        Some(ClassifiedRange {
            slot,
            offset: start - range.start,
        })
    }
}

/// One stable virtual range in the sorted address index.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct AddressRange {
    /// First reserved byte.
    start: usize,
    /// Exclusive end of the reservation.
    end: usize,
    /// Index into [`RegistryGeneration::slots_in_claim_order`].
    slot_index: usize,
}

impl AddressRange {
    /// Constructs a checked address range for `slot`.
    fn for_slot(slot: &BlockSlot, slot_index: usize) -> Result<Self, ArenaError> {
        let start = slot.base_address();
        let len = slot.reserved_len();
        let end = start.checked_add(len).ok_or(ArenaError::AddressOverflow {
            slot_id: slot.id(),
            start,
            len,
        })?;
        Ok(Self {
            start,
            end,
            slot_index,
        })
    }

    /// Constructs a checked synthetic range.
    #[cfg(test)]
    fn new(start: usize, len: usize, slot_index: usize) -> Result<Self, ArenaError> {
        let end = start.checked_add(len).ok_or(ArenaError::AddressOverflow {
            slot_id: u32::MAX,
            start,
            len,
        })?;
        Ok(Self {
            start,
            end,
            slot_index,
        })
    }
}

/// Validates sorted, non-overlapping address ranges.
fn validate_address_ranges(ranges: &[AddressRange]) -> Result<(), ArenaError> {
    for pair in ranges.windows(2) {
        let first = pair[0];
        let second = pair[1];
        if first.end > second.start {
            return Err(ArenaError::AddressOverlap {
                first_start: first.start,
                first_end: first.end,
                second_start: second.start,
                second_end: second.end,
            });
        }
    }
    Ok(())
}

/// Classification of an integer range within one stable slot.
pub(super) struct ClassifiedRange {
    /// Slot containing the complete range.
    slot: Arc<BlockSlot>,
    /// Byte offset from the slot base.
    offset: usize,
}

impl ClassifiedRange {
    /// Returns the containing slot.
    pub(super) fn slot(&self) -> &Arc<BlockSlot> {
        &self.slot
    }

    /// Returns the byte offset from the slot base.
    pub(super) fn offset(&self) -> usize {
        self.offset
    }
}

#[cfg(not(all(test, s3_tm_loom)))]
mod registry_cell {
    //! Lock-free production publication for registry generations.

    use arc_swap::{ArcSwap, Guard};

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

    /// Atomic storage for the current registry generation.
    pub(super) struct RegistryCell {
        inner: ArcSwap<RegistryGeneration>,
    }

    impl RegistryCell {
        /// Creates a cell containing `initial`.
        pub(super) fn new(initial: Arc<RegistryGeneration>) -> Self {
            Self {
                inner: ArcSwap::from(initial),
            }
        }

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

        /// Replaces the current generation.
        pub(super) fn store(&self, generation: Arc<RegistryGeneration>) {
            self.inner.store(generation);
        }
    }

    /// Protection for one loaded registry generation.
    pub(super) struct RegistryCellGuard {
        inner: Guard<Arc<RegistryGeneration>>,
    }

    impl RegistryCellGuard {
        /// Returns the protected generation.
        pub(super) fn as_ref(&self) -> &RegistryGeneration {
            &self.inner
        }
    }
}

#[cfg(all(test, s3_tm_loom))]
mod registry_cell {
    //! Loom-instrumented publication with owned registry generations.

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

    /// Loom-instrumented storage for the current registry generation.
    pub(super) struct RegistryCell {
        inner: Mutex<Arc<RegistryGeneration>>,
    }

    impl RegistryCell {
        /// Creates a cell containing `initial`.
        pub(super) fn new(initial: Arc<RegistryGeneration>) -> Self {
            Self {
                inner: Mutex::new(initial),
            }
        }

        /// Loads an owned generation.
        pub(super) fn load(&self) -> RegistryCellGuard {
            RegistryCellGuard {
                inner: Arc::clone(&self.inner.lock()),
            }
        }

        /// Replaces the current generation.
        pub(super) fn store(&self, generation: Arc<RegistryGeneration>) {
            *self.inner.lock() = generation;
        }
    }

    /// Owned protection for one loaded registry generation.
    pub(super) struct RegistryCellGuard {
        inner: Arc<RegistryGeneration>,
    }

    impl RegistryCellGuard {
        /// Returns the protected generation.
        pub(super) fn as_ref(&self) -> &RegistryGeneration {
            &self.inner
        }
    }
}

#[cfg(all(test, not(s3_tm_loom)))]
mod tests {
    use std::sync::Barrier;
    use std::thread;

    use super::super::admission::{AdmissionGuard, AdmissionState, MAX_PACKED_CARRIERS};
    use super::super::block::TrimBlocked;
    use super::super::test_util::operation_sequence::PLACEMENT_PROFILE;
    use super::super::virtual_memory::{page_size, VirtualMemoryOperation};
    use super::super::CarrierCount;
    use super::*;

    fn geometry() -> PoolGeometry {
        geometry_with_carriers(4)
    }

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

    fn test_arena(
        geometry: PoolGeometry,
        optimistic_scan_words: usize,
    ) -> Result<Arena, ArenaError> {
        Arena::new(geometry, ArenaOptions::new(optimistic_scan_words, true))
    }

    fn admission_with_prepared(prepared: CarrierCount) -> Mutex<AdmissionState> {
        let state = Mutex::new(AdmissionState::new(MAX_PACKED_CARRIERS));
        {
            let mut admission = AdmissionGuard::new(state.lock());
            *admission.prepared_capacity_mut() = prepared;
        }
        state
    }

    fn prepare_slots(arena: &Arena, count: usize) -> Vec<Arc<BlockSlot>> {
        let mut prepared = CarrierCount::ZERO;
        (0..count)
            .map(|_| {
                let slot = arena.reserve_slot().unwrap();
                slot.prepare(&mut prepared).unwrap();
                slot
            })
            .collect()
    }

    fn assert_fully_free(slot: &Arc<BlockSlot>) {
        let all = BlockSlot::try_claim(slot, slot.carrier_count())
            .unwrap()
            .expect("every carrier should be free");
        assert_eq!(all.len(), slot.carrier_count());
        drop(all);
    }

    #[test]
    fn empty_registry_classifies_no_range() {
        let arena = test_arena(geometry(), 4).unwrap();

        assert!(arena.classify_range(1, 1).is_none());
        assert!(arena
            .registry_generation()
            .slots_in_claim_order()
            .is_empty());
    }

    #[test]
    fn slot_reservation_publishes_one_coherent_generation() {
        let arena = test_arena(geometry(), 4).unwrap();
        let first = arena.reserve_slot().unwrap();
        let second = arena.reserve_slot().unwrap();
        let generation = arena.registry_generation();

        assert_eq!(
            generation
                .slots_in_claim_order()
                .iter()
                .map(|slot| slot.id())
                .collect::<Vec<_>>(),
            vec![0, 1]
        );
        assert_eq!(generation.inner.as_ref().address_ranges.len(), 2);
        assert!(generation
            .inner
            .as_ref()
            .address_ranges
            .windows(2)
            .all(|pair| pair[0].end <= pair[1].start));
        assert!(generation
            .slots_in_claim_order()
            .iter()
            .any(|slot| Arc::ptr_eq(slot, &first)));
        assert!(generation
            .slots_in_claim_order()
            .iter()
            .any(|slot| Arc::ptr_eq(slot, &second)));
    }

    #[test]
    fn production_registry_guard_survives_concurrent_publication() {
        let arena = Arc::new(test_arena(geometry(), 4).unwrap());
        let first = arena.reserve_slot().unwrap();
        let old_generation = arena.registry_generation();

        let writer_arena = Arc::clone(&arena);
        let writer = thread::spawn(move || writer_arena.reserve_slot().unwrap());
        let second = writer.join().unwrap();
        let new_generation = arena.registry_generation();

        assert_eq!(old_generation.slots_in_claim_order().len(), 1);
        assert!(Arc::ptr_eq(
            &old_generation.slots_in_claim_order()[0],
            &first
        ));
        assert_eq!(new_generation.slots_in_claim_order().len(), 2);
        assert!(new_generation
            .slots_in_claim_order()
            .iter()
            .any(|slot| Arc::ptr_eq(slot, &first)));
        assert!(new_generation
            .slots_in_claim_order()
            .iter()
            .any(|slot| Arc::ptr_eq(slot, &second)));
    }

    #[test]
    fn classification_requires_one_complete_nonempty_slot_range() {
        let arena = test_arena(geometry(), 4).unwrap();
        let slot = arena.reserve_slot().unwrap();
        let range = slot.address_range().unwrap();

        let complete = arena
            .classify_range(range.start, range.len())
            .expect("complete slot range is classified");
        assert!(Arc::ptr_eq(complete.slot(), &slot));
        assert_eq!(complete.offset(), 0);

        let final_byte = arena
            .classify_range(range.end - 1, 1)
            .expect("final byte is inside the slot");
        assert!(Arc::ptr_eq(final_byte.slot(), &slot));
        assert_eq!(final_byte.offset(), range.len() - 1);

        assert!(arena.classify_range(range.start, 0).is_none());
        assert!(arena.classify_range(range.end - 1, 2).is_none());
        assert!(arena.classify_range(usize::MAX, 2).is_none());
    }

    #[test]
    fn classification_rejects_gaps_and_cross_slot_ranges() {
        let geometry = geometry();
        let slots_in_claim_order = (0..3)
            .map(|slot_id| Arc::new(BlockSlot::new(slot_id, geometry).unwrap()))
            .collect::<Vec<_>>()
            .into_boxed_slice();
        let generation = RegistryGeneration {
            slots_in_claim_order,
            address_ranges: vec![
                AddressRange::new(0x1000, 0x1000, 0).unwrap(),
                AddressRange::new(0x2000, 0x1000, 1).unwrap(),
                AddressRange::new(0x4000, 0x1000, 2).unwrap(),
            ]
            .into_boxed_slice(),
        };

        let second = generation
            .classify_range(0x2000, 1)
            .expect("the second range begins at its lower boundary");
        assert!(Arc::ptr_eq(
            second.slot(),
            &generation.slots_in_claim_order[1]
        ));
        assert_eq!(second.offset(), 0);

        assert!(generation.classify_range(0x3000, 1).is_none());
        assert!(generation.classify_range(0x1fff, 2).is_none());
    }

    #[test]
    fn classification_survives_trimmed_block_backing() {
        let arena = test_arena(geometry(), 4).unwrap();
        let slot = arena.reserve_slot().unwrap();
        let range = slot.address_range().unwrap();
        let mut prepared = CarrierCount::ZERO;
        slot.prepare(&mut prepared).unwrap();

        BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO)
            .unwrap()
            .finish()
            .unwrap();

        assert_eq!(prepared, CarrierCount::ZERO);
        let classified = arena
            .classify_range(range.start, range.len())
            .expect("stable slot remains classified after trim");
        assert!(Arc::ptr_eq(classified.slot(), &slot));
    }

    #[test]
    fn address_validation_accepts_adjacency_and_rejects_overlap() {
        let adjacent = [
            AddressRange::new(0x1000, 0x1000, 0).unwrap(),
            AddressRange::new(0x2000, 0x1000, 1).unwrap(),
        ];
        assert!(validate_address_ranges(&adjacent).is_ok());

        let overlap = [
            AddressRange::new(0x1000, 0x1001, 0).unwrap(),
            AddressRange::new(0x2000, 0x1000, 1).unwrap(),
        ];
        assert!(matches!(
            validate_address_ranges(&overlap),
            Err(ArenaError::AddressOverlap { .. })
        ));
    }

    #[test]
    fn synthetic_address_overflow_is_rejected() {
        assert!(matches!(
            AddressRange::new(usize::MAX, 2, 0),
            Err(ArenaError::AddressOverflow { .. })
        ));
    }

    #[test]
    fn exhausted_slot_ids_leave_the_registry_unchanged() {
        let arena = test_arena(geometry(), 4).unwrap();
        arena.state.lock().next_slot = None;

        assert!(matches!(
            arena.reserve_slot(),
            Err(ArenaError::SlotIdExhausted)
        ));
        assert!(arena
            .registry_generation()
            .slots_in_claim_order()
            .is_empty());
    }

    #[test]
    fn rejects_zero_scan_budget_and_zero_claim_count() {
        assert!(matches!(
            test_arena(geometry(), 0),
            Err(ArenaError::InvalidScanBudget)
        ));

        let arena = test_arena(geometry(), 1).unwrap();
        assert!(matches!(
            arena.claim_optimistic(CarrierCount::ZERO),
            Err(ArenaError::InvalidClaimCount)
        ));
    }

    #[test]
    fn empty_registry_returns_an_empty_partial_batch() {
        let arena = test_arena(geometry(), 2).unwrap();

        let batch = arena.claim_optimistic(CarrierCount::new(2)).unwrap();

        assert_eq!(batch.required(), CarrierCount::new(2));
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        assert_eq!(batch.remaining(), CarrierCount::new(2));
        assert_eq!(batch.inspected_words(), 0);
        assert!(!batch.is_complete());
    }

    #[test]
    fn incomplete_scan_charges_the_exact_budget() {
        let arena = test_arena(geometry_with_carriers(130), 2).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let occupied = BlockSlot::try_claim(&slot, slot.carrier_count())
            .unwrap()
            .unwrap();

        let batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();

        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        assert_eq!(batch.inspected_words(), 2);
        drop(batch);
        drop(occupied);
        assert_fully_free(&slot);
    }

    #[test]
    fn inactive_slots_consume_scan_positions() {
        let arena = test_arena(geometry_with_carriers(1), 1).unwrap();
        let inactive = arena.reserve_slot().unwrap();
        let active = prepare_slots(&arena, 1).pop().unwrap();

        let batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();

        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        assert_eq!(batch.inspected_words(), 1);
        drop(batch);
        assert_fully_free(&active);
        assert!(BlockSlot::try_claim(&inactive, CarrierCount::new(1))
            .unwrap()
            .is_none());
    }

    #[test]
    fn scan_origin_rotates_by_the_charged_budget() {
        let arena = test_arena(geometry_with_carriers(130), 2).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let mut indices = Vec::new();

        for _ in 0..3 {
            let carriers = arena
                .claim_optimistic(CarrierCount::new(1))
                .unwrap()
                .finish()
                .unwrap();
            indices.push(carriers[0].carrier_index());
            drop(carriers);
        }

        assert_eq!(indices, vec![0, 128, 64]);
        assert_fully_free(&slot);
    }

    #[test]
    fn scan_origin_rotates_when_budget_covers_the_scan_space() {
        let arena = test_arena(geometry_with_carriers(130), 3).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let mut indices = Vec::new();

        for _ in 0..3 {
            let carriers = arena
                .claim_optimistic(CarrierCount::new(1))
                .unwrap()
                .finish()
                .unwrap();
            indices.push(carriers[0].carrier_index());
            drop(carriers);
        }

        assert_eq!(indices, vec![0, 64, 128]);
        assert_fully_free(&slot);
    }

    #[test]
    fn placement_profile_matches_arena_whole_word_eligibility() {
        let arena = test_arena(
            geometry_with_carriers(PLACEMENT_PROFILE.block_carriers()),
            1,
        )
        .unwrap();

        for carriers in 0..=PLACEMENT_PROFILE.configured_carriers() + 1 {
            assert_eq!(
                arena
                    .contiguous_word_count(CarrierCount::new(carriers))
                    .is_some(),
                PLACEMENT_PROFILE.is_whole_word_claim(carriers),
                "placement profile drifted at {carriers} carriers"
            );
        }
    }

    #[test]
    fn contiguous_scan_prefers_a_complete_run_over_fragmented_prefix() {
        let arena = test_arena(geometry_with_carriers(192), 3).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let mut occupied = BlockSlot::try_claim(&slot, CarrierCount::new(192))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        drop(occupied.drain(64..192).collect::<Vec<_>>());
        drop(occupied.drain(0..32).collect::<Vec<_>>());

        let carriers = arena
            .claim_optimistic(CarrierCount::new(128))
            .unwrap()
            .finish()
            .unwrap();

        assert_eq!(carriers.first().unwrap().carrier_index(), 64);
        assert_eq!(carriers.last().unwrap().carrier_index(), 191);
        drop(carriers);
        drop(occupied);
        assert_fully_free(&slot);
    }

    #[test]
    fn whole_word_claim_larger_than_budget_skips_impossible_scan() {
        /*
         * A two-word request cannot complete inside a one-word optimistic
         * budget. Preserve the request for serialized run-first fallback
         * without scanning, allocating claim storage, or fragmenting it.
         */
        const WORD_CARRIERS: usize = u64::BITS as usize;

        let arena = test_arena(geometry_with_carriers(WORD_CARRIERS * 2), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let batch = arena
            .claim_optimistic(CarrierCount::new(WORD_CARRIERS * 2))
            .unwrap();
        let diagnostics = arena.diagnostics();
        let detailed = diagnostics
            .detailed
            .expect("test arena must collect detailed scan counters");

        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        assert!(!batch.is_complete());
        assert_eq!(detailed.optimistic_scans, 1);
        assert_eq!(detailed.optimistic_scan_words, 0);
        assert_eq!(diagnostics.optimistic_misses, 1);

        drop(batch);
        assert_fully_free(&slot);
    }

    #[test]
    fn serialized_contiguous_scan_starts_from_the_rotating_cursor() {
        let arena = test_arena(geometry_with_carriers(192), 1).unwrap();
        let slots = prepare_slots(&arena, 2);
        let mut occupied = BlockSlot::try_claim(&slots[0], CarrierCount::new(192))
            .unwrap()
            .unwrap()
            .into_carriers()
            .unwrap();
        drop(occupied.drain(128..192).collect::<Vec<_>>());
        drop(occupied.drain(0..64).collect::<Vec<_>>());
        arena.scan_origin.store(2, Ordering::Relaxed);

        let mut batch = arena.claim_optimistic(CarrierCount::new(128)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        let admission = admission_with_prepared(CarrierCount::new(384));
        arena
            .complete_claim_serialized(&mut AdmissionGuard::new(admission.lock()), &mut batch)
            .unwrap();
        let carriers = batch.finish().unwrap();

        assert!(carriers
            .iter()
            .all(|carrier| carrier.slot_id() == slots[1].id()));
        assert_eq!(carriers.first().unwrap().carrier_index(), 0);
        assert_eq!(carriers.last().unwrap().carrier_index(), 127);
        drop(carriers);
        drop(occupied);
        assert_fully_free(&slots[0]);
        assert_fully_free(&slots[1]);
    }

    #[test]
    fn contiguous_miss_preserves_fragmented_fallback() {
        let arena = test_arena(geometry_with_carriers(192), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        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 mut batch = arena.claim_optimistic(CarrierCount::new(128)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        let admission = admission_with_prepared(CarrierCount::new(192));
        arena
            .complete_claim_serialized(&mut AdmissionGuard::new(admission.lock()), &mut batch)
            .unwrap();
        let carriers = batch.finish().unwrap();

        assert_eq!(carriers.len(), 128);
        assert_eq!(carriers.first().unwrap().carrier_index(), 0);
        assert_eq!(carriers.last().unwrap().carrier_index(), 191);
        drop(carriers);
        drop(occupied);
        assert_fully_free(&slot);
    }

    #[test]
    fn scan_wraps_across_slot_and_bitmap_boundaries() {
        let arena = test_arena(geometry_with_carriers(65), 3).unwrap();
        let slots = prepare_slots(&arena, 2);
        arena.scan_origin.store(3, Ordering::Relaxed);

        let batch = arena.claim_optimistic(CarrierCount::new(66)).unwrap();

        assert!(batch.is_complete());
        assert_eq!(batch.inspected_words(), 3);
        let carriers = batch.finish().unwrap();
        assert_eq!(
            (carriers[0].slot_id(), carriers[0].carrier_index()),
            (slots[1].id(), 64)
        );
        assert!(carriers[1..]
            .iter()
            .all(|carrier| carrier.slot_id() == slots[0].id()));
        assert_eq!(carriers[1].carrier_index(), 0);
        assert_eq!(carriers.last().unwrap().carrier_index(), 64);
        drop(carriers);
        assert_fully_free(&slots[0]);
        assert_fully_free(&slots[1]);
    }

    #[test]
    fn one_batch_accumulates_carriers_across_blocks() {
        let arena = test_arena(geometry_with_carriers(2), 2).unwrap();
        let slots = prepare_slots(&arena, 2);

        let batch = arena.claim_optimistic(CarrierCount::new(3)).unwrap();

        assert_eq!(batch.claimed(), CarrierCount::new(3));
        assert_eq!(batch.inspected_words(), 2);
        let carriers = batch.finish().unwrap();
        assert_eq!(
            carriers
                .iter()
                .filter(|carrier| carrier.slot_id() == slots[0].id())
                .count(),
            2
        );
        assert_eq!(
            carriers
                .iter()
                .filter(|carrier| carrier.slot_id() == slots[1].id())
                .count(),
            1
        );
        drop(carriers);
        assert_fully_free(&slots[0]);
        assert_fully_free(&slots[1]);
    }

    #[test]
    fn incomplete_finish_returns_all_provisional_bits() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let batch = arena.claim_optimistic(CarrierCount::new(3)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::new(2));

        let error = match batch.finish() {
            Ok(_) => panic!("an incomplete batch must not expose carriers"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            ArenaError::IncompleteClaim {
                required: 3,
                claimed: 2
            }
        ));
        assert_fully_free(&slot);
    }

    #[test]
    fn dropping_partial_batch_returns_all_provisional_bits() {
        let arena = test_arena(geometry_with_carriers(65), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let batch = arena.claim_optimistic(CarrierCount::new(66)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::new(64));

        drop(batch);

        assert_fully_free(&slot);
    }

    #[test]
    fn complete_batch_converts_exactly_the_requested_carriers() {
        let arena = test_arena(geometry_with_carriers(70), 2).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();

        let carriers = arena
            .claim_optimistic(CarrierCount::new(67))
            .unwrap()
            .finish()
            .unwrap();

        assert_eq!(carriers.len(), 67);
        assert_eq!(carriers.first().unwrap().carrier_index(), 0);
        assert_eq!(carriers.last().unwrap().carrier_index(), 66);
        drop(carriers);
        assert_fully_free(&slot);
    }

    #[test]
    fn concurrent_optimistic_claimants_cannot_share_a_carrier() {
        let arena = Arc::new(test_arena(geometry_with_carriers(2), 1).unwrap());
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let start = Arc::new(Barrier::new(2));
        let live = Arc::new(Barrier::new(2));

        let claim = |arena: Arc<Arena>, start: Arc<Barrier>, live: Arc<Barrier>| {
            thread::spawn(move || {
                start.wait();
                let carriers = loop {
                    let batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
                    if batch.is_complete() {
                        break batch.finish().unwrap();
                    }
                    thread::yield_now();
                };
                let id = (carriers[0].slot_id(), carriers[0].carrier_index());
                live.wait();
                drop(carriers);
                id
            })
        };
        let first = claim(Arc::clone(&arena), Arc::clone(&start), Arc::clone(&live));
        let second = claim(Arc::clone(&arena), Arc::clone(&start), Arc::clone(&live));

        assert_ne!(first.join().unwrap(), second.join().unwrap());
        assert_fully_free(&slot);
    }

    #[test]
    fn test_prepare_to_rounds_to_blocks_and_is_idempotent() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .prepare_to(&mut admission, CarrierCount::new(3))
            .unwrap();

        assert_eq!(admission.prepared_capacity(), CarrierCount::new(4));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 2);
        assert_eq!(arena.diagnostics().blocks_prepared, 2);

        arena
            .prepare_to(&mut admission, CarrierCount::new(4))
            .unwrap();
        assert_eq!(arena.diagnostics().blocks_prepared, 2);
    }

    #[test]
    fn test_prepare_to_reuses_an_inactive_slot_before_reserving() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slot = arena.reserve_slot().unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .prepare_to(&mut admission, CarrierCount::new(1))
            .unwrap();

        assert_eq!(admission.prepared_capacity(), CarrierCount::new(2));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 1);
        assert_fully_free(&slot);
    }

    #[test]
    fn test_prepare_to_failure_retains_earlier_preparation() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let first = arena.reserve_slot().unwrap();
        let second = arena.reserve_slot().unwrap();
        second.inject_failure_once(VirtualMemoryOperation::Prepare);
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        let error = arena
            .prepare_to(&mut admission, CarrierCount::new(3))
            .unwrap_err();

        assert!(matches!(
            error,
            ArenaError::Block(BlockError::VirtualMemory(ref error))
                if error.operation() == VirtualMemoryOperation::Prepare
        ));
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(2));
        assert_fully_free(&first);
        assert!(BlockSlot::try_claim(&second, CarrierCount::new(1))
            .unwrap()
            .is_none());

        arena
            .prepare_to(&mut admission, CarrierCount::new(3))
            .unwrap();
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(4));
        assert_fully_free(&second);
    }

    #[test]
    fn serialized_fallback_rechecks_active_capacity_before_growth() {
        let arena = test_arena(geometry_with_carriers(65), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let occupied = BlockSlot::try_claim_words(&slot, 0, 1, CarrierCount::new(64))
            .unwrap()
            .into_provisional()
            .unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        let admission = admission_with_prepared(CarrierCount::new(65));
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();

        assert!(batch.is_complete());
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(65));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 1);
        let carriers = batch.finish().unwrap();
        assert_eq!(carriers[0].carrier_index(), 64);
        drop(carriers);
        drop(occupied);
        assert_fully_free(&slot);
    }

    #[test]
    fn serialized_fallback_exhausts_fragmented_capacity_before_growth() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slots = prepare_slots(&arena, 3);
        let occupied = slots
            .iter()
            .map(|slot| {
                BlockSlot::try_claim(slot, CarrierCount::new(1))
                    .unwrap()
                    .unwrap()
            })
            .collect::<Vec<_>>();
        let mut batch = arena.claim_optimistic(CarrierCount::new(3)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::new(1));
        let admission = admission_with_prepared(CarrierCount::new(6));
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();

        assert!(batch.is_complete());
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(6));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 3);
        let carriers = batch.finish().unwrap();
        assert!(slots.iter().all(|slot| {
            carriers
                .iter()
                .filter(|carrier| carrier.slot_id() == slot.id())
                .count()
                == 1
        }));
        drop(carriers);
        drop(occupied);
        for slot in &slots {
            assert_fully_free(slot);
        }
    }

    #[test]
    fn serialized_fallback_reuses_inactive_slot_before_reserving() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let inactive = arena.reserve_slot().unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();

        assert_eq!(admission.prepared_capacity(), CarrierCount::new(2));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 1);
        let carriers = batch.finish().unwrap();
        assert_eq!(carriers[0].slot_id(), inactive.id());
        drop(carriers);
        assert_fully_free(&inactive);
    }

    #[test]
    fn serialized_fallback_grows_whole_blocks_until_complete() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(5)).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();

        assert!(batch.is_complete());
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(6));
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 3);
        let carriers = batch.finish().unwrap();
        assert_eq!(carriers.len(), 5);
        assert_eq!(
            carriers
                .iter()
                .map(|carrier| carrier.slot_id())
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            3
        );
    }

    #[test]
    fn later_preparation_failure_preserves_earlier_capacity() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let first = arena.reserve_slot().unwrap();
        let second = arena.reserve_slot().unwrap();
        second.inject_failure_once(VirtualMemoryOperation::Prepare);
        let mut batch = arena.claim_optimistic(CarrierCount::new(3)).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        let error = arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap_err();

        assert!(matches!(
            error,
            ArenaError::Block(BlockError::VirtualMemory(ref error))
                if error.operation() == VirtualMemoryOperation::Prepare
        ));
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(2));
        assert_eq!(batch.claimed(), CarrierCount::new(2));
        assert!(!batch.is_complete());
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 2);
        drop(batch);
        assert_fully_free(&first);
        assert!(BlockSlot::try_claim(&second, CarrierCount::new(1))
            .unwrap()
            .is_none());
    }

    #[test]
    fn serialized_growth_rejects_prepared_capacity_overflow() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
        let admission = admission_with_prepared(CarrierCount::new(usize::MAX));
        let mut admission = AdmissionGuard::new(admission.lock());

        let error = arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap_err();

        assert!(matches!(
            error,
            ArenaError::Block(BlockError::PreparedCapacityOverflow)
        ));
        assert_eq!(admission.prepared_capacity(), CarrierCount::new(usize::MAX));
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        let generation = arena.registry_generation();
        assert_eq!(generation.slots_in_claim_order().len(), 1);
        assert!(
            BlockSlot::try_claim(&generation.slots_in_claim_order()[0], CarrierCount::new(1))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn concurrent_serialized_fallbacks_retain_private_growth() {
        let arena = Arc::new(test_arena(geometry_with_carriers(2), 1).unwrap());
        let admission = Arc::new(admission_with_prepared(CarrierCount::ZERO));
        let start = Arc::new(Barrier::new(2));

        let fallback =
            |arena: Arc<Arena>, admission: Arc<Mutex<AdmissionState>>, start: Arc<Barrier>| {
                thread::spawn(move || {
                    let mut batch = arena.claim_optimistic(CarrierCount::new(2)).unwrap();
                    start.wait();
                    let mut admission = AdmissionGuard::new(admission.lock());
                    arena
                        .complete_claim_serialized(&mut admission, &mut batch)
                        .unwrap();
                    drop(admission);
                    batch.finish().unwrap()
                })
            };
        let first = fallback(
            Arc::clone(&arena),
            Arc::clone(&admission),
            Arc::clone(&start),
        );
        let second = fallback(
            Arc::clone(&arena),
            Arc::clone(&admission),
            Arc::clone(&start),
        );

        let first = first.join().unwrap();
        let second = second.join().unwrap();
        assert_eq!(
            AdmissionGuard::new(admission.lock()).prepared_capacity(),
            CarrierCount::new(4)
        );
        assert_eq!(arena.registry_generation().slots_in_claim_order().len(), 2);
        assert!(first.iter().all(|left| second.iter().all(|right| {
            (left.slot_id(), left.carrier_index()) != (right.slot_id(), right.carrier_index())
        })));
    }

    #[test]
    fn trim_selection_skips_inactive_and_occupied_slots() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let inactive = arena.reserve_slot().unwrap();
        let active = prepare_slots(&arena, 2);
        let occupied = BlockSlot::try_claim(&active[0], CarrierCount::new(1))
            .unwrap()
            .unwrap();

        let candidate = arena
            .select_trim_candidate()
            .expect("one active block is free");

        assert!(Arc::ptr_eq(&candidate, &active[1]));
        assert!(!Arc::ptr_eq(&candidate, &inactive));
        assert_eq!(arena.diagnostics().trim_slots_scanned, 3);
        drop(occupied);
    }

    #[test]
    fn trim_candidate_is_rechecked_after_selection() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let candidate = arena
            .select_trim_candidate()
            .expect("prepared block is initially free");
        let occupied = BlockSlot::try_claim(&slot, CarrierCount::new(1))
            .unwrap()
            .unwrap();
        let mut prepared = CarrierCount::new(2);

        assert!(matches!(
            BlockSlot::start_trim(&candidate, &mut prepared, CarrierCount::ZERO),
            Err(TrimBlocked::Busy)
        ));
        assert_eq!(prepared, CarrierCount::new(2));
        drop(occupied);
    }

    #[test]
    fn trim_selection_skips_cleanup_owned_slot() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();
        let mut prepared = CarrierCount::new(2);
        let cleanup = BlockSlot::start_trim(&slot, &mut prepared, CarrierCount::ZERO).unwrap();

        assert!(arena.select_trim_candidate().is_none());
        assert_eq!(arena.diagnostics().trim_slots_scanned, 1);

        cleanup.finish().unwrap();
    }

    #[test]
    fn arena_diagnostics_record_scan_growth_and_rollback() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        arena.reserve_slot().unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(3)).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();
        let before_rollback = arena.diagnostics();

        let detailed = before_rollback
            .detailed
            .expect("test arena must collect detailed scan counters");
        assert_eq!(detailed.optimistic_scans, 1);
        assert_eq!(detailed.optimistic_scan_words, 1);
        assert_eq!(before_rollback.optimistic_misses, 1);
        assert_eq!(before_rollback.serialized_fallbacks, 1);
        assert_eq!(before_rollback.serialized_slots_inspected, 2);
        assert_eq!(before_rollback.blocks_prepared, 2);
        assert_eq!(before_rollback.block_ranges_reserved, 2);
        assert_eq!(before_rollback.rolled_back_carriers, 0);

        drop(batch);
        assert_eq!(arena.diagnostics().rolled_back_carriers, 3);
    }

    #[test]
    fn serialized_completion_is_a_noop_for_an_already_complete_batch() {
        let arena = test_arena(geometry_with_carriers(1), 1).unwrap();
        prepare_slots(&arena, 1);
        let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
        assert!(batch.is_complete());
        let admission = admission_with_prepared(CarrierCount::new(1));
        let mut admission = AdmissionGuard::new(admission.lock());
        let before = arena.diagnostics();

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();

        assert_eq!(
            arena.diagnostics().serialized_fallbacks,
            before.serialized_fallbacks
        );
        drop(batch);
    }

    /// Asserts exact fallback frequency and registry work for one packed topology.
    fn assert_packed_fallback_work(
        block_counts: &[usize],
        carriers_per_block: usize,
        optimistic_scan_words: usize,
        iterations: u64,
    ) {
        for &blocks in block_counts {
            let full_blocks = blocks * 7 / 8;
            let arena = test_arena(
                geometry_with_carriers(carriers_per_block),
                optimistic_scan_words,
            )
            .unwrap();
            let slots = prepare_slots(&arena, blocks);
            let occupied = slots
                .iter()
                .take(full_blocks)
                .map(|slot| {
                    BlockSlot::try_claim(slot, slot.carrier_count())
                        .unwrap()
                        .expect("packed block should be free")
                })
                .collect::<Vec<_>>();
            let prepared = CarrierCount::new(blocks * carriers_per_block);
            let admission = admission_with_prepared(prepared);
            let before = arena.diagnostics();

            for _ in 0..iterations {
                let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
                if !batch.is_complete() {
                    let mut admission = AdmissionGuard::new(admission.lock());
                    arena
                        .complete_claim_serialized(&mut admission, &mut batch)
                        .unwrap();
                }
                drop(batch);
            }

            let after = arena.diagnostics();
            let fallbacks = after.serialized_fallbacks - before.serialized_fallbacks;
            let before_detailed = before
                .detailed
                .expect("test arena must collect detailed scan counters");
            let after_detailed = after
                .detailed
                .expect("test arena must collect detailed scan counters");
            let optimistic_scans =
                after_detailed.optimistic_scans - before_detailed.optimistic_scans;
            let recorded_slots =
                after.serialized_slots_inspected - before.serialized_slots_inspected;
            let expected_fallbacks = iterations * 7 / 8;
            let expected_slots = usize::try_from(expected_fallbacks)
                .unwrap()
                .checked_mul(full_blocks + 1)
                .unwrap();
            eprintln!(
                "blocks={blocks} full_blocks={full_blocks} \
                 iterations={iterations} fallbacks={fallbacks} \
                 serialized_slots_inspected={recorded_slots}"
            );

            assert_eq!(optimistic_scans, iterations);
            assert_eq!(fallbacks, expected_fallbacks);
            assert_eq!(recorded_slots, expected_slots as u64);
            drop(occupied);
        }
    }

    #[test]
    #[cfg_attr(
        miri,
        ignore = "registry-size work counting is covered by native suites; focused Miri tests cover allocator pointer safety"
    )]
    fn packed_fallback_work_has_an_exact_ci_regression_barrier() {
        assert_packed_fallback_work(&[8, 16, 32, 64, 128, 256], 64, 1, 256);
    }

    #[test]
    fn whole_word_miss_has_an_exact_serialized_work_barrier() {
        /*
         * Four two-word slots each retain one carrier in each word:
         *
         *     [x...............................][x...............................]
         *
         * No complete two-word run exists. Serialized completion must inspect
         * all four slots for a contiguous run, then consume 126 fragmented
         * carriers from slot 0 and the final two from slot 1. The exact work is
         * therefore 4 + 2 slot inspections, with no growth pass.
         */
        const SLOTS: usize = 4;
        const WORDS_PER_SLOT: usize = 2;
        const REQUEST: usize = WORDS_PER_SLOT * u64::BITS as usize;

        let arena = test_arena(geometry_with_carriers(REQUEST), WORDS_PER_SLOT).unwrap();
        let slots = prepare_slots(&arena, SLOTS);
        let mut blockers = Vec::new();
        for slot in &slots {
            for word in 0..WORDS_PER_SLOT {
                let blocker = BlockSlot::try_claim_words(slot, word, 1, CarrierCount::new(1))
                    .unwrap()
                    .into_provisional()
                    .expect("one carrier remains free in each word")
                    .into_carriers()
                    .unwrap();
                blockers.push(blocker);
            }
        }

        let admission = admission_with_prepared(CarrierCount::new(SLOTS * REQUEST));
        let before = arena.diagnostics();
        let mut batch = arena.claim_optimistic(CarrierCount::new(REQUEST)).unwrap();
        assert_eq!(batch.claimed(), CarrierCount::ZERO);
        arena
            .complete_claim_serialized(&mut AdmissionGuard::new(admission.lock()), &mut batch)
            .unwrap();
        let carriers = batch.finish().unwrap();
        let after = arena.diagnostics();

        assert_eq!(after.serialized_fallbacks - before.serialized_fallbacks, 1);
        assert_eq!(
            after.serialized_slots_inspected - before.serialized_slots_inspected,
            6
        );
        assert_eq!(after.blocks_prepared, before.blocks_prepared);
        assert_eq!(after.block_ranges_reserved, before.block_ranges_reserved);
        assert_eq!(
            carriers
                .iter()
                .filter(|carrier| carrier.slot_id() == slots[0].id())
                .count(),
            REQUEST - WORDS_PER_SLOT
        );
        assert_eq!(
            carriers
                .iter()
                .filter(|carrier| carrier.slot_id() == slots[1].id())
                .count(),
            WORDS_PER_SLOT
        );

        drop(carriers);
        drop(blockers);
        for slot in &slots {
            assert_fully_free(slot);
        }
    }

    #[test]
    #[ignore = "manual allocator work probe"]
    fn test_packed_fallback_work_scales_with_registry() {
        assert_packed_fallback_work(&[8, 16, 32, 64, 128, 256], 8_192, 32, 8_192);
    }

    #[test]
    fn completed_batch_is_not_recorded_as_rollback() {
        let arena = test_arena(geometry_with_carriers(2), 1).unwrap();
        let slot = prepare_slots(&arena, 1).pop().unwrap();

        let carriers = arena
            .claim_optimistic(CarrierCount::new(1))
            .unwrap()
            .finish()
            .unwrap();

        assert_eq!(arena.diagnostics().rolled_back_carriers, 0);
        drop(carriers);
        assert_eq!(arena.diagnostics().rolled_back_carriers, 0);
        assert_fully_free(&slot);
    }

    #[test]
    fn arena_diagnostics_saturate() {
        let diagnostics = ArenaDiagnostics::new(true);
        diagnostics
            .rolled_back_carriers
            .store(u64::MAX - 1, DiagnosticOrdering::Relaxed);

        diagnostics.record_rolled_back_carriers(usize::MAX);
        diagnostics.record_rolled_back_carriers(1);

        assert_eq!(diagnostics.snapshot().rolled_back_carriers, u64::MAX);
    }

    #[test]
    fn basic_diagnostics_omit_success_path_scan_counters() {
        let arena = Arena::new(geometry_with_carriers(2), ArenaOptions::new(1, false)).unwrap();
        let mut batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
        let admission = admission_with_prepared(CarrierCount::ZERO);
        let mut admission = AdmissionGuard::new(admission.lock());

        arena
            .complete_claim_serialized(&mut admission, &mut batch)
            .unwrap();
        let diagnostics = arena.diagnostics();

        assert_eq!(diagnostics.optimistic_misses, 1);
        assert_eq!(diagnostics.serialized_fallbacks, 1);
        assert_eq!(diagnostics.serialized_slots_inspected, 0);
        assert_eq!(diagnostics.detailed, None);
    }

    #[test]
    fn wrapped_scan_position_does_not_overflow() {
        assert_eq!(wrapped_position(3, 0, 4), 3);
        assert_eq!(wrapped_position(3, 1, 4), 0);
        assert_eq!(wrapped_position(3, 3, 4), 2);
        assert_eq!(wrapped_position(usize::MAX - 1, 1, usize::MAX), 0);
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use super::super::admission::{AdmissionGuard, AdmissionState, MAX_PACKED_CARRIERS};
    use super::super::virtual_memory::page_size;
    use super::*;
    use crate::runtime::sync::thread;

    fn test_arena(
        geometry: PoolGeometry,
        optimistic_scan_words: usize,
    ) -> Result<Arena, ArenaError> {
        Arena::new(geometry, ArenaOptions::new(optimistic_scan_words, true))
    }

    fn admission_with_prepared(prepared: CarrierCount) -> Mutex<AdmissionState> {
        let state = Mutex::new(AdmissionState::new(MAX_PACKED_CARRIERS));
        {
            let mut admission = AdmissionGuard::new(state.lock());
            *admission.prepared_capacity_mut() = prepared;
        }
        state
    }

    fn assert_coherent(generation: &RegistryGenerationGuard) {
        let generation = generation.inner.as_ref();
        assert_eq!(
            generation.slots_in_claim_order.len(),
            generation.address_ranges.len()
        );
        for range in &generation.address_ranges {
            let slot = &generation.slots_in_claim_order[range.slot_index];
            assert_eq!(slot.address_range(), Some(range.start..range.end));
        }
    }

    #[test]
    fn registry_generation_is_published_coherently() {
        loom::model(|| {
            let page_size = page_size().unwrap().get();
            let geometry = PoolGeometry::new(page_size, page_size, page_size).unwrap();
            let arena = Arc::new(test_arena(geometry, 1).unwrap());
            arena.reserve_slot().unwrap();

            let writer_arena = Arc::clone(&arena);
            let writer = thread::spawn(move || {
                writer_arena.reserve_slot().unwrap();
            });

            let reader_arena = Arc::clone(&arena);
            let reader = thread::spawn(move || {
                assert_coherent(&reader_arena.registry_generation());
            });

            writer.join().unwrap();
            reader.join().unwrap();
            let generation = arena.registry_generation();
            assert_coherent(&generation);
            assert_eq!(generation.slots_in_claim_order().len(), 2);
        });
    }

    #[test]
    fn completed_concurrent_batches_cannot_own_the_same_carrier() {
        loom::model(|| {
            let page_size = page_size().unwrap().get();
            let geometry = PoolGeometry::new(page_size, page_size * 2, page_size).unwrap();
            let arena = Arc::new(test_arena(geometry, 1).unwrap());
            let slot = arena.reserve_slot().unwrap();
            let mut prepared = CarrierCount::ZERO;
            slot.prepare(&mut prepared).unwrap();

            let claim = |arena: Arc<Arena>| {
                thread::spawn(move || {
                    let batch = arena.claim_optimistic(CarrierCount::new(1)).unwrap();
                    if batch.is_complete() {
                        Some(batch.finish().unwrap())
                    } else {
                        None
                    }
                })
            };
            let first = claim(Arc::clone(&arena));
            let second = claim(Arc::clone(&arena));

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            assert!(first.is_some() || second.is_some());
            if let (Some(first), Some(second)) = (&first, &second) {
                assert_ne!(first[0].carrier_index(), second[0].carrier_index());
            }
        });
    }

    #[test]
    fn concurrent_claims_use_distinct_rotated_windows() {
        loom::model(|| {
            let page_size = page_size().unwrap().get();
            let geometry = PoolGeometry::new(page_size, page_size * 65, page_size).unwrap();
            let arena = Arc::new(test_arena(geometry, 1).unwrap());
            let slot = arena.reserve_slot().unwrap();
            let mut prepared = CarrierCount::ZERO;
            slot.prepare(&mut prepared).unwrap();

            let claim = |arena: Arc<Arena>| {
                thread::spawn(move || {
                    arena
                        .claim_optimistic(CarrierCount::new(1))
                        .unwrap()
                        .finish()
                        .unwrap()
                })
            };
            let first = claim(Arc::clone(&arena));
            let second = claim(Arc::clone(&arena));

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            let mut indices = [first[0].carrier_index(), second[0].carrier_index()];
            indices.sort_unstable();
            assert_eq!(indices, [0, 64]);

            drop(first);
            drop(second);
            let returned = BlockSlot::try_claim(&slot, slot.carrier_count())
                .unwrap()
                .expect("both rotated-window owners returned");
            assert_eq!(returned.len(), slot.carrier_count());
        });
    }

    #[test]
    fn private_growth_cannot_be_stolen_by_an_optimistic_claim() {
        loom::model(|| {
            let page_size = page_size().unwrap().get();
            let geometry = PoolGeometry::new(page_size, page_size * 2, page_size).unwrap();
            let arena = Arc::new(test_arena(geometry, 1).unwrap());

            let fallback_arena = Arc::clone(&arena);
            let fallback = thread::spawn(move || {
                let mut batch = fallback_arena
                    .claim_optimistic(CarrierCount::new(1))
                    .unwrap();
                let admission = admission_with_prepared(CarrierCount::ZERO);
                let mut admission = AdmissionGuard::new(admission.lock());
                fallback_arena
                    .complete_claim_serialized(&mut admission, &mut batch)
                    .unwrap();
                assert_eq!(admission.prepared_capacity(), CarrierCount::new(2));
                batch.finish().unwrap()
            });

            let optimistic_arena = Arc::clone(&arena);
            let optimistic = thread::spawn(move || {
                let batch = optimistic_arena
                    .claim_optimistic(CarrierCount::new(1))
                    .unwrap();
                if batch.is_complete() {
                    Some(batch.finish().unwrap())
                } else {
                    None
                }
            });

            let fallback = fallback.join().unwrap();
            let optimistic = optimistic.join().unwrap();
            assert_eq!(fallback.len(), 1);
            if let Some(optimistic) = optimistic {
                assert_ne!(
                    (fallback[0].slot_id(), fallback[0].carrier_index()),
                    (optimistic[0].slot_id(), optimistic[0].carrier_index())
                );
            }
        });
    }
}