ramvamp-core 0.1.1

Runtime for streaming fine-grained MoE experts from NVMe: packed format, io_uring reads, LFU expert cache, CPU kernels, KV cache, generation loop
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
//! Page-aligned expert slot pool.
//!
//! One allocation of `n_layers * slots_per_layer` slots, each sized to its
//! layer's blob stride and based at a 4096-aligned address, faulted in at
//! construction, handed out through an explicit free list. These are the
//! destination buffers that io_uring + `O_DIRECT` reads land in and that the
//! expert GEMVs then read from.
//!
//! Two hard requirements. Both follow from the kernel source cited below;
//! the percentages attached to them come from bring-up runs on btrfs that
//! are **not recorded in `docs/experiments.md`**, so treat every number here
//! as provisional until they are.
//!
//! - The backing pages must be touched before any O_DIRECT read targets
//!   them. btrfs runs direct reads with page faults disabled
//!   (`fs/btrfs/direct-io.c`), and when it cannot fault the destination it
//!   silently completes the transfer through the buffered path instead —
//!   no error, full byte count, and the page cache grows inside our cgroup.
//! - A slot backing an in-flight read is never handed to a second reader.
//!   Aliasing two concurrent O_DIRECT reads onto one buffer makes btrfs
//!   fail checksum verification (provisional: 13-27% spurious EIO, and it
//!   increments the filesystem's persistent `corruption_errs`). Index
//!   arithmetic is not sufficient, because completions arrive out of order.
//!
//! # Alignment contract
//!
//! btrfs requires 4096 on the file offset, the transfer length **and** the
//! destination address. The device's 512-byte logical block size is not
//! sufficient, and `statx(STATX_DIOALIGN)` is unsupported on btrfs so the
//! real requirement cannot be probed at runtime — it is hard-coded as
//! [`SLOT_ALIGN`] and asserted in the tests.
//!
//! The slab is allocated once with `Layout::from_size_align(_, SLOT_ALIGN)`
//! and freed in `Drop` with that identical layout. Every slot's *pitch* (the
//! distance to the next slot) is the layer's stride rounded up to
//! [`SLOT_ALIGN`], so each slot base is `base + k * 4096` and therefore
//! 4096-aligned too. The real installed geometry needs no rounding — both
//! Qwen3-30B-A3B strides (3,059,712 B and 2,654,208 B) are exact multiples
//! of 4096 — but the pool stays correct for a layout that is not, at a cost
//! of under one page per slot. A slot's *length* is the declared stride, not
//! the pitch; a caller issuing O_DIRECT reads still owes the filesystem a
//! 4096-multiple length, which is the layout's job, not the pool's.
//!
//! # Aliasing contract
//!
//! [`SlotPool::acquire`] is the only way to obtain a slot and it yields an
//! owning [`SlotGuard`]. A guard is the unique lease on its slot: the slot
//! index leaves the layer's free stack on acquire and only returns on the
//! guard's `Drop`, and there is no by-index accessor. So *while a guard is
//! alive*, no second reader can name its bytes.
//!
//! That is a lease, and a lease is not a statement about in-flight DMA. The
//! difference is the whole risk in this file: dropping a guard and acquiring
//! again hands back the same slot at the same address, entirely from safe
//! code, so a caller that drops a guard while its read is still in flight
//! aliases the buffer exactly as if it had duplicated the pointer. Holding
//! the guard until the completion has been reaped is therefore a **caller
//! obligation**, not a structural guarantee. Two things make it visible:
//!
//! - [`SlotGuard::as_mut_ptr`] is `unsafe`, so every site that can create
//!   in-flight DMA has to acknowledge the contract in writing.
//! - [`SlotGuard::leak`] discharges the one case the obligation cannot cover
//!   on its own — an unwind that tears down an in-flight table before its
//!   completions can be reaped. Dropping those parked guards would recycle
//!   buffers the kernel is still writing into; leaking them costs one slot
//!   each and keeps the invariant.
//!
//! Recycling the address is only half of what a live read needs protected
//! from, though: the bytes have to keep *existing*. A guard borrows the pool,
//! so no live guard can outlive the slab — but `leak` consumes the guard and
//! ends that borrow, and the same unwind that forced the leak normally drops
//! the [`SlotPool`] a few frames further up. `Drop for SlotPool` therefore
//! refuses to `dealloc` while any slot is still leased and leaks the whole
//! slab instead, so a leaked slot's address stays owned by this process for
//! good. That is deliberate and it is not cheap — the slab is the byte budget,
//! up to 1438 MiB today — but it is bounded, it only happens on a teardown
//! that has already given up on reaping a completion, and the alternative is
//! the kernel writing into freed heap.
//!
//! Guards are `Send`, so the io_uring path parks them in its in-flight table
//! (keyed by `user_data`) for the lifetime of the read and drops them after
//! the completion is consumed.
//!
//! # Borrowing the whole slab as an arena
//!
//! [`SlotPool::slab_base`] hands out the base of the single owning
//! allocation, which is how the prefill sweep borrows the *idle* pool as
//! scratch for its large layer-major reads (see `io::sweep`). It is
//! `pub(crate)` and `unsafe` because it steps around the lease discipline
//! above: the returned address covers bytes that live [`SlotGuard`]s also
//! name, so the caller owes the exclusivity the guards would otherwise have
//! proved. `crate::io::stream` discharges that by tying the borrow to a
//! `&mut ExpertStream`, which makes every cache operation unreachable for as
//! long as the arena is live.
//!
//! [`SlotPool::padded_layer`] exists for the same caller: an arena is only a
//! gapless run of blob-sized buffers when every layer's pitch equals its
//! stride, which holds for any 4096-aligned layout (both shipped Qwen3
//! strides are) but is an emergent property of the geometry rather than a
//! contract, so it is checked rather than assumed.
//!
//! # Allocation
//!
//! Everything is allocated in [`SlotPool::new`]: the slab, the per-slot
//! occupancy flags, and the per-layer free stacks (each at exactly
//! `slots_per_layer` capacity, which they never exceed). `acquire` is a
//! `Vec::pop` and release is a `Vec::push` within that capacity, so the
//! decode loop never allocates.

use std::alloc::{Layout, alloc, dealloc};
use std::fmt;
use std::mem::ManuallyDrop;
use std::ptr::NonNull;
use std::slice;
use std::sync::{Mutex, MutexGuard, PoisonError};

use thiserror::Error;

use crate::format::{COMMON_FILE, ExpertsLayout, FormatError, Manifest};
use crate::kv::KvCache;

use super::error::IoError;
use super::stream::{bytes_per_slot, slots_for_budget};

/// Required alignment of every slot base address, in bytes.
///
/// btrfs's O_DIRECT path rejects anything coarser than this on the buffer
/// address, and the requirement is not probeable (`STATX_DIOALIGN` is
/// unimplemented there), so it is fixed rather than discovered.
pub const SLOT_ALIGN: usize = 4096;

/// Largest slab [`SlotPool::new`] will attempt, in bytes (4 GiB).
///
/// The expert-cache dial is a byte budget rather than a slot count: 1438 MiB
/// at the time of writing, which is 11 slots/layer over 48 layers at the
/// installed Qwen3-30B-A3B strides. This cap sits about 2.8x above that, so
/// every pool that could fit the 3 GB budget is still expressible, while a
/// corrupt or hostile layout is not.
///
/// It is *not* the constraint that decides the top of EXP-005's sweep, and
/// this cap being generous enough for 24 slots/layer does not mean the
/// project can build one. 24 slots/layer is 3,291,217,920 B, over the
/// 3,221,225,472 B of the `memory.max=3G` cgroup published numbers come from,
/// so `check_resident_budget` refuses it there — before the mmap'd common
/// core and the KV cache have taken their share. Under that cgroup the last
/// expressible sweep point is **23 slots/layer**, at 3,154,083,840 B.
///
/// A cap alone would not be worth much. Under default Linux overcommit a
/// multi-GiB `alloc` succeeds and returns non-null, so
/// [`SlotError::AllocFailed`] never fires; it is the pre-fault pass touching
/// every page that would then get the process OOM-killed inside its cgroup —
/// no error at all, which is strictly worse than an abort. So
/// [`SlotPool::new`] also refuses, before faulting anything, a slab that
/// cannot fit in the memory this process is allowed to make resident
/// ([`SlotError::ExceedsMemoryBudget`]).
pub const MAX_POOL_BYTES: u64 = 4 << 30;

/// Failures from sizing, allocating, or leasing expert slots.
///
/// Geometry reaches this module from `experts/layout.json`, which is
/// untrusted until validated, so every rejection is a recoverable error and
/// never a panic or an OOM abort.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum SlotError {
    /// `slots_per_layer` was zero; a pool with no slots can never serve a read.
    #[error("slot pool needs at least one slot per layer")]
    ZeroSlotsPerLayer,

    /// The stride list was empty.
    #[error("slot pool needs at least one layer")]
    NoLayers,

    /// More layers than a `u32` index can address.
    #[error("slot pool layer count {n_layers} exceeds u32")]
    TooManyLayers {
        /// Number of strides supplied.
        n_layers: usize,
    },

    /// A layer declared a zero-byte blob stride. Zero-length slots would all
    /// share one address, which is exactly the aliasing this pool prevents.
    #[error("layer {layer}: blob stride is zero")]
    ZeroStride {
        /// Offending layer index.
        layer: u32,
    },

    /// The requested geometry overflowed or exceeded [`MAX_POOL_BYTES`].
    #[error("slot pool needs {requested} bytes, over the {limit}-byte cap")]
    PoolTooLarge {
        /// Bytes the geometry asked for, computed in 128-bit to survive overflow.
        requested: u128,
        /// The cap that was exceeded.
        limit: u128,
    },

    /// The slab is at or over the memory this process may make resident, so
    /// pre-faulting it would be an OOM kill rather than an error.
    ///
    /// Distinct from [`SlotError::AllocFailed`], which under default
    /// overcommit is nearly unreachable: the allocation succeeds and it is
    /// the touching of the pages that fails, fatally and silently. Checked
    /// before a single page is touched.
    #[error(
        "slot pool needs {requested} bytes, at or over this process's {limit}-byte memory limit"
    )]
    ExceedsMemoryBudget {
        /// Bytes the geometry asked for.
        requested: u128,
        /// Tightest limit found: a cgroup v2 `memory.max` on this process's
        /// path, else `MemTotal`.
        limit: u64,
    },

    /// The allocator refused the slab.
    #[error("slot pool allocation of {bytes} bytes failed")]
    AllocFailed {
        /// Size of the refused request.
        bytes: usize,
    },

    /// A layer index is at or past the pool's layer count.
    #[error("layer {layer} out of range ({n_layers} layers)")]
    LayerOutOfRange {
        /// Requested layer index.
        layer: u32,
        /// Layers in the pool.
        n_layers: u32,
    },

    /// Every slot for the layer is already leased.
    #[error("layer {layer}: all {slots_per_layer} slots are in use")]
    Exhausted {
        /// Layer whose free stack is empty.
        layer: u32,
        /// Slots the layer owns.
        slots_per_layer: u32,
    },
}

/// Resolved geometry of one layer's slot run, fixed at construction.
#[derive(Debug, Clone, Copy)]
struct LayerGeom {
    /// Byte offset of the layer's first slot from the slab base. A multiple
    /// of [`SLOT_ALIGN`], because every pitch is.
    base_offset: usize,
    /// Usable bytes per slot: the layer's declared blob stride.
    stride: usize,
    /// Distance between consecutive slot bases: `stride` rounded up to
    /// [`SLOT_ALIGN`].
    pitch: usize,
}

/// Mutable pool bookkeeping. Both halves are sized at construction and never
/// grow.
#[derive(Debug)]
struct PoolState {
    /// Per-slot lease flag, flat-indexed `layer * slots_per_layer + slot`.
    /// Redundant with the free stacks by construction; kept as the explicit
    /// per-slot state that makes a double release detectable rather than
    /// silently corrupting the free list.
    leased: Box<[bool]>,
    /// Per-layer stack of free slot indices, capacity `slots_per_layer`.
    free: Box<[Vec<u32>]>,
}

/// A pool of page-aligned, pre-faulted expert blob buffers.
///
/// One owning allocation is carved into `slots_per_layer` slots for each
/// layer, each slot sized to that layer's blob stride. See the module docs
/// for the alignment, aliasing, and allocation contracts.
///
/// Usage sketch (not a doctest until the module is re-exported from
/// `io/mod.rs`):
///
/// ```text
/// // 48 layers with the real Qwen3-30B-A3B strides. The dial is a byte
/// // budget; 11 slots/layer is what 1438 MiB buys on this model today.
/// let pool = SlotPool::new(11, &layer_strides)?;
/// let mut slot = pool.acquire(layer)?;
/// // SAFETY: `slot` is parked below and not touched until the CQE lands.
/// let dst: *mut u8 = unsafe { slot.as_mut_ptr() };
/// // ... submit, park `slot` in the in-flight table, wait for the CQE ...
/// let filled: &[u8] = slot.as_slice();    // compute reads the filled blob
/// // dropping `slot` returns it to that layer's free stack
/// ```
#[derive(Debug)]
pub struct SlotPool {
    /// Base of the single owning allocation, aligned to [`SLOT_ALIGN`].
    base: NonNull<u8>,
    /// The exact layout `base` was allocated with; `Drop` frees with it.
    alloc_layout: Layout,
    /// Total slab size in bytes.
    total_bytes: usize,
    /// Slots held for every layer.
    slots_per_layer: u32,
    /// Per-layer geometry, indexed by layer.
    layers: Box<[LayerGeom]>,
    /// Free stacks and lease flags.
    state: Mutex<PoolState>,
}

// SAFETY: `SlotPool` owns its allocation exclusively for its whole lifetime
// and never dereferences `base` itself — it only computes offsets from it.
// Every byte handed out is handed out through a `SlotGuard`, and which slot a
// guard covers is decided under `state`'s mutex, so two threads can never
// obtain overlapping views. The raw pointer is the only reason the automatic
// impls do not apply.
unsafe impl Send for SlotPool {}
// SAFETY: see the `Send` impl. `&SlotPool` exposes only `acquire`, whose
// mutation goes through the mutex, and immutable geometry accessors.
unsafe impl Sync for SlotPool {}

impl SlotPool {
    /// Allocate, pre-fault, and index a pool of `slots_per_layer` slots for
    /// each stride in `layer_strides`.
    ///
    /// Sizing arithmetic runs in 128-bit, so an absurd geometry is reported
    /// rather than wrapped; the slab is checked against this process's memory
    /// limit before it is faulted, so an absurd geometry is an error rather
    /// than an OOM kill; and it is allocated with a null check, so a refusal
    /// is an error rather than an abort. Construction touches every page,
    /// which at the 1438 MiB budget is the dominant cost of this call.
    ///
    /// # Errors
    ///
    /// [`SlotError::ZeroSlotsPerLayer`], [`SlotError::NoLayers`],
    /// [`SlotError::TooManyLayers`], or [`SlotError::ZeroStride`] for a
    /// degenerate geometry; [`SlotError::PoolTooLarge`] when the slab would
    /// exceed [`MAX_POOL_BYTES`] (or this platform's `isize::MAX`);
    /// [`SlotError::ExceedsMemoryBudget`] when it would not fit in the memory
    /// this process may make resident; [`SlotError::AllocFailed`] when the
    /// allocator returns null.
    pub fn new(slots_per_layer: u32, layer_strides: &[u64]) -> Result<Self, SlotError> {
        Self::new_within(slots_per_layer, layer_strides, resident_limit())
    }

    /// [`SlotPool::new`] with the resident-memory limit supplied rather than
    /// probed, so the budget path is testable on any host.
    fn new_within(
        slots_per_layer: u32,
        layer_strides: &[u64],
        limit: Option<u64>,
    ) -> Result<Self, SlotError> {
        if slots_per_layer == 0 {
            return Err(SlotError::ZeroSlotsPerLayer);
        }
        if layer_strides.is_empty() {
            return Err(SlotError::NoLayers);
        }
        let n_layers =
            u32::try_from(layer_strides.len()).map_err(|_| SlotError::TooManyLayers {
                n_layers: layer_strides.len(),
            })?;

        // Cap at the smaller of the policy limit and what this platform can
        // even address, so the `usize` narrowing below cannot fail.
        let cap = u128::from(MAX_POOL_BYTES).min(isize::MAX as u128);
        let align = SLOT_ALIGN as u64;

        let mut layers = Vec::with_capacity(layer_strides.len());
        let mut total: u128 = 0;
        for (index, &stride) in layer_strides.iter().enumerate() {
            let layer = index as u32;
            if stride == 0 {
                return Err(SlotError::ZeroStride { layer });
            }
            // Rounding up keeps every slot base a multiple of SLOT_ALIGN even
            // when a layout's stride is not.
            let pitch = stride
                .checked_next_multiple_of(align)
                .ok_or(SlotError::PoolTooLarge {
                    requested: u128::from(stride),
                    limit: cap,
                })?;
            let base_offset = total;
            total += u128::from(pitch) * u128::from(slots_per_layer);
            if total > cap {
                // Report what the whole geometry needs, not the running total
                // at the layer that first crossed the cap. Bailing out here
                // with `total` understates the requirement by however many
                // layers are left, which for a 48-layer model is roughly 4x.
                let mut needed = total;
                for &rest in &layer_strides[layers.len() + 1..] {
                    let pitch = rest.checked_next_multiple_of(align).unwrap_or(rest);
                    needed = needed.saturating_add(
                        u128::from(pitch).saturating_mul(u128::from(slots_per_layer)),
                    );
                }
                return Err(SlotError::PoolTooLarge {
                    requested: needed,
                    limit: cap,
                });
            }
            layers.push(LayerGeom {
                // In range: `total <= cap <= isize::MAX` was just checked, and
                // `base_offset < total`.
                base_offset: base_offset as usize,
                stride: stride as usize,
                pitch: pitch as usize,
            });
        }
        // In range for the same reason.
        let total_bytes = total as usize;

        // Before the allocator, because under overcommit the allocator is not
        // the thing that says no: `prefault` below makes every byte resident.
        check_resident_budget(total, limit)?;

        let alloc_layout = Layout::from_size_align(total_bytes, SLOT_ALIGN).map_err(|_| {
            SlotError::PoolTooLarge {
                requested: total,
                limit: cap,
            }
        })?;
        // SAFETY: `total_bytes` is non-zero — there is at least one layer and
        // one slot, and every pitch is at least SLOT_ALIGN — which is the only
        // precondition of `alloc` beyond a valid layout.
        let raw = unsafe { alloc(alloc_layout) };
        let base = NonNull::new(raw).ok_or(SlotError::AllocFailed { bytes: total_bytes })?;

        // SAFETY: `base` is the start of `total_bytes` freshly allocated,
        // exclusively owned bytes.
        unsafe { prefault(base, total_bytes) };

        let n_slots = layers.len() * slots_per_layer as usize;
        let free = (0..layers.len())
            .map(|_| {
                let mut stack = Vec::with_capacity(slots_per_layer as usize);
                // Reversed so `pop` hands out ascending slot indices, which
                // keeps the early-life access pattern sequential.
                stack.extend((0..slots_per_layer).rev());
                stack
            })
            .collect::<Vec<_>>()
            .into_boxed_slice();

        tracing::debug!(
            n_layers,
            slots_per_layer,
            total_bytes,
            align = SLOT_ALIGN,
            "expert slot pool allocated and pre-faulted"
        );

        Ok(Self {
            base,
            alloc_layout,
            total_bytes,
            slots_per_layer,
            layers: layers.into_boxed_slice(),
            state: Mutex::new(PoolState {
                leased: vec![false; n_slots].into_boxed_slice(),
                free,
            }),
        })
    }

    /// Slots held for each layer.
    pub fn slots_per_layer(&self) -> u32 {
        self.slots_per_layer
    }

    /// Number of layers the pool covers.
    pub fn n_layers(&self) -> u32 {
        // Bounded by the `u32::try_from` in `new`.
        self.layers.len() as u32
    }

    /// Usable bytes in one of `layer`'s slots: the layer's declared blob
    /// stride, not the padded pitch.
    ///
    /// # Panics
    ///
    /// If `layer >= self.n_layers()`. Layer indices are program state, not
    /// untrusted input; use [`SlotPool::acquire`] when the index may be out
    /// of range, which reports [`SlotError::LayerOutOfRange`] instead.
    #[track_caller]
    pub fn stride(&self, layer: u32) -> usize {
        self.layers[layer as usize].stride
    }

    /// Distance between consecutive slot bases in `layer`: [`SlotPool::stride`]
    /// rounded up to [`SLOT_ALIGN`]. Equal to the stride for any
    /// page-aligned layout, including the installed Qwen3 one.
    ///
    /// # Panics
    ///
    /// If `layer >= self.n_layers()`.
    #[track_caller]
    pub fn pitch(&self, layer: u32) -> usize {
        self.layers[layer as usize].pitch
    }

    /// Largest per-slot stride across all layers — the size a scratch buffer
    /// must have to hold any expert blob.
    pub fn max_stride(&self) -> usize {
        self.layers.iter().map(|l| l.stride).max().unwrap_or(0)
    }

    /// Total resident bytes owned by the pool.
    pub fn total_bytes(&self) -> usize {
        self.total_bytes
    }

    /// Byte offset of one slot from the slab base, or `None` for an index out
    /// of range. Always a multiple of [`SLOT_ALIGN`].
    pub(crate) fn slot_offset(&self, layer: u32, slot: u32) -> Option<usize> {
        let geom = self.layers.get(layer as usize)?;
        if slot >= self.slots_per_layer {
            return None;
        }
        // No overflow: `base_offset + pitch * slots_per_layer` was summed into
        // `total_bytes` in `new`, in 128-bit, against a cap of `isize::MAX`.
        Some(geom.base_offset + geom.pitch * slot as usize)
    }

    /// The first layer whose slots are padded — pitch strictly greater than
    /// stride — as `(layer, stride, pitch)`, or `None` when every layer's
    /// blob stride is already [`SLOT_ALIGN`]-aligned.
    ///
    /// A padded layer means the slab is *not* a gapless run of blob-sized
    /// buffers, so a caller carving it into one (the prefill sweep) has to
    /// refuse rather than read blobs into addresses that drift by a page per
    /// slot. Both shipped Qwen3-30B-A3B strides are exact 4096 multiples, so
    /// this answers `None` on the model the runtime targets; a future layout
    /// that is not gets a typed refusal instead of silent corruption.
    pub(crate) fn padded_layer(&self) -> Option<(u32, usize, usize)> {
        self.layers
            .iter()
            .enumerate()
            .find(|(_, geom)| geom.pitch != geom.stride)
            .map(|(index, geom)| (index as u32, geom.stride, geom.pitch))
    }

    /// Base address of the single owning allocation, [`SLOT_ALIGN`]-aligned
    /// and valid for [`SlotPool::total_bytes`] bytes.
    ///
    /// # Safety
    ///
    /// This is the one accessor that reaches past the lease discipline: the
    /// range it covers includes every slot, and live [`SlotGuard`]s name those
    /// same bytes. Until the returned pointer and everything derived from it
    /// is dead, the caller must ensure no guard of this pool is read, written,
    /// or handed to the kernel, from any thread. See the module docs.
    pub(crate) unsafe fn slab_base(&self) -> NonNull<u8> {
        self.base
    }

    /// Slots currently free in `layer`, or `None` past the last layer.
    ///
    /// Advisory only: with concurrent readers the value can change before the
    /// caller acts on it. Use it for accounting, not for deciding whether
    /// [`SlotPool::acquire`] will succeed.
    pub fn free_slots(&self, layer: u32) -> Option<u32> {
        if layer >= self.n_layers() {
            return None;
        }
        let state = self.lock();
        // In range: checked above, and `free` has one entry per layer.
        Some(state.free[layer as usize].len() as u32)
    }

    /// Take the unique lease on a free slot of `layer`.
    ///
    /// The returned guard is the only handle to those bytes until it is
    /// dropped, which is what makes concurrent O_DIRECT reads onto one buffer
    /// unrepresentable.
    ///
    /// # Errors
    ///
    /// [`SlotError::LayerOutOfRange`] for an unknown layer;
    /// [`SlotError::Exhausted`] when every slot of the layer is leased. The
    /// caller decides what exhaustion means — wait for a completion, or fall
    /// back to a synchronous read.
    pub fn acquire(&self, layer: u32) -> Result<SlotGuard<'_>, SlotError> {
        let geom = *self
            .layers
            .get(layer as usize)
            .ok_or(SlotError::LayerOutOfRange {
                layer,
                n_layers: self.n_layers(),
            })?;
        let slot = {
            let mut state = self.lock();
            // In range: `layer` indexed `layers` successfully above.
            let slot = state.free[layer as usize]
                .pop()
                .ok_or(SlotError::Exhausted {
                    layer,
                    slots_per_layer: self.slots_per_layer,
                })?;
            let flat = self.flat_index(layer, slot);
            debug_assert!(!state.leased[flat], "free stack yielded a leased slot");
            state.leased[flat] = true;
            slot
        };

        // No overflow and in bounds: `pitch * slots_per_layer` was summed into
        // `total_bytes` in `new`, and `slot < slots_per_layer`.
        let offset = geom.base_offset + geom.pitch * slot as usize;
        debug_assert!(offset + geom.stride <= self.total_bytes);
        // SAFETY: `offset + stride <= total_bytes`, so the result stays within
        // the one allocation `base` points into, and a pointer one past the
        // end would still be well-defined. Non-null because `base` is.
        let ptr = unsafe { NonNull::new_unchecked(self.base.as_ptr().add(offset)) };
        Ok(SlotGuard {
            pool: self,
            layer,
            slot,
            ptr,
            len: geom.stride,
        })
    }

    /// Return a slot to its layer's free stack. Called only by
    /// [`SlotGuard::drop`], which guarantees one call per lease.
    fn release(&self, layer: u32, slot: u32) {
        let flat = self.flat_index(layer, slot);
        let mut state = self.lock();
        if !state.leased[flat] {
            // Unreachable while `SlotGuard` is the only lease handle. Logged
            // rather than panicked so a bug here degrades into a leaked slot
            // instead of unwinding through a drop.
            tracing::error!(layer, slot, "slot released without an active lease");
            return;
        }
        state.leased[flat] = false;
        let stack = &mut state.free[layer as usize];
        debug_assert!(
            stack.len() < stack.capacity(),
            "free stack would reallocate"
        );
        stack.push(slot);
    }

    /// Flat index of `(layer, slot)` into the lease-flag array.
    fn flat_index(&self, layer: u32, slot: u32) -> usize {
        layer as usize * self.slots_per_layer as usize + slot as usize
    }

    /// Whether any slot is still leased.
    ///
    /// Only [`SlotGuard::leak`] can make this true at drop time: every live
    /// guard borrows the pool, so the borrow checker already proves none of
    /// them outlives it. A leaked slot may still be an in-flight O_DIRECT
    /// destination, which is what [`Drop`] consults this for.
    fn any_slot_leased(&self) -> bool {
        self.lock().leased.iter().any(|&leased| leased)
    }

    /// Lock the bookkeeping, recovering from a poisoned mutex.
    ///
    /// A panic elsewhere while the lock was held cannot leave the free stacks
    /// inconsistent — every mutation under the lock is a single push or pop —
    /// so refusing to hand out slots for the rest of the process would be a
    /// worse outcome than continuing.
    fn lock(&self) -> MutexGuard<'_, PoolState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl Drop for SlotPool {
    fn drop(&mut self) {
        if self.any_slot_leased() {
            // The other half of `SlotGuard::leak`. A leaked slot exists
            // because its read could not be reaped, so the kernel may still
            // be writing into it; freeing the slab here would hand those
            // bytes back to the allocator under a live DMA, which is strictly
            // worse than the recycled address `leak` was called to avoid.
            // Leaking the whole slab is the only way to keep the address
            // owned once the guard that borrowed this pool is gone.
            tracing::error!(
                total_bytes = self.total_bytes,
                "expert slot pool dropped with slots still leased; leaking the \
                 slab so an unreaped O_DIRECT read cannot land in freed memory"
            );
            return;
        }
        // SAFETY: `base` came from `alloc(self.alloc_layout)` in `new` and was
        // never reallocated, so this is the same block with the identical
        // layout. Every `SlotGuard` borrows the pool, so none can outlive it;
        // the branch above rules out the one case a borrow cannot — a slot
        // whose guard was `leak`ed — so no live view into the slab exists here.
        unsafe { dealloc(self.base.as_ptr(), self.alloc_layout) };
    }
}

/// Exclusive lease on one expert slot.
///
/// While this value exists it is the only handle to its slot's bytes: no
/// other `acquire` can return the same slot, and there is no by-index
/// accessor on [`SlotPool`]. Dropping it returns the slot to the free stack,
/// and the next `acquire` for that layer may hand out the identical address,
/// so it must be held for the entire time a read is in flight — for io_uring
/// that means parking it in the in-flight table, not dropping it at
/// submission, and [`SlotGuard::leak`]ing it if an unwind makes the
/// completion unreapable. See [`SlotGuard::as_mut_ptr`] for the full
/// contract.
#[derive(Debug)]
pub struct SlotGuard<'pool> {
    pool: &'pool SlotPool,
    layer: u32,
    slot: u32,
    /// Base of this slot inside the pool slab; 4096-aligned.
    ptr: NonNull<u8>,
    /// Usable bytes: the layer's blob stride.
    len: usize,
}

// SAFETY: the guard is the unique lease on a disjoint sub-range of the slab,
// so moving it to another thread cannot create aliasing. It is only not
// automatically `Send`/`Sync` because of the raw pointer; `&SlotGuard` grants
// shared immutable reads and `&mut SlotGuard` is required for every write
// *by Rust*. Writes by the kernel are outside that argument and are excluded
// instead by the `unsafe` contract on `as_mut_ptr`, which forbids any slice
// view while a read is in flight — including from a thread holding a shared
// `&SlotGuard`, which is what this `Sync` impl makes possible.
unsafe impl Send for SlotGuard<'_> {}
// SAFETY: see the `Send` impl.
unsafe impl Sync for SlotGuard<'_> {}

impl SlotGuard<'_> {
    /// Layer this slot belongs to.
    pub fn layer(&self) -> u32 {
        self.layer
    }

    /// Index of this slot within its layer.
    pub fn index(&self) -> u32 {
        self.slot
    }

    /// Usable bytes in the slot: the layer's blob stride.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Always `false`; a zero-stride layer is rejected at construction.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Read-only view of the slot, for compute after a read completes.
    ///
    /// Every byte was initialized to zero in [`SlotPool::new`], so this is
    /// defined even before the slot has been filled; it just reads zeros.
    ///
    /// **Not while a read is in flight.** A kernel write through the pointer
    /// from [`SlotGuard::as_mut_ptr`] races any reference this returns, which
    /// no `&self`/`&mut self` distinction can rule out. That obligation is
    /// part of `as_mut_ptr`'s `unsafe` contract; it is restated here because
    /// this function is safe and `SlotGuard` is `Sync`, so a `&SlotGuard`
    /// shared with another thread can reach it.
    pub fn as_slice(&self) -> &[u8] {
        // SAFETY: `ptr` starts `len` initialized bytes inside the pool slab,
        // which outlives `self` via `pool`. This guard is the unique lease on
        // that range, and `&self` rules out a concurrent `&mut` view of it.
        // That covers conflicting *Rust* references only; the caller of
        // `as_mut_ptr` separately promised no kernel write is outstanding.
        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
    }

    /// Mutable view of the slot, for a synchronous read destination
    /// (`read_exact_at`) or for tests.
    ///
    /// Carries the same "not while a read is in flight" obligation as
    /// [`SlotGuard::as_slice`], for the same reason.
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        // SAFETY: as `as_slice`, plus `&mut self` proves no other reference
        // into this range exists. Ranges of distinct guards are disjoint by
        // construction. The kernel is not a Rust reference and is excluded by
        // `as_mut_ptr`'s contract, not by this borrow.
        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
    }

    /// Write destination for an asynchronous read, e.g. an io_uring `Read`
    /// SQE.
    ///
    /// The pointer is valid for `len()` bytes for as long as this guard is
    /// alive, and it is 4096-aligned as btrfs's O_DIRECT path requires.
    ///
    /// # Safety
    ///
    /// Handing this pointer to the kernel starts a write that Rust cannot
    /// see. Until the completion for that write has been reaped, the caller
    /// must ensure that:
    ///
    /// - this guard stays alive and is not dropped. Dropping it returns the
    ///   slot to the free stack, and the next [`SlotPool::acquire`] for that
    ///   layer can hand the identical address to a second reader — from
    ///   entirely safe code. This is the one way the pool's exclusivity can
    ///   be lost, and it is on the caller;
    /// - the [`SlotPool`] itself stays alive. Holding the guard is not
    ///   enough on its own to say this, because [`SlotGuard::leak`] ends the
    ///   guard's borrow of the pool: the bytes have to keep existing, not
    ///   just keep their lease. A live guard already proves this through the
    ///   borrow; a leaked one relies on `Drop for SlotPool` leaking the slab
    ///   rather than freeing it while any slot is still leased;
    /// - no second read is submitted against this pointer;
    /// - no [`as_slice`](SlotGuard::as_slice),
    ///   [`as_mut_slice`](SlotGuard::as_mut_slice), or
    ///   [`as_ptr`](SlotGuard::as_ptr) view of the range is created,
    ///   dereferenced, or held, from any thread — the guard is `Sync`, and a
    ///   shared reference over bytes the kernel is writing is a data race.
    ///   `as_ptr` is safe to *call* (it only computes an address), but
    ///   reading through it while a read is in flight is the same race as
    ///   `as_slice`.
    ///
    /// On an unwind that cannot reap the completion, [`SlotGuard::leak`] is
    /// the correct way to satisfy the first two obligations at once.
    pub unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
        self.ptr.as_ptr()
    }

    /// Give up this lease permanently: the slot never returns to its layer's
    /// free stack, so nothing can ever be handed its address again.
    ///
    /// The escape hatch for the case a guard alone cannot cover — an unwind
    /// that tears down an in-flight table before its completions have been
    /// reaped. Dropping those guards would recycle buffers the kernel is
    /// still writing into, which is the btrfs checksum failure this module
    /// exists to prevent; leaking them costs one slot of capacity each and
    /// keeps the invariant.
    ///
    /// The bytes are *not* freed with the rest of the slab afterwards. This
    /// consumes the guard, which ends its borrow of the pool, and the same
    /// unwind that made a completion unreapable will usually drop the
    /// [`SlotPool`] a few frames up — so `Drop for SlotPool` refuses to
    /// `dealloc` while any slot is still leased and leaks the slab instead.
    /// Recycling the address and freeing the address are the same bug at
    /// different scales, and `leak` has to answer both or it answers neither.
    /// The cost is the whole slab rather than one slot, paid only on a
    /// teardown that has already given up on the read.
    pub fn leak(self) {
        // Skipping `Drop` leaves `leased` set and the free stack short by
        // one, which is exactly the intent.
        let guard = ManuallyDrop::new(self);
        tracing::warn!(
            layer = guard.layer,
            slot = guard.slot,
            "expert slot leaked to protect an unreaped read; it will not be reused"
        );
    }

    /// Read-only raw pointer to the slot base, 4096-aligned.
    pub fn as_ptr(&self) -> *const u8 {
        self.ptr.as_ptr().cast_const()
    }
}

impl Drop for SlotGuard<'_> {
    fn drop(&mut self) {
        self.pool.release(self.layer, self.slot);
    }
}

/// Reject a slab that cannot be made resident at all.
///
/// Necessary, not sufficient: a pool under the process's limit can still be
/// far too big next to the mmap'd common core and the KV cache, and sizing it
/// inside the budget stays the caller's job. What this rules out is the case
/// with no error path at all — a geometry so large that the allocation
/// succeeds under overcommit and the pre-fault pass then gets the process
/// killed, which reports nothing to anyone.
///
/// **[`Footprint::project`] does not make this redundant, and deleting it
/// would reopen a hole.** The two checks answer different questions at
/// different times. This one is exact, runs at the last moment before the
/// pages are touched, and guards *every* path into [`SlotPool::new`] —
/// including callers that never went near a [`ForwardState`][fs], such as the
/// repacker's tools and the tests. The footprint check is an estimate of the
/// whole process, runs far earlier, and guards exactly one caller. A narrow,
/// certain check late plus a broad, approximate check early is the intended
/// arrangement; neither one covers the other's case.
///
/// [fs]: crate::model::ForwardState
fn check_resident_budget(requested: u128, limit: Option<u64>) -> Result<(), SlotError> {
    let Some(limit) = limit else {
        return Ok(());
    };
    // At the limit is already hopeless: the process's own text and stack, the
    // mmap'd common core and the KV cache all have to fit under it too.
    if requested >= u128::from(limit) {
        return Err(SlotError::ExceedsMemoryBudget { requested, limit });
    }
    Ok(())
}

/// One mebibyte.
const MIB: u128 = 1 << 20;

/// Anonymous runtime memory the process holds outside the three sized
/// tenants: activations and scratch, the tokenizer, thread stacks, allocator
/// arenas. **115.1 MiB, measured and provisional (EXP-012).**
///
/// Provisional in the experiment log's sense: EXP-012 sampled peak `anon`
/// from inside the cgroup on a live decode run whose context length, token
/// count and page-cache state were not recorded, so it fails rule 2 and
/// `docs/architecture.md` carries it as a floor for this tenant rather than a
/// ceiling. It is the one term of [`Footprint`] that is not arithmetic, and
/// it is why the whole projection is an estimate rather than a bound.
///
/// Two known residuals, of opposite sign, neither of which is corrected for
/// here — see [`Footprint::project`] for why:
///
/// - the fixed-tenant sum this constant belongs to **over**predicts the
///   measured cgroup peak by about 27 MiB once the KV cache's lazy faulting
///   is accounted for (EXP-023);
/// - EXP-018 records a separate, unexplained 99-105 MiB residual in the other
///   direction.
///
/// Exact arithmetic has since added 435 KiB to this tenant (387 KiB of
/// per-shard attention scratch in phase 7, 48 KiB of fused expert scratch in
/// phase 9), which is inside the noise of a figure that is provisional to
/// the nearest tens of MiB and is deliberately not folded in.
pub const RUNTIME_ANON_BYTES: u64 = (1151 * 1024 * 1024) / 10;

/// Why a footprint could not be projected.
///
/// Both variants are failures to *compute* the estimate, not verdicts on it:
/// the configuration was rejected by the same arithmetic that construction
/// would have rejected it with, only earlier.
#[derive(Debug, Error)]
pub enum FootprintError {
    /// The KV geometry is degenerate or overflows `usize`. Exactly what
    /// [`KvCache::new`] would have said.
    #[error(transparent)]
    Kv(#[from] crate::kv::KvError),

    /// The expert budget could not be divided into slots on this layout, or
    /// the install's metadata is incomplete. Exactly what
    /// [`ExpertStream::new`](super::ExpertStream::new) would have said.
    #[error(transparent)]
    Io(#[from] IoError),
}

/// Projected resident bytes of a whole runtime configuration, by tenant.
///
/// The breakdown, not just the sum, because the only reason to compute this
/// is to tell an operator which dial to move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Footprint {
    /// The mmap'd `common.bin`: embeddings, lm_head, attention, routers,
    /// norms. Charged to the cgroup as `file`, and resident in practice
    /// because every token touches it.
    pub common: u64,
    /// The expert slot slab, allocated and pre-faulted whole by
    /// [`SlotPool::new`].
    pub experts: u64,
    /// The FP16 KV cache at [`Footprint::context_cap`] positions.
    pub kv: u64,
    /// [`RUNTIME_ANON_BYTES`]: everything else the process holds.
    pub runtime: u64,
    /// Positions the KV term was sized for. Carried so the message can name
    /// the dial rather than only the byte count it produced.
    pub context_cap: usize,
}

impl Footprint {
    /// Project what a configuration will hold resident, before anything is
    /// allocated.
    ///
    /// Three of the four terms are arithmetic on numbers the install already
    /// declares, and each is computed by the code that will later do the
    /// allocating rather than by a restatement of it: `common` is the
    /// manifest's verified size for `common.bin` (checked byte-for-byte
    /// against the file in
    /// [`verify_named_file`](super::verify_named_file) before it is mapped),
    /// `experts` is [`slots_for_budget`]'s slot count times
    /// [`bytes_per_slot`], and `kv` is [`KvCache::projected_bytes`]. The
    /// fourth, [`RUNTIME_ANON_BYTES`], is measured and provisional.
    ///
    /// **This is an estimate, and it is deliberately not corrected.** Two
    /// residuals are on record, in opposite directions: the fixed-tenant sum
    /// overpredicts the measured cgroup peak by roughly 27 MiB (EXP-023,
    /// unattributed, though the KV cache's lazy faulting explains about 6.7
    /// MiB of the 33.4 MiB total), while EXP-018 records an unexplained
    /// 99-105 MiB residual the other way. A fudge factor tuned to either
    /// would be a guess dressed as a measurement, and would make the next
    /// person rediscover both. So the sum stays honest arithmetic on the
    /// numbers above, and the caller should refuse only what it says is
    /// impossible — never what it says is merely tight.
    ///
    /// Ordering note: the KV cache is `alloc_zeroed` at full capacity and
    /// faulted lazily, so at run time it is charged to the cgroup as it is
    /// written, not when it is allocated. That is precisely why this has to
    /// be asked *before* [`KvCache::new`]: the allocation cannot report the
    /// problem, and the pages that would are faulted in the middle of a
    /// prefill.
    ///
    /// # Errors
    ///
    /// [`FootprintError::Kv`] when the KV geometry is degenerate or its byte
    /// count overflows; [`FootprintError::Io`] when the manifest has no
    /// `common.bin` entry, the layout has no layers or a zero stride, or the
    /// expert budget buys fewer slots per layer than the model routes
    /// experts per step.
    pub fn project(
        manifest: &Manifest,
        layout: &ExpertsLayout,
        cache_bytes: u64,
        context_cap: usize,
    ) -> Result<Self, FootprintError> {
        // `Manifest::validate` already requires this entry, and
        // `verify_named_file` has already proved it equal to the file on
        // disk, so a `Model` can never take this branch. It is here because
        // the signature takes a `Manifest` rather than a loaded model, and
        // this crate does not `unwrap` on metadata.
        let common = manifest
            .files
            .get(COMMON_FILE)
            .ok_or_else(|| IoError::from(FormatError::MissingFileEntry(COMMON_FILE.to_owned())))?
            .size;

        let strides: Vec<u64> = layout.layers.iter().map(|layer| layer.stride).collect();
        let n_experts: Vec<u32> = layout.layers.iter().map(|layer| layer.n_experts).collect();
        let per_slot = bytes_per_slot(&strides)?;
        let slots = slots_for_budget(cache_bytes, &strides, &n_experts, manifest.arch.top_k)?;
        // `SlotPool::new` lays out `slots_per_layer` slots at each layer's
        // page-aligned pitch, so its whole slab is this product — the same
        // number `ExpertStream::cache_bytes` reports afterwards.
        let experts =
            u64::try_from(per_slot * u128::from(slots)).map_err(|_| IoError::TooLarge {
                what: "expert slot pool bytes",
                value: cache_bytes,
            })?;

        let arch = &manifest.arch;
        let kv = KvCache::projected_bytes(
            arch.n_layers as usize,
            arch.n_kv_heads as usize,
            arch.head_dim as usize,
            context_cap,
        )?;

        Ok(Self {
            common,
            experts,
            kv,
            runtime: RUNTIME_ANON_BYTES,
            context_cap,
        })
    }

    /// Projected resident bytes across every tenant.
    ///
    /// In 128-bit so the sum of four `u64`s cannot be the thing that wraps.
    pub fn total(&self) -> u128 {
        u128::from(self.common)
            + u128::from(self.experts)
            + u128::from(self.kv)
            + u128::from(self.runtime)
    }

    /// Whether this configuration is arithmetically possible under `limit`.
    ///
    /// Strictly `>` rather than `>=`: a sum that exactly meets the ceiling is
    /// what the arithmetic says fits, and given the residuals documented on
    /// [`RUNTIME_ANON_BYTES`] this check has no business being stricter than
    /// its own inputs.
    pub fn fits_within(&self, limit: u64) -> bool {
        self.total() <= u128::from(limit)
    }
}

impl fmt::Display for Footprint {
    /// `about 4,113 MiB (common 1,023 + experts 1,439 + KV 1,536 at 16384
    /// tokens + runtime 115)` — every term named, so the reader can see which
    /// one is theirs to change.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "about {} MiB (common {} + experts {} + KV {} at {} tokens + runtime {})",
            mib(self.total()),
            mib(u128::from(self.common)),
            mib(u128::from(self.experts)),
            mib(u128::from(self.kv)),
            self.context_cap,
            mib(u128::from(self.runtime)),
        )
    }
}

/// `bytes` as whole mebibytes, rounded to nearest, grouped with `,` — the way
/// `docs/architecture.md` writes every figure in the memory contract
/// (`1,023.34 MiB`, `3,072 MiB`).
pub(crate) fn mib(bytes: u128) -> String {
    let whole = (bytes + MIB / 2) / MIB;
    let digits = whole.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, digit) in digits.char_indices() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            out.push(',');
        }
        out.push(digit);
    }
    out
}

/// Bytes this process could hold resident at most, or `None` when the kernel
/// will not say — the ceiling [`Footprint`] is judged against.
///
/// The public face of the same probe [`SlotPool::new`] uses for its own
/// narrower check, so the two cannot disagree about what the limit is.
pub fn resident_ceiling() -> Option<u64> {
    resident_limit()
}

/// Bytes this process could hold resident at most, or `None` when the kernel
/// will not say.
///
/// The tightest of `MemTotal` and every cgroup v2 `memory.max` on this
/// process's path — published numbers come from a `memory.max=3G` cgroup, so
/// the cgroup limit is the one that actually binds. cgroup v1 is not
/// consulted; a host old enough to lack v2 falls back to `MemTotal`, which is
/// still enough to catch a corrupt layout.
#[cfg(target_os = "linux")]
fn resident_limit() -> Option<u64> {
    let mut limit = std::fs::read_to_string("/proc/meminfo")
        .ok()
        .and_then(|meminfo| parse_mem_total(&meminfo));
    if let Ok(contents) = std::fs::read_to_string("/proc/self/cgroup")
        && let Some(path) = parse_cgroup_v2_path(&contents)
    {
        for dir in cgroup_ancestors(path) {
            let max = std::fs::read_to_string(format!("/sys/fs/cgroup{dir}/memory.max"))
                .ok()
                .and_then(|contents| parse_memory_max(&contents));
            if let Some(max) = max {
                limit = Some(limit.map_or(max, |current| current.min(max)));
            }
        }
    }
    limit
}

#[cfg(not(target_os = "linux"))]
fn resident_limit() -> Option<u64> {
    None
}

/// This process's cgroup v2 path from `/proc/self/cgroup`: the `0::` line.
#[cfg(target_os = "linux")]
fn parse_cgroup_v2_path(contents: &str) -> Option<&str> {
    contents
        .lines()
        .find_map(|line| line.strip_prefix("0::"))
        .map(str::trim_end)
}

/// A cgroup path and every ancestor up to the root, because the limit that
/// binds this process is often set on a parent slice rather than the leaf.
#[cfg(target_os = "linux")]
fn cgroup_ancestors(path: &str) -> Vec<&str> {
    let mut out = vec![path];
    let mut rest = path;
    while let Some(cut) = rest.rfind('/') {
        rest = &rest[..cut];
        out.push(rest);
    }
    out
}

/// A cgroup v2 `memory.max`, or `None` for the literal `max` (no limit).
#[cfg(target_os = "linux")]
fn parse_memory_max(contents: &str) -> Option<u64> {
    let value = contents.trim();
    if value == "max" {
        return None;
    }
    value.parse().ok()
}

/// `MemTotal` from `/proc/meminfo`, in bytes. The kernel writes it in kB.
#[cfg(target_os = "linux")]
fn parse_mem_total(contents: &str) -> Option<u64> {
    let line = contents
        .lines()
        .find_map(|line| line.strip_prefix("MemTotal:"))?;
    let mut fields = line.split_whitespace();
    let value: u64 = fields.next()?.parse().ok()?;
    match fields.next() {
        Some("kB") => value.checked_mul(1024),
        None => Some(value),
        _ => None,
    }
}

/// Make every page of `base[..len]` resident and its bytes initialized.
///
/// This is the single most important thing in this file. btrfs issues
/// O_DIRECT reads with page faults disabled (`fs/btrfs/direct-io.c:1107`):
/// when it cannot fault the destination it does not fail, it silently
/// completes the transfer through the *buffered* path — the read returns the
/// full byte count with no error, and the page cache grows inside our 3 GB
/// cgroup, which is the one thing the whole design exists to avoid. Freshly
/// allocated pages are untouched, so without this the very first read into
/// every slot takes that path.
///
/// Two passes, for two different reasons:
///
/// 1. `write_bytes` zeroes the slab, which makes every byte an initialized
///    `u8` so [`SlotGuard::as_slice`] is defined before the first fill.
/// 2. One `write_volatile` per 4096 bytes. A volatile store cannot be elided
///    or sunk by the optimizer, so the write fault that makes each page a
///    private resident anon page provably happens here rather than inside a
///    fault-disabled O_DIRECT read. The step is [`SLOT_ALIGN`] rather than
///    the running page size because 4096 divides every Linux page size, so
///    stepping by it touches every page on 16K- and 64K-page hosts too.
///
/// The kernel serves *read* faults from the shared zero page but always
/// allocates a private page on a *write* fault, which is why both passes
/// write.
///
/// # Safety
///
/// `base` must point to `len` writable bytes that the caller owns
/// exclusively.
unsafe fn prefault(base: NonNull<u8>, len: usize) {
    let ptr = base.as_ptr();
    // SAFETY: the caller guarantees `len` writable, exclusively owned bytes
    // at `ptr`.
    unsafe { ptr.write_bytes(0, len) };
    let mut offset = 0;
    while offset < len {
        // SAFETY: `offset < len`, so `ptr.add(offset)` is a writable byte in
        // the same allocation.
        unsafe { ptr.add(offset).write_volatile(0) };
        offset += SLOT_ALIGN;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::sync::Arc;

    /// The two real Qwen3-30B-A3B per-layer blob strides.
    const REAL_STRIDES: [u64; 2] = [3_059_712, 2_654_208];

    /// Small page-aligned geometry: three layers, two distinct strides.
    fn small_pool(slots_per_layer: u32) -> SlotPool {
        SlotPool::new(slots_per_layer, &[8192, 4096, 8192]).unwrap()
    }

    /// Acquire every slot of every layer at once.
    fn acquire_all(pool: &SlotPool) -> Vec<SlotGuard<'_>> {
        let mut held = Vec::new();
        for layer in 0..pool.n_layers() {
            for _ in 0..pool.slots_per_layer() {
                held.push(pool.acquire(layer).unwrap());
            }
        }
        held
    }

    #[test]
    fn pool_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SlotPool>();
        assert_send_sync::<SlotGuard<'_>>();
        assert_send_sync::<SlotError>();
    }

    #[test]
    fn every_slot_base_is_page_aligned() {
        // Includes a deliberately unaligned stride: alignment must survive it.
        let pool = SlotPool::new(3, &[8192, 4096, 100, 3_059_712]).unwrap();
        let held = acquire_all(&pool);
        assert_eq!(held.len(), 12);
        for guard in &held {
            assert_eq!(
                guard.as_ptr() as usize % SLOT_ALIGN,
                0,
                "layer {} slot {} base {:p} is not {SLOT_ALIGN}-aligned",
                guard.layer(),
                guard.index(),
                guard.as_ptr()
            );
        }
    }

    /// The arena surface: a gapless slab reports no padded layer, its base is
    /// page-aligned, and every slot offset lands where `acquire` puts it.
    ///
    /// This is what the prefill sweep carves, so "no padded layer" is not a
    /// diagnostic — it is the precondition for the carve being a run of
    /// blob-sized buffers rather than one with a hole every slot.
    #[test]
    fn a_gapless_pool_reports_no_padding_and_offsets_that_match_its_guards() {
        for strides in [&[8192u64, 4096][..], &REAL_STRIDES[..]] {
            let pool = SlotPool::new(3, strides).unwrap();
            assert_eq!(
                pool.padded_layer(),
                None,
                "{strides:?} is 4096-aligned throughout"
            );
            // SAFETY: nothing is leased, so no guard can be aliased.
            let base = unsafe { pool.slab_base() }.as_ptr() as usize;
            assert_eq!(base % SLOT_ALIGN, 0);

            let mut expected = 0usize;
            for (layer, &stride) in strides.iter().enumerate() {
                for slot in 0..3 {
                    assert_eq!(
                        pool.slot_offset(layer as u32, slot),
                        Some(expected),
                        "layer {layer} slot {slot}"
                    );
                    // The guard the pool hands out sits at exactly that offset.
                    let guard = pool.acquire(layer as u32).unwrap();
                    assert_eq!(
                        guard.as_ptr() as usize - base,
                        pool.slot_offset(layer as u32, guard.index()).unwrap()
                    );
                    expected += stride as usize;
                }
            }
            // Gapless: the offsets tile the whole slab.
            assert_eq!(expected, pool.total_bytes());
            assert_eq!(pool.slot_offset(strides.len() as u32, 0), None);
            assert_eq!(pool.slot_offset(0, 3), None);
        }
    }

    /// A stride that is not a 4096 multiple pads every slot, which is exactly
    /// the geometry an arena carve must refuse.
    #[test]
    fn a_padded_layer_is_named_with_its_stride_and_pitch() {
        let pool = SlotPool::new(2, &[4096, 5000, 8192]).unwrap();
        assert_eq!(pool.padded_layer(), Some((1, 5000, 8192)));
        // The gap is real: consecutive slots of layer 1 are a pitch apart, not
        // a stride apart, so a blob written at `base + 2 * stride` would land
        // inside the wrong slot.
        assert_eq!(pool.slot_offset(1, 0), Some(8192));
        assert_eq!(pool.slot_offset(1, 1), Some(8192 + 8192));
        assert_ne!(pool.slot_offset(1, 1), Some(8192 + 5000));
    }

    #[test]
    fn strides_and_sizing_match_the_real_layout() {
        // 48 layers, 24 of each real stride, but one slot each so the test
        // does not allocate the 1569 MiB the target configuration would.
        let strides: Vec<u64> = (0..48).map(|i| REAL_STRIDES[i % 2]).collect();
        for &stride in &REAL_STRIDES {
            assert_eq!(stride % SLOT_ALIGN as u64, 0, "real stride is page-sized");
        }
        let pool = SlotPool::new(1, &strides).unwrap();
        assert_eq!(pool.n_layers(), 48);
        assert_eq!(pool.slots_per_layer(), 1);
        assert_eq!(pool.max_stride(), 3_059_712);
        for layer in 0..pool.n_layers() {
            let expected = REAL_STRIDES[layer as usize % 2] as usize;
            assert_eq!(pool.stride(layer), expected, "layer {layer} stride");
            // Already page-aligned, so no padding.
            assert_eq!(pool.pitch(layer), expected, "layer {layer} pitch");
            assert_eq!(pool.acquire(layer).unwrap().len(), expected);
        }
        let expected_total: usize = strides.iter().map(|&s| s as usize).sum();
        assert_eq!(pool.total_bytes(), expected_total);

        // The dial is a byte budget, so the arithmetic that matters is bytes
        // per slot per model; the slot count is what a budget buys. Checked
        // without allocating any of it: 24 layers of each stride.
        let per_slot_per_model = 24 * (3_059_712usize + 2_654_208);
        assert_eq!(per_slot_per_model, 137_134_080);
        // 1438 MiB, the current default, is 11 slots/layer.
        assert_eq!(11 * per_slot_per_model / (1024 * 1024), 1438);
        // The next slot up costs 131 MiB more, and every configuration that
        // could fit the 3 GB budget stays under the policy cap.
        assert_eq!(12 * per_slot_per_model / (1024 * 1024), 1569);
        assert!(24 * per_slot_per_model < MAX_POOL_BYTES as usize);
    }

    #[test]
    fn unaligned_stride_is_padded_up_to_a_page_pitch() {
        let pool = SlotPool::new(2, &[100, 4097]).unwrap();
        assert_eq!(pool.stride(0), 100);
        assert_eq!(pool.pitch(0), 4096);
        assert_eq!(pool.stride(1), 4097);
        assert_eq!(pool.pitch(1), 8192);
        assert_eq!(pool.total_bytes(), 2 * 4096 + 2 * 8192);

        let a = pool.acquire(1).unwrap();
        let b = pool.acquire(1).unwrap();
        assert_eq!(a.len(), 4097);
        let gap = (b.as_ptr() as usize).abs_diff(a.as_ptr() as usize);
        assert_eq!(gap, 8192, "consecutive slots are a pitch apart");
        assert_eq!(b.as_ptr() as usize % SLOT_ALIGN, 0);
    }

    #[test]
    fn slots_are_zeroed_and_writable_over_their_whole_length() {
        let pool = SlotPool::new(1, &[3_059_712]).unwrap();
        let mut guard = pool.acquire(0).unwrap();
        assert!(
            guard.as_slice().iter().all(|&b| b == 0),
            "slab is zero-initialized at construction"
        );
        // Touch the first and last byte of every page, then read back.
        let len = guard.len();
        let bytes = guard.as_mut_slice();
        let mut offset = 0;
        while offset < len {
            bytes[offset] = 0xa5;
            let end = (offset + SLOT_ALIGN - 1).min(len - 1);
            bytes[end] = 0x5a;
            offset += SLOT_ALIGN;
        }
        let bytes = guard.as_slice();
        let mut offset = 0;
        while offset < len {
            assert_eq!(bytes[offset], 0xa5, "page at {offset} lost its write");
            offset += SLOT_ALIGN;
        }
    }

    /// Count resident pages of `[base, base+len)` via `/proc/self/pagemap`.
    ///
    /// Bit 63 of each 64-bit entry is "page present". Unprivileged readers
    /// have the PFN masked out since Linux 4.2 but keep the flags, so this
    /// works without capabilities. Returns `None` if pagemap is unreadable.
    #[cfg(target_os = "linux")]
    fn resident_pages(base: *const u8, len: usize) -> Option<usize> {
        use std::io::{Read, Seek, SeekFrom};

        let pages = len / SLOT_ALIGN;
        let mut file = std::fs::File::open("/proc/self/pagemap").ok()?;
        let index = base as u64 / SLOT_ALIGN as u64;
        file.seek(SeekFrom::Start(index * 8)).ok()?;
        let mut buf = vec![0u8; pages * 8];
        file.read_exact(&mut buf).ok()?;
        Some(
            buf.chunks_exact(8)
                .filter(|e| u64::from_le_bytes((*e).try_into().unwrap()) >> 63 & 1 == 1)
                .count(),
        )
    }

    /// The load-bearing test: prove the slab is resident after `new`, and
    /// prove the measurement can tell, by checking an equally sized fresh
    /// allocation that was *not* pre-faulted.
    #[test]
    #[cfg(target_os = "linux")]
    fn construction_faults_in_every_page() {
        const SLAB: usize = 512 * 1024;

        // A same-sized, same-aligned block that nobody touched. Mapped
        // rather than `alloc`ed: freeing a large block anywhere else in the
        // test binary raises glibc's dynamic `mmap_threshold` to that size,
        // after which an `alloc` of SLAB comes off the heap and can hand back
        // pages some earlier test already faulted in — which would fail this
        // control for a reason that has nothing to do with the slot pool.
        // Fresh anonymous pages are untouched by construction.
        let control = memmap2::MmapOptions::new().len(SLAB).map_anon().unwrap();
        let control_resident = resident_pages(control.as_ptr(), SLAB);
        drop(control);

        // 4 layers * 8 slots * 16 KiB == SLAB.
        let pool = SlotPool::new(8, &[16384; 4]).unwrap();
        assert_eq!(pool.total_bytes(), SLAB);
        let first = pool.acquire(0).unwrap();
        let pool_resident = resident_pages(first.as_ptr(), SLAB);
        drop(first);

        let (Some(control_resident), Some(pool_resident)) = (control_resident, pool_resident)
        else {
            // pagemap is unreadable (hardened kernel, unusual container).
            // The write/read-back coverage in the sibling test still stands.
            eprintln!("skipping residency assertions: /proc/self/pagemap unreadable");
            return;
        };

        let pages = SLAB / SLOT_ALIGN;
        assert_eq!(
            pool_resident, pages,
            "every page of the slab must be resident after new(); \
             an untouched page makes btrfs silently fall back to buffered I/O"
        );
        assert!(
            control_resident * 2 < pages,
            "residency check is not meaningful: an untouched {SLAB}-byte block \
             already reported {control_resident}/{pages} pages resident"
        );
    }

    #[test]
    fn simultaneously_held_slots_never_overlap() {
        let pool = SlotPool::new(4, &[8192, 4096, 12288]).unwrap();
        let held = acquire_all(&pool);
        assert_eq!(held.len(), 12);
        let ranges: Vec<(usize, usize)> = held
            .iter()
            .map(|g| {
                let start = g.as_ptr() as usize;
                (start, start + g.len())
            })
            .collect();
        for (i, a) in ranges.iter().enumerate() {
            for (j, b) in ranges.iter().enumerate().skip(i + 1) {
                assert!(
                    a.1 <= b.0 || b.1 <= a.0,
                    "slots {i} {a:?} and {j} {b:?} overlap"
                );
            }
        }
        // And every range lies inside the slab.
        let base = ranges.iter().map(|r| r.0).min().unwrap();
        let end = ranges.iter().map(|r| r.1).max().unwrap();
        assert!(end - base <= pool.total_bytes());
    }

    #[test]
    fn writes_through_one_slot_do_not_disturb_another() {
        let pool = small_pool(2);
        let mut held = acquire_all(&pool);
        for (i, guard) in held.iter_mut().enumerate() {
            guard.as_mut_slice().fill(i as u8 + 1);
        }
        for (i, guard) in held.iter().enumerate() {
            assert!(
                guard.as_slice().iter().all(|&b| b == i as u8 + 1),
                "slot {i} was clobbered by a neighbour"
            );
        }
    }

    #[test]
    fn exhaustion_is_a_typed_error_and_a_release_makes_a_slot_available() {
        let pool = small_pool(2);
        let a = pool.acquire(1).unwrap();
        let b = pool.acquire(1).unwrap();
        assert_ne!(a.index(), b.index(), "the same slot was leased twice");
        assert_eq!(pool.free_slots(1), Some(0));
        assert_eq!(
            pool.acquire(1).unwrap_err(),
            SlotError::Exhausted {
                layer: 1,
                slots_per_layer: 2
            }
        );
        // Other layers are unaffected.
        assert_eq!(pool.free_slots(0), Some(2));
        pool.acquire(0).unwrap();

        let freed = a.index();
        drop(a);
        assert_eq!(pool.free_slots(1), Some(1));
        let c = pool.acquire(1).unwrap();
        assert_eq!(c.index(), freed, "the released slot came back");
        drop((b, c));
        assert_eq!(pool.free_slots(1), Some(2));
    }

    #[test]
    fn acquire_rejects_an_out_of_range_layer() {
        let pool = small_pool(1);
        assert_eq!(
            pool.acquire(3).unwrap_err(),
            SlotError::LayerOutOfRange {
                layer: 3,
                n_layers: 3
            }
        );
        assert_eq!(pool.acquire(u32::MAX).unwrap_err(), {
            SlotError::LayerOutOfRange {
                layer: u32::MAX,
                n_layers: 3,
            }
        });
        assert_eq!(pool.free_slots(3), None);
    }

    #[test]
    fn rejects_degenerate_geometry() {
        assert_eq!(
            SlotPool::new(0, &[4096]).unwrap_err(),
            SlotError::ZeroSlotsPerLayer
        );
        assert_eq!(SlotPool::new(4, &[]).unwrap_err(), SlotError::NoLayers);
        assert_eq!(
            SlotPool::new(4, &[4096, 0, 4096]).unwrap_err(),
            SlotError::ZeroStride { layer: 1 }
        );
    }

    #[test]
    fn rejects_oversized_and_overflowing_geometry() {
        // Over the cap but nowhere near overflowing.
        let err = SlotPool::new(12, &[u64::from(u32::MAX); 48]).unwrap_err();
        assert!(
            matches!(err, SlotError::PoolTooLarge { .. }),
            "expected PoolTooLarge, got {err:?}"
        );
        // Would overflow a u64 product: 2^32 slots of ~2^63 bytes each.
        let err = SlotPool::new(u32::MAX, &[u64::MAX / 2; 4]).unwrap_err();
        assert!(
            matches!(err, SlotError::PoolTooLarge { .. }),
            "expected PoolTooLarge, got {err:?}"
        );
        // Rounding the stride up to a page is itself checked for overflow.
        let err = SlotPool::new(1, &[u64::MAX]).unwrap_err();
        assert!(
            matches!(err, SlotError::PoolTooLarge { .. }),
            "expected PoolTooLarge, got {err:?}"
        );
        // Right at the cap in one layer, still rejected rather than attempted.
        let err = SlotPool::new(1, &[MAX_POOL_BYTES + SLOT_ALIGN as u64]).unwrap_err();
        assert!(
            matches!(err, SlotError::PoolTooLarge { requested, limit }
                if requested > limit),
            "expected PoolTooLarge, got {err:?}"
        );
    }

    #[test]
    fn steady_state_acquire_and_release_do_not_allocate() {
        let pool = small_pool(3);
        let capacities: Vec<usize> = {
            let state = pool.lock();
            state.free.iter().map(Vec::capacity).collect()
        };
        for _ in 0..64 {
            let held = acquire_all(&pool);
            drop(held);
        }
        let after: Vec<usize> = {
            let state = pool.lock();
            state.free.iter().map(Vec::capacity).collect()
        };
        assert_eq!(
            capacities, after,
            "free stacks reallocated during steady state"
        );
        assert!(capacities.iter().all(|&c| c == 3));
    }

    /// Requirement 3, directly: hammer the pool from many threads and assert
    /// that no base address is ever leased twice at the same time. Modulo
    /// indexing over a queue depth would fail this; the free list does not.
    #[test]
    fn concurrent_acquire_never_hands_out_a_live_slot_twice() {
        let pool = Arc::new(SlotPool::new(2, &[8192, 4096, 8192]).unwrap());
        let live: Arc<Mutex<HashSet<usize>>> = Arc::new(Mutex::new(HashSet::new()));
        let mut handles = Vec::new();
        for t in 0..8u32 {
            let pool = Arc::clone(&pool);
            let live = Arc::clone(&live);
            handles.push(std::thread::spawn(move || {
                for i in 0..500u32 {
                    let layer = (t + i) % pool.n_layers();
                    let Ok(mut guard) = pool.acquire(layer) else {
                        continue; // legitimate exhaustion
                    };
                    let addr = guard.as_ptr() as usize;
                    assert!(
                        live.lock().unwrap().insert(addr),
                        "address {addr:#x} was leased twice concurrently"
                    );
                    // Write through the lease so a real aliasing bug would
                    // also show up as data corruption under a sanitizer.
                    guard.as_mut_slice()[0] = t as u8;
                    assert!(live.lock().unwrap().remove(&addr));
                }
            }));
        }
        for handle in handles {
            handle.join().unwrap();
        }
        assert!(live.lock().unwrap().is_empty());
        for layer in 0..pool.n_layers() {
            assert_eq!(
                pool.free_slots(layer),
                Some(2),
                "layer {layer} leaked slots"
            );
        }
    }

    /// The module's aliasing claim, stated as precisely as it is true: a
    /// *live* guard is exclusive, but dropping one recycles its address from
    /// entirely safe code. That is why holding the guard across an in-flight
    /// read is a caller obligation and [`SlotGuard::as_mut_ptr`] is `unsafe`
    /// rather than safe.
    #[test]
    fn a_dropped_guard_recycles_the_same_address() {
        let pool = SlotPool::new(1, &[8192]).unwrap();
        let first = pool.acquire(0).unwrap();
        let addr = first.as_ptr() as usize;
        drop(first);
        let second = pool.acquire(0).unwrap();
        assert_eq!(
            second.as_ptr() as usize,
            addr,
            "a released slot comes back at the same address, so a guard \
             dropped under a live read would alias it"
        );
    }

    /// The other half: `leak` is how the unwind path keeps that from
    /// happening when the completion cannot be reaped.
    #[test]
    fn a_leaked_guard_never_returns_to_the_free_stack() {
        let pool = small_pool(2);
        let leaked = pool.acquire(0).unwrap();
        let addr = leaked.as_ptr() as usize;
        leaked.leak();
        assert_eq!(pool.free_slots(0), Some(1), "the slot stays leased");

        let other = pool.acquire(0).unwrap();
        assert_ne!(
            other.as_ptr() as usize,
            addr,
            "the leaked slot was handed out again"
        );
        assert_eq!(
            pool.acquire(0).unwrap_err(),
            SlotError::Exhausted {
                layer: 0,
                slots_per_layer: 2
            }
        );
        // Dropping the pool with a slot still leased must not free the slab:
        // the point of the leak is that a read may still be landing in it.
        drop(other);
        assert!(
            pool.any_slot_leased(),
            "the leaked slot is what makes Drop keep the slab"
        );
        drop(pool);
    }

    /// The half of `leak` a guard cannot express: `leak` consumes the guard,
    /// which ends its borrow of the pool, so nothing in the type system stops
    /// the pool — and the slab — from being dropped out from under a read
    /// that is still in flight. `Drop for SlotPool` closes that by refusing
    /// to `dealloc` while any slot is leased.
    ///
    /// The `dealloc` itself is not observable from a test; what is observable
    /// is the decision it branches on, so that is what this pins.
    #[test]
    fn a_pool_with_a_leaked_slot_does_not_free_its_slab() {
        let pool = small_pool(2);
        assert!(
            !pool.any_slot_leased(),
            "a fresh pool owes nothing to anyone"
        );

        // An ordinary lease, taken and returned, still leaves nothing owed:
        // the slab is freed normally in that case.
        let ordinary = pool.acquire(0).unwrap();
        assert!(pool.any_slot_leased(), "a live guard holds its lease");
        drop(ordinary);
        assert!(
            !pool.any_slot_leased(),
            "a dropped guard hands its lease back"
        );

        // A leaked one does, forever, and that is what keeps the slab alive.
        pool.acquire(0).unwrap().leak();
        assert!(pool.any_slot_leased());
        // Every other slot going home does not change that: one unreaped
        // read is enough to make freeing the whole slab unsafe.
        let mut rest = vec![pool.acquire(0).unwrap()];
        for layer in 1..pool.n_layers() {
            for _ in 0..pool.slots_per_layer() {
                rest.push(pool.acquire(layer).unwrap());
            }
        }
        drop(rest);
        assert!(
            pool.any_slot_leased(),
            "the leaked slot must still pin the slab after every other guard \
             has been returned"
        );
        drop(pool);
    }

    #[test]
    fn the_raw_write_destination_is_the_slot_itself() {
        let pool = SlotPool::new(1, &[8192]).unwrap();
        let mut guard = pool.acquire(0).unwrap();
        // SAFETY: no read is in flight, no slice view is live, and the guard
        // outlives the pointer's use — the contract, discharged by hand.
        let ptr = unsafe { guard.as_mut_ptr() };
        assert_eq!(ptr as usize % SLOT_ALIGN, 0);
        // SAFETY: `ptr` is the base of `guard.len()` owned writable bytes.
        unsafe {
            ptr.write(0xa5);
            ptr.add(8191).write(0x5a);
        }
        assert_eq!(guard.as_slice()[0], 0xa5);
        assert_eq!(guard.as_slice()[8191], 0x5a);
    }

    #[test]
    fn a_slab_over_the_resident_budget_is_a_typed_error() {
        // The decision, exactly: at or over the limit is refused, under it is
        // allowed, and an unknown limit never refuses.
        assert_eq!(check_resident_budget(1 << 20, None), Ok(()));
        assert_eq!(check_resident_budget(1 << 20, Some(2 << 20)), Ok(()));
        assert_eq!(
            check_resident_budget(u128::from(3u64 << 30), Some(3 << 30)),
            Err(SlotError::ExceedsMemoryBudget {
                requested: u128::from(3u64 << 30),
                limit: 3 << 30,
            })
        );
        assert!(check_resident_budget(u128::from(MAX_POOL_BYTES), Some(3 << 30)).is_err());

        // And end to end, with the limit injected so the test reads the same
        // on every host: a geometry under `MAX_POOL_BYTES` that a 3 GB cgroup
        // could never hold is refused *before* anything is allocated or
        // faulted. Default overcommit would otherwise let the allocation
        // succeed and turn the pre-fault pass into a silent OOM kill.
        // 3.375 GiB: comfortably under the 4 GiB policy cap, so the cap does
        // not get to answer this one.
        let strides = vec![6 << 20; 48];
        let err = SlotPool::new_within(12, &strides, Some(3 << 30)).unwrap_err();
        assert_eq!(
            err,
            SlotError::ExceedsMemoryBudget {
                requested: 48 * 12 * (6 << 20),
                limit: 3 << 30,
            }
        );
        const { assert!(48 * 12 * (6u64 << 20) < MAX_POOL_BYTES) };

        // The same call is fine when the process may hold the slab.
        SlotPool::new_within(1, &[4096], Some(3 << 30)).expect("4 KiB fits in 3 GiB");
        SlotPool::new_within(1, &[4096], None).expect("an unknown limit is not a refusal");
    }

    /// [`MAX_POOL_BYTES`] is not the constraint that decides how many slots
    /// this project can actually build. Published numbers come from a
    /// `memory.max=3G` cgroup, which is tighter than the 4 GiB policy cap for
    /// every slot count above 23 — so quoting the cap as evidence that the
    /// whole EXP-005 sweep is reachable is wrong at the top of the sweep.
    #[test]
    fn the_benchmark_cgroup_binds_before_the_policy_cap() {
        // The 3 GB benchmark cgroup, exactly as `memory.max` spells it.
        const CGROUP_3G: u64 = 3 << 30;
        assert_eq!(CGROUP_3G, 3_221_225_472);
        // 24 layers of each real stride, one slot per layer.
        let per_slot: u128 = 24 * (3_059_712 + 2_654_208);
        assert_eq!(per_slot, 137_134_080);

        // The top of the EXP-005 sweep is under the policy cap...
        assert_eq!(24 * per_slot, 3_291_217_920);
        assert!(24 * per_slot < u128::from(MAX_POOL_BYTES));
        // ...and over the budget the benchmark actually runs in.
        assert_eq!(
            check_resident_budget(24 * per_slot, Some(CGROUP_3G)),
            Err(SlotError::ExceedsMemoryBudget {
                requested: 24 * per_slot,
                limit: CGROUP_3G,
            }),
            "24 slots/layer does not fit a memory.max=3G cgroup"
        );

        // 23 is the real boundary, and it already claims 97.9% of the cgroup
        // on its own.
        assert_eq!(23 * per_slot, 3_154_083_840);
        assert_eq!(
            check_resident_budget(23 * per_slot, Some(CGROUP_3G)),
            Ok(())
        );
        assert!(23 * per_slot * 100 / u128::from(CGROUP_3G) >= 97);
    }

    // -----------------------------------------------------------------------
    // The projected footprint
    // -----------------------------------------------------------------------

    /// The 3 GB benchmark cgroup every published number comes from.
    const CGROUP_3G: u64 = 3 << 30;
    /// The 4 GiB contract (EXP-033), as `memory.max` spells it.
    const CGROUP_4G: u64 = 4 << 30;

    /// `models/qwen3.rvmp/common.bin`, exactly — 1,023.34 MiB, the "Common
    /// core" row of the memory contract in `docs/architecture.md`.
    const V0_COMMON_BYTES: u64 = 1_073_051_648;

    /// One slot across all 48 layers at the audited strides: `24 *
    /// 3,059,712 + 24 * 2,654,208`, both already page multiples.
    const V0_PER_SLOT: u64 = 24 * (REAL_STRIDES[0] + REAL_STRIDES[1]);

    /// The audited Qwen3-30B-A3B install, in the only terms a footprint
    /// reads: the verified `common.bin` size, the attention geometry, the
    /// router width, and the two real per-layer blob strides.
    ///
    /// Declared rather than installed. The predictor's whole point is that it
    /// runs on metadata before anything is opened, so a test of it can hand
    /// it metadata; building a 16 GiB install to check arithmetic would test
    /// the fixture builder instead.
    fn v0_install() -> (Manifest, ExpertsLayout) {
        use crate::format::{FileEntry, LayerLayout, QuantInfo, RVMP_VERSION, SourceInfo};
        use std::collections::BTreeMap;

        let mut arch = crate::io::testutil::fixture_arch();
        arch.n_layers = 48;
        arch.n_experts = 128;
        arch.top_k = 8;
        arch.n_heads = 32;
        arch.n_kv_heads = 4;
        arch.head_dim = 128;

        let manifest = Manifest {
            rvmp_version: RVMP_VERSION,
            model_id: "qwen3-30b-a3b-instruct-2507".to_owned(),
            source: SourceInfo {
                hf_repo: "test/qwen3".to_owned(),
                revision: "0".repeat(40),
                file: "qwen3-Q4_K_M.gguf".to_owned(),
                sha256: "0".repeat(64),
            },
            arch,
            quant: QuantInfo {
                scheme: "gguf".to_owned(),
                tensor_types: BTreeMap::new(),
            },
            common_tensors: BTreeMap::new(),
            files: BTreeMap::from([(
                COMMON_FILE.to_owned(),
                FileEntry {
                    size: V0_COMMON_BYTES,
                    sha256: "0".repeat(64),
                },
            )]),
        };

        let layout = ExpertsLayout {
            layers: (0..48)
                .map(|layer| LayerLayout {
                    file: crate::format::layer_file_name(layer),
                    // 24 Q6_K-down layers pack the wider blob; the other 24
                    // are pure Q4_K.
                    stride: REAL_STRIDES[usize::from(layer >= 24)],
                    n_experts: 128,
                    projections: Vec::new(),
                })
                .collect(),
        };
        (manifest, layout)
    }

    /// **The published claim.** 19 slots per layer at a 4,096-token context
    /// under `memory.max=4G` is the 4 GiB contract (EXP-033), measured at a
    /// 4,008.4 MiB peak. A predictor that refuses it is wrong about the
    /// runtime, not the other way around — so this pins every tenant byte for
    /// byte, then the verdict, and then that the 3 GiB contract before it
    /// still holds at `--cache-bytes 1440M`.
    #[test]
    fn the_shipped_default_fits_the_published_four_gigabyte_budget() {
        let (manifest, layout) = v0_install();
        let projected =
            Footprint::project(&manifest, &layout, crate::model::DEFAULT_CACHE_BYTES, 4096)
                .expect("the shipped dials project");

        // Row by row against docs/architecture.md's memory contract.
        assert_eq!(projected.common, V0_COMMON_BYTES, "common core row");
        assert_eq!(V0_PER_SLOT, 137_134_080);
        assert_eq!(projected.experts, 19 * V0_PER_SLOT, "expert slot pool row");
        assert_eq!(projected.experts, 2_605_547_520);
        assert_eq!(projected.kv, 384 << 20, "KV cache row at 4K");
        assert_eq!(projected.runtime, RUNTIME_ANON_BYTES, "anonymous row");
        assert_eq!(projected.context_cap, 4096);

        // 4,007.28 MiB, against a measured 4,008.4 (EXP-033).
        assert_eq!(mib(projected.total()), "4,007");
        assert!(
            projected.fits_within(CGROUP_4G),
            "the shipped default must be accepted: {projected}"
        );
        // And it clears the ceiling by 88.7 MiB, not by a hair — if this
        // moves, the prediction has drifted from the measurement.
        let spare = u128::from(CGROUP_4G) - projected.total();
        assert_eq!(mib(spare), "89");
        // One slot more would not fit.
        let twenty = Footprint::project(&manifest, &layout, 20 * V0_PER_SLOT, 4096).unwrap();
        assert!(!twenty.fits_within(CGROUP_4G), "{twenty}");

        // The 3 GiB contract before it: 11 slots, 2,961.03 MiB, 111 spare.
        let three = Footprint::project(&manifest, &layout, 1440 << 20, 4096).unwrap();
        assert_eq!(three.experts, 11 * V0_PER_SLOT);
        assert_eq!(mib(three.total()), "2,961");
        assert!(three.fits_within(CGROUP_3G), "{three}");
        assert_eq!(mib(u128::from(CGROUP_3G) - three.total()), "111");
    }

    /// The KV term is the dial that is about to become configurable, so it is
    /// pinned at the rate the memory contract quotes: 96 KiB a token on the
    /// v0 geometry (48 layers x 4 kv heads x 128 head_dim x 2 planes x 2 B),
    /// and linear in the cap.
    #[test]
    fn the_kv_term_is_ninety_six_kibibytes_a_token_on_the_v0_geometry() {
        let (manifest, layout) = v0_install();
        for cap in [1usize, 512, 4096, 16_384, 131_072] {
            let projected =
                Footprint::project(&manifest, &layout, crate::model::DEFAULT_CACHE_BYTES, cap)
                    .expect("a sane cap projects");
            assert_eq!(
                projected.kv,
                cap as u64 * 96 * 1024,
                "kv term at a {cap}-token cap"
            );
            assert_eq!(projected.context_cap, cap);
            // Only the KV term moves with the context.
            assert_eq!(projected.common, V0_COMMON_BYTES);
            assert_eq!(projected.experts, 19 * V0_PER_SLOT);
            assert_eq!(projected.runtime, RUNTIME_ANON_BYTES);
        }
        // 4K is 384 MiB and 16K is 1,536 MiB, the two figures the docs quote.
        assert_eq!(4096u64 * 96 * 1024, 384 << 20);
        assert_eq!(16_384u64 * 96 * 1024, 1536 << 20);
    }

    /// The expert term is not a restatement of the pool's sizing rule; it is
    /// the pool's sizing rule. Built small enough to allocate for real, so
    /// the claim is checked against the slab rather than against a comment.
    #[test]
    fn the_expert_term_is_the_slab_the_pool_would_actually_allocate() {
        use crate::format::{FileEntry, LayerLayout, QuantInfo, RVMP_VERSION, SourceInfo};
        use std::collections::BTreeMap;

        // A deliberately unaligned stride in the middle: the pool charges its
        // page-aligned pitch, and a prediction that used the raw stride would
        // come up short here and nowhere else.
        let strides = [8192u64, 100, 4096];
        let per_slot = 8192 + 4096 + 4096;

        let mut arch = crate::io::testutil::fixture_arch();
        arch.n_layers = 3;
        arch.n_experts = 8;
        arch.top_k = 2;
        let manifest = Manifest {
            rvmp_version: RVMP_VERSION,
            model_id: "tiny".to_owned(),
            source: SourceInfo {
                hf_repo: "test/tiny".to_owned(),
                revision: "0".repeat(40),
                file: "tiny.gguf".to_owned(),
                sha256: "0".repeat(64),
            },
            arch,
            quant: QuantInfo {
                scheme: "gguf".to_owned(),
                tensor_types: BTreeMap::new(),
            },
            common_tensors: BTreeMap::new(),
            files: BTreeMap::from([(
                COMMON_FILE.to_owned(),
                FileEntry {
                    size: 4096,
                    sha256: "0".repeat(64),
                },
            )]),
        };
        let layout = ExpertsLayout {
            layers: strides
                .iter()
                .enumerate()
                .map(|(layer, &stride)| LayerLayout {
                    file: crate::format::layer_file_name(layer as u32),
                    stride,
                    n_experts: 8,
                    projections: Vec::new(),
                })
                .collect(),
        };

        // A budget that buys 3 slots exactly, and one that buys 3 with change
        // left over: the pool rounds down, so both must predict the same slab.
        for budget in [3 * per_slot, 3 * per_slot + per_slot - 1] {
            let projected = Footprint::project(&manifest, &layout, budget, 16).unwrap();
            let pool = SlotPool::new(3, &strides).unwrap();
            assert_eq!(
                projected.experts,
                pool.total_bytes() as u64,
                "predicted slab for a {budget}-byte budget"
            );
            assert_eq!(projected.experts, 3 * per_slot);
        }
    }

    /// A context cap the arithmetic cannot even represent must come back as
    /// the typed error [`KvCache::new`] would have raised, never as a wrapped
    /// product that looks affordable.
    #[test]
    fn a_context_cap_near_usize_max_is_an_error_not_an_overflow() {
        let (manifest, layout) = v0_install();
        // The v0 row is 512 elements wide, so anything past `usize::MAX / 512`
        // overflows the plane; `usize::MAX` overflows it by the widest margin
        // the type allows.
        for cap in [usize::MAX, usize::MAX / 2, usize::MAX / 512 + 1] {
            let err =
                Footprint::project(&manifest, &layout, crate::model::DEFAULT_CACHE_BYTES, cap)
                    .expect_err("a {cap}-token context cannot be sized");
            assert!(
                matches!(
                    err,
                    FootprintError::Kv(crate::kv::KvError::InvalidDims { .. })
                ),
                "cap {cap} gave {err}"
            );
        }
        // And a zero cap is still the degenerate-geometry error, not a
        // zero-byte cache that silently projects as affordable.
        let err = Footprint::project(&manifest, &layout, crate::model::DEFAULT_CACHE_BYTES, 0)
            .expect_err("a zero context cannot be sized");
        assert!(
            matches!(
                err,
                FootprintError::Kv(crate::kv::KvError::InvalidDims { .. })
            ),
            "{err}"
        );
    }

    /// The verdict, at the boundary. Exactly meeting the ceiling is what the
    /// arithmetic calls a fit; one byte past it is not. Nothing here is
    /// allowed to be conservative on top of that — see `RUNTIME_ANON_BYTES`
    /// for the two residuals a fudge factor would be guessing at.
    #[test]
    fn the_verdict_is_the_arithmetic_and_nothing_more() {
        let footprint = Footprint {
            common: 1000,
            experts: 1000,
            kv: 1000,
            runtime: 1000,
            context_cap: 8,
        };
        assert_eq!(footprint.total(), 4000);
        assert!(footprint.fits_within(4001));
        assert!(footprint.fits_within(4000), "an exact fit is a fit");
        assert!(!footprint.fits_within(3999));

        // The sum is 128-bit, so four maximal tenants report rather than wrap.
        let huge = Footprint {
            common: u64::MAX,
            experts: u64::MAX,
            kv: u64::MAX,
            runtime: u64::MAX,
            context_cap: usize::MAX,
        };
        assert_eq!(huge.total(), 4 * u128::from(u64::MAX));
        assert!(!huge.fits_within(u64::MAX));
    }

    /// The breakdown reads the way the memory contract is written, because
    /// its only job is telling an operator which dial is theirs to move.
    #[test]
    fn the_breakdown_names_every_tenant_in_the_contract_s_units() {
        let (manifest, layout) = v0_install();
        let projected = Footprint::project(
            &manifest,
            &layout,
            crate::model::DEFAULT_CACHE_BYTES,
            16_384,
        )
        .unwrap();
        assert_eq!(
            projected.to_string(),
            "about 5,159 MiB (common 1,023 + experts 2,485 + KV 1,536 \
             at 16384 tokens + runtime 115)"
        );
    }

    #[test]
    fn mib_rounds_to_nearest_and_groups_by_threes() {
        assert_eq!(mib(0), "0");
        assert_eq!(mib(MIB / 2 - 1), "0");
        assert_eq!(mib(MIB / 2), "1", "rounds to nearest, not down");
        assert_eq!(mib(MIB), "1");
        assert_eq!(mib(u128::from(V0_COMMON_BYTES)), "1,023");
        assert_eq!(mib(u128::from(11 * V0_PER_SLOT)), "1,439");
        assert_eq!(mib(u128::from(RUNTIME_ANON_BYTES)), "115");
        assert_eq!(mib(u128::from(CGROUP_3G)), "3,072");
        assert_eq!(mib(1 << 40), "1,048,576");
    }

    /// The provisional row, pinned so a silent edit to a measured-and-caveated
    /// constant cannot pass review as a rounding tidy-up.
    #[test]
    fn the_anonymous_runtime_row_is_exp_012_s_measurement() {
        assert_eq!(RUNTIME_ANON_BYTES, 120_691_097);
        assert_eq!(mib(u128::from(RUNTIME_ANON_BYTES)), "115");
        // 115.1 MiB to the precision the figure is quoted at.
        let hundredths = u128::from(RUNTIME_ANON_BYTES) * 100 / MIB;
        assert_eq!(hundredths, 11_509);
    }

    /// A manifest without a `common.bin` entry is metadata this crate does
    /// not trust, so it reports rather than indexes.
    #[test]
    fn a_manifest_missing_its_common_entry_reports_rather_than_panics() {
        let (mut manifest, layout) = v0_install();
        manifest.files.clear();
        let err = Footprint::project(&manifest, &layout, crate::model::DEFAULT_CACHE_BYTES, 4096)
            .unwrap_err();
        assert!(
            matches!(
                err,
                FootprintError::Io(IoError::Format(
                    crate::format::FormatError::MissingFileEntry(ref name)
                )) if name == COMMON_FILE
            ),
            "{err}"
        );
    }

    /// [`resident_ceiling`] and the pool's own probe must be the same number,
    /// or the broad check and the narrow one are judging against different
    /// ceilings.
    #[test]
    fn the_public_ceiling_is_the_pool_s_own_probe() {
        assert_eq!(resident_ceiling(), resident_limit());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn the_resident_limit_probe_reports_something_plausible() {
        let limit = resident_limit().expect("Linux always reports MemTotal");
        assert!(
            limit >= 64 << 20,
            "implausible resident limit {limit}; the probe is misreading the kernel"
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn budget_probe_parsers_read_the_kernel_formats() {
        assert_eq!(parse_memory_max("3221225472\n"), Some(3 << 30));
        assert_eq!(parse_memory_max("max\n"), None);
        assert_eq!(parse_memory_max("garbage"), None);

        assert_eq!(
            parse_mem_total("MemTotal:       15914637 kB\nMemFree: 12 kB\n"),
            Some(16_296_588_288)
        );
        assert_eq!(parse_mem_total("MemFree: 12 kB\n"), None);
        assert_eq!(parse_mem_total("MemTotal:\n"), None);

        assert_eq!(
            parse_cgroup_v2_path("0::/user.slice/session.scope\n"),
            Some("/user.slice/session.scope")
        );
        // A cgroup v1 line is not a v2 path.
        assert_eq!(parse_cgroup_v2_path("7:memory:/foo\n"), None);

        assert_eq!(
            cgroup_ancestors("/user.slice/session.scope"),
            ["/user.slice/session.scope", "/user.slice", ""]
        );
        assert_eq!(cgroup_ancestors("/"), ["/", ""]);
    }

    #[test]
    fn error_messages_name_the_problem() {
        assert_eq!(
            SlotError::Exhausted {
                layer: 7,
                slots_per_layer: 12
            }
            .to_string(),
            "layer 7: all 12 slots are in use"
        );
        assert_eq!(
            SlotError::ZeroStride { layer: 3 }.to_string(),
            "layer 3: blob stride is zero"
        );
    }
}