inky-engine 2.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
//! Layer 3 paged KV block cache for `inky serve`:
//! - Shared GPU `BlockPools` (`Window` + `Full`) with zero-copy block sharing across lanes
//! - `EntryTree` (`PrefixTree<BlockHandles>`) + `RetainedStart` checkpoints (`EVERY` + `PROMPT`)
//! - Exact LRU eviction of retained start points on pool pressure (never grows or panics)
//! - Pool-pressure admission guard keeping GPU memory bounded inside Metal working set

use crate::blockbook::{EVERY, PROMPT};
use crate::blocks::{BlockEntry, BlockIndex, BlockKind, BlockPools, BlockTable, Slot, BLOCK, FULL_PASSES, NKV, WINDOW};
use crate::engine::EXT;
use crate::prefix::{BlockHandles, EntryTree, PrefixTree, SealedId};
use crate::spill::{
    read_block_from_dir, RawDiskRead, ReadOutcome, Sha256, SpillBlockKind, SpillKey, SpillStore, WriteOutcome,
};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

#[cfg(standalone_blocks)]
#[path = "block_cache/trace.rs"]
pub(crate) mod trace;

pub const KINDS: [BlockKind; 2] = [BlockKind::Window, BlockKind::Full];

/// Periodic checkpoint stride for the first `EARLY_EVERY_LIMIT` tokens so shared system+tools
/// prompts (e.g. OpenCode ~8,500 tokens) are cached in large 2048-token tensor chunks.
pub const EARLY_EVERY_TOKENS: usize = 2048;
/// Above `EARLY_EVERY_LIMIT`, periodic checkpoints widen to 4096 tokens for full-chunk prefill.
pub const LATE_EVERY_TOKENS: usize = 4096;
pub const EARLY_EVERY_LIMIT: usize = 16384;

/// Maximum decode tokens reserved per request in the admission pool-pressure guard.
pub const MAX_ADMIT_DECODE_RESERVE: usize = 4096;

/// Maximum retained spilled start-point metadata entries tracked on disk.
pub const DEFAULT_MAX_SPILLED_STARTS: usize = 512;

/// Maximum concurrent host staging bytes buffered by the background SSD restore worker
/// (`512 MiB`, strictly `< 15%` of the 4 GiB safety headroom even at 128K context).
pub const MAX_INFLIGHT_RESTORE_STAGING_BYTES: usize = 512 * 1024 * 1024;
const SPILL_INDEX_MAGIC: [u8; 8] = *b"INKYSPID";
const SPILL_INDEX_VERSION: u32 = 3;
const SPILL_INDEX_HEADER_LEN: usize = 84;
const SPILL_INDEX_PREFIX_LEN: usize = 52;
const MAX_SPILL_INDEX_BYTES: usize = 64 * 1024 * 1024;

/// Default host-RAM cap for retained checkpoint copies (`cs` + `toks` + `entries`).
pub const DEFAULT_MAX_RETAINED_HOST_BYTES: u64 = 512 << 20;

/// Default wall-clock deadline for spilling one checkpoint to `--spill-dir` (aligned with
/// `DEFAULT_GPU_STEP_TIMEOUT` / `DEFAULT_SCHEDULER_STALL_THRESHOLD` so multi-block fsyncs on
/// large checkpoints or virtualized CI runners do not prematurely abort mid-spill).
pub const DEFAULT_SPILL_WRITE_TIMEOUT: Duration = Duration::from_secs(30);

/// Leading SWA + `cs` boundary ramp (`16` blocks = `1,024` tokens = `EXT`) prefilled normally at
/// `[s_start .. stitch_start)` before switching to stitched `Full` K/V blocks: ensures all 40 SWA
/// layers (`EXT = 1,024`) inside `[stitch_start .. heal_start)` are 100% blind to the caller's
/// private prefix `[0 .. s_start)`.
pub const LEFT_HEAL_TOKENS: usize = 16 * BLOCK;

/// Minimum trailing healing ramp (`24` blocks = `1,536` tokens = `512` pre-window shock-absorber
/// tokens + `1,024` `EXT` SWA window tokens) recomputed after every Zero-RoPE `Full`-KV stitch:
/// tokens in `[heal_start .. heal_start + 512)` absorb the zeroed `Window` guard / reset-`cs` edge
/// strictly *outside* `span_end`'s trailing `1,024`-token SWA window `[span_end - 1,024 .. span_end)`.
pub const MIN_HEAL_TOKENS: usize = 24 * BLOCK;

/// Minimum contiguous shared span length (`42` blocks = `2,688` tokens) eligible for Zero-RoPE
/// shifted-span KV stitching (`--kv-stitch` / `--ikv-dir`). Guarantees `heal_start >= stitch_start + 64`
/// for every possible unaligned offset `s_start % 64 in 0..64` while reserving `>= LEFT_HEAL_TOKENS`
/// (`1,024` tokens) at the left SWA boundary and `>= MIN_HEAL_TOKENS` (`1,536` tokens) at the right.
pub const MIN_STITCH_TOKENS: usize = LEFT_HEAL_TOKENS + MIN_HEAL_TOKENS + 2 * BLOCK;

const STITCH_ROLL_BASE: u64 = 0x9e37_79b9_7f4a_7c15;
const STITCH_ROLL_BASE_POW_63: u64 = {
    let mut p = 1u64;
    let mut i = 0;
    while i < BLOCK - 1 {
        p = p.wrapping_mul(STITCH_ROLL_BASE);
        i += 1;
    }
    p
};
const MAX_STITCH_BUCKET_LEN: usize = 16;

#[inline]
fn mix_stitch_token(t: u32) -> u64 {
    let mut z = (t as u64).wrapping_add(0x9e37_79b9_7f4a_7c15);
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

/// Exact rolling 64-token polynomial hash (`sum_{k=0..63} mix(chunk[k]) * BASE^(63 - k)` mod `2^64`).
#[inline]
pub fn stitch_hash_64(chunk: &[u32]) -> u64 {
    debug_assert_eq!(chunk.len(), BLOCK);
    let mut h = 0u64;
    for &t in chunk {
        h = h.wrapping_mul(STITCH_ROLL_BASE).wrapping_add(mix_stitch_token(t));
    }
    h
}

/// Slide `h = stitch_hash_64(window)` forward by one token (`leaving = window[0]`, `entering = next_tok`).
#[inline]
pub fn slide_stitch_hash_64(h: u64, leaving: u32, entering: u32) -> u64 {
    let without_first = h.wrapping_sub(mix_stitch_token(leaving).wrapping_mul(STITCH_ROLL_BASE_POW_63));
    without_first.wrapping_mul(STITCH_ROLL_BASE).wrapping_add(mix_stitch_token(entering))
}

fn copy_full_slot_rows(
    src_slot: &[u8],
    src_ib: usize,
    dst_slot: &mut [u8],
    dst_ib: usize,
    count: usize,
    kvb: u32,
) {
    if count == 0 {
        return;
    }
    let mode = crate::blocks::KvMode::from_kvb_tag(kvb).unwrap_or_else(|_| panic!("invalid kvb {kvb}"));
    assert!(src_ib + count <= BLOCK && dst_ib + count <= BLOCK, "in-block slice out of range");
    let row = mode.row_bytes() as usize;
    let head_bytes = BLOCK * row;
    let total_heads = FULL_PASSES * 2 * NKV;
    assert_eq!(src_slot.len(), total_heads * head_bytes);
    assert_eq!(dst_slot.len(), total_heads * head_bytes);
    if src_ib == 0 && dst_ib == 0 && count == BLOCK {
        dst_slot.copy_from_slice(src_slot);
        return;
    }
    let copy_len = count * row;
    let src_in_head = src_ib * row;
    let dst_in_head = dst_ib * row;
    for h in 0..total_heads {
        let base = h * head_bytes;
        dst_slot[base + dst_in_head..base + dst_in_head + copy_len]
            .copy_from_slice(&src_slot[base + src_in_head..base + src_in_head + copy_len]);
    }
}

/// Backing source for a planned shifted-span `Full`-KV stitch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchSource {
    Retained { sid: SealedId, src_start: usize },
    Ikv { cart_idx: usize, src_start: usize },
}

/// One planned `[stitch_start .. heal_start)` `Full`-KV stitch inside a shared span
/// `[span_start .. span_end)`, preceded by the `>= 1,024`-token left SWA ramp
/// `[span_start .. stitch_start)` and followed by the `>= 1,536`-token right healing ramp
/// `[heal_start .. span_end)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StitchSpanPlan {
    pub span_start: usize,
    pub stitch_start: usize,
    pub heal_start: usize,
    pub span_end: usize,
    pub source: StitchSource,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchApplyOutcome {
    Applied { stitched_tokens: usize, zero_copy_blocks: usize },
    SourceGone,
    PoolBusy,
}

/// Outcome of starting a stitch plan on the scheduler loop:
/// - `Retained` sources execute immediately in RAM (`Applied`).
/// - `Ikv` sources stream `F_NOCACHE` `pread` + per-page `SHA-256` verification on the background
///   `IkvStageWorker` (`Staging`) so active GPU decode/prefill ticks on other lanes never stall.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchStartOutcome {
    Applied { stitched_tokens: usize, zero_copy_blocks: usize },
    Staging,
    SourceGone,
    PoolBusy,
}

/// Completed background `.ikv` stitch stage drained via [`ServeBlockCache::poll_ikv_stages`].
#[derive(Debug)]
pub struct CompletedIkvStage {
    pub lane: usize,
    pub stitched_tokens: Option<usize>,
    pub heal_start: usize,
    pub elapsed: Duration,
    pub corrupt_fallback: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CacheError {
    PoolExhausted(BlockKind),
}

impl std::fmt::Display for CacheError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CacheError::PoolExhausted(kind) => write!(f, "KV block pool exhausted ({kind:?})"),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheStats {
    pub slots_taken: u64,
    pub slots_reused: u64,
    pub blocks_sealed: u64,
    pub shared_dedups: u64,
    pub start_points_saved: u64,
    pub start_points_evicted: u64,
    pub start_matches: u64,
    pub cached_tokens_total: u64,
    pub window_pruned: u64,
    pub admit_deferred_pool_pressure: u64,
    pub step_deferred_pool_pressure: u64,
    pub singleflight_rebinds: u64,
    pub singleflight_saved_tokens: u64,
    pub starts_spilled: u64,
    pub starts_restored: u64,
    pub corrupt_fallbacks: u64,
    pub last_restore_us: u64,
    pub restore_us_total: u64,
    pub lanes_released: u64,
    pub spill_maint_passes: u64,
    pub spill_maint_evictions: u64,
    pub spill_write_timeouts: u64,
    pub ikv_cartridges_loaded: u64,
    pub ikv_quarantined: u64,
    pub stitch_hits: u64,
    pub stitched_tokens_total: u64,
}

/// Per-lane Layer 3 tracking state (lives alongside `Lane` inside `LaneS`).
#[derive(Default, Debug)]
pub struct LaneBlockState {
    pub namespace: u64,
    pub sealed: Vec<SealedId>,
    pub prompt_len: usize,
    pub written: usize,
    /// True once this lane has applied any Zero-RoPE shifted-span stitch (`--kv-stitch` / `--ikv-dir`).
    /// Enforces strict provenance isolation: once `true`, neither stitched blocks nor post-stitch
    /// prefill blocks are ever inserted into `EntryTree` or saved as `RetainedStart` checkpoints,
    /// guaranteeing exact non-stitching requests never inherit approximate K/V and stitches never chain.
    pub(crate) stitched_approx: bool,
    pub(crate) bound_lane: Option<usize>,
}

struct RetainedStart {
    namespace: u64,
    pos: usize,
    cs: Vec<u8>,
    reasons: u8,
    entries: Vec<(BlockKind, BlockIndex, BlockEntry)>,
    toks: Vec<u32>,
    last_used_tick: u64,
}

impl RetainedStart {
    fn host_bytes(&self) -> u64 {
        (self.cs.len() as u64).saturating_add((self.toks.len() as u64).saturating_mul(4)).saturating_add(
            (self.entries.len() as u64)
                .saturating_mul(std::mem::size_of::<(BlockKind, BlockIndex, BlockEntry)>() as u64),
        )
    }
}

struct SpilledStart {
    namespace: u64,
    pos: usize,
    reasons: u8,
    cs_key: SpillKey,
    entries: Vec<(BlockKind, BlockIndex, SpillKey)>,
    toks: Vec<u32>,
    last_used_tick: u64,
}

// Preserve the source files and shorter resident match while making room for a restore.
struct RestoreSource {
    spill_id: u64,
    keys: HashSet<SpillKey>,
    resident_start: Option<SealedId>,
}

/// Result of binding an admitted lane: either immediately ready in RAM (`Some` / `None`)
/// or asynchronously restoring a deeper spilled checkpoint from SSD (`Restoring`).
#[derive(Debug)]
pub enum AdmitBindOutcome {
    Immediate(Option<(usize, Vec<u8>)>),
    Restoring { target_pos: usize },
}

/// Completed background SSD restore ready to transition `Restoring -> Ready`.
#[derive(Debug)]
pub struct CompletedRestore {
    pub lane: usize,
    pub matched: Option<(usize, Vec<u8>)>,
    pub elapsed: Duration,
    pub corrupt_fallback: bool,
}

struct RestoreJob {
    lane: usize,
    restore_seq: u64,
    dir: PathBuf,
    kvb: u32,
    cs_key: SpillKey,
    blocks: Vec<(usize, SpillKey, usize)>,
    cancel_flag: Arc<AtomicBool>,
    began: Instant,
}

enum RestoreMsgPayload {
    RecurrentState { key: SpillKey, raw: RawDiskRead },
    Block { idx: usize, key: SpillKey, raw: RawDiskRead },
    Done { elapsed: Duration },
    Aborted { key: SpillKey, raw: RawDiskRead },
}

struct RestoreMsg {
    lane: usize,
    restore_seq: u64,
    budget_bytes: usize,
    payload: RestoreMsgPayload,
}

struct StagingBudget {
    inner: Mutex<usize>,
    cvar: Condvar,
}

impl StagingBudget {
    fn new() -> Self {
        Self { inner: Mutex::new(0), cvar: Condvar::new() }
    }

    fn acquire(&self, bytes: usize, cancel: &AtomicBool) -> bool {
        if bytes == 0 {
            return !cancel.load(Ordering::Acquire);
        }
        let capped = bytes.min(MAX_INFLIGHT_RESTORE_STAGING_BYTES);
        let mut used = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        loop {
            if cancel.load(Ordering::Acquire) {
                return false;
            }
            if *used == 0 || used.saturating_add(capped) <= MAX_INFLIGHT_RESTORE_STAGING_BYTES {
                *used = used.saturating_add(capped);
                return true;
            }
            let (next, _) = self.cvar.wait_timeout(used, Duration::from_millis(5)).unwrap_or_else(|e| e.into_inner());
            used = next;
        }
    }

    fn release(&self, bytes: usize) {
        if bytes == 0 {
            return;
        }
        let capped = bytes.min(MAX_INFLIGHT_RESTORE_STAGING_BYTES);
        let mut used = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        *used = used.saturating_sub(capped);
        self.cvar.notify_all();
    }
}

struct RestoreWake {
    seq: Mutex<u64>,
    cvar: Condvar,
}

impl RestoreWake {
    fn new() -> Self {
        Self { seq: Mutex::new(0), cvar: Condvar::new() }
    }

    fn notify(&self) {
        let mut g = self.seq.lock().unwrap_or_else(|e| e.into_inner());
        *g = g.wrapping_add(1);
        self.cvar.notify_all();
    }

    fn wait_timeout(&self, last_seen: &mut u64, timeout: Duration) {
        let g = self.seq.lock().unwrap_or_else(|e| e.into_inner());
        if *g != *last_seen {
            *last_seen = *g;
            return;
        }
        let (g2, _) = self.cvar.wait_timeout(g, timeout).unwrap_or_else(|e| e.into_inner());
        *last_seen = *g2;
    }
}

struct RestoreWorker {
    job_tx: Option<Sender<RestoreJob>>,
    msg_rx: Receiver<RestoreMsg>,
    budget: Arc<StagingBudget>,
    join: Option<std::thread::JoinHandle<()>>,
}

impl RestoreWorker {
    fn spawn(wake_bg: Arc<RestoreWake>) -> Self {
        let (job_tx, job_rx) = channel::<RestoreJob>();
        let (msg_tx, msg_rx) = channel::<RestoreMsg>();
        let budget = Arc::new(StagingBudget::new());
        let budget_bg = budget.clone();
        let join = std::thread::Builder::new()
            .name("inky-spill-restore".into())
            .spawn(move || {
                while let Ok(job) = job_rx.recv() {
                    if job.cancel_flag.load(Ordering::Acquire) {
                        continue;
                    }
                    let cs_est = crate::spill::MAX_RECURRENT_STATE_BYTES.min(4 * 1024 * 1024);
                    if !budget_bg.acquire(cs_est, &job.cancel_flag) {
                        continue;
                    }
                    let cs_raw = read_block_from_dir(&job.dir, job.kvb, job.cs_key, Some(0));
                    if job.cancel_flag.load(Ordering::Acquire) {
                        budget_bg.release(cs_est);
                        continue;
                    }
                    let cs_ok = matches!(
                        &cs_raw.outcome,
                        ReadOutcome::Hit(blk) if blk.recurrent_state.as_ref().is_some_and(|s| !s.is_empty())
                    );
                    if !cs_ok {
                        if msg_tx
                            .send(RestoreMsg {
                                lane: job.lane,
                                restore_seq: job.restore_seq,
                                budget_bytes: cs_est,
                                payload: RestoreMsgPayload::Aborted { key: job.cs_key, raw: cs_raw },
                            })
                            .is_err()
                        {
                            budget_bg.release(cs_est);
                            break;
                        }
                        wake_bg.notify();
                        continue;
                    }
                    if msg_tx
                        .send(RestoreMsg {
                            lane: job.lane,
                            restore_seq: job.restore_seq,
                            budget_bytes: cs_est,
                            payload: RestoreMsgPayload::RecurrentState { key: job.cs_key, raw: cs_raw },
                        })
                        .is_err()
                    {
                        budget_bg.release(cs_est);
                        break;
                    }
                    wake_bg.notify();

                    let mut aborted = false;
                    for (idx, key, expected_len) in job.blocks {
                        if !budget_bg.acquire(expected_len, &job.cancel_flag) {
                            aborted = true;
                            break;
                        }
                        let raw = read_block_from_dir(&job.dir, job.kvb, key, Some(expected_len));
                        if job.cancel_flag.load(Ordering::Acquire) {
                            budget_bg.release(expected_len);
                            aborted = true;
                            break;
                        }
                        let hit = matches!(&raw.outcome, ReadOutcome::Hit(_));
                        let payload = if hit {
                            RestoreMsgPayload::Block { idx, key, raw }
                        } else {
                            RestoreMsgPayload::Aborted { key, raw }
                        };
                        if msg_tx
                            .send(RestoreMsg {
                                lane: job.lane,
                                restore_seq: job.restore_seq,
                                budget_bytes: expected_len,
                                payload,
                            })
                            .is_err()
                        {
                            budget_bg.release(expected_len);
                            return;
                        }
                        wake_bg.notify();
                        if !hit {
                            aborted = true;
                            break;
                        }
                    }
                    if !aborted && !job.cancel_flag.load(Ordering::Acquire) {
                        if msg_tx
                            .send(RestoreMsg {
                                lane: job.lane,
                                restore_seq: job.restore_seq,
                                budget_bytes: 0,
                                payload: RestoreMsgPayload::Done { elapsed: job.began.elapsed() },
                            })
                            .is_err()
                        {
                            return;
                        }
                        wake_bg.notify();
                    }
                }
            })
            .expect("spawn inky-spill-restore worker");
        Self { job_tx: Some(job_tx), msg_rx, budget, join: Some(join) }
    }
}

impl Drop for RestoreWorker {
    fn drop(&mut self) {
        self.job_tx.take();
        while let Ok(msg) = self.msg_rx.try_recv() {
            self.budget.release(msg.budget_bytes);
        }
        if let Some(j) = self.join.take() {
            let _ = j.join();
        }
    }
}

struct IkvStageJob {
    lane: usize,
    stage_seq: u64,
    lane_namespace: u64,
    expected_namespace: u64,
    catalog: Arc<crate::ikv::IkvCatalog>,
    cart_idx: usize,
    src_start: usize,
    n_stitch_blks: usize,
    cancel_flag: Arc<AtomicBool>,
    began: Instant,
}

enum IkvStagePayload {
    Block { idx: usize, bytes: Vec<u8> },
    Done { elapsed: Duration },
    Aborted { elapsed: Duration },
}

struct IkvStageMsg {
    lane: usize,
    stage_seq: u64,
    budget_bytes: usize,
    payload: IkvStagePayload,
}

struct IkvStageWorker {
    job_tx: Option<Sender<IkvStageJob>>,
    msg_rx: Receiver<IkvStageMsg>,
    budget: Arc<StagingBudget>,
    join: Option<std::thread::JoinHandle<()>>,
}

impl IkvStageWorker {
    fn spawn(wake_bg: Arc<RestoreWake>) -> Self {
        let (job_tx, job_rx) = channel::<IkvStageJob>();
        let (msg_tx, msg_rx) = channel::<IkvStageMsg>();
        let budget = Arc::new(StagingBudget::new());
        let budget_bg = budget.clone();
        let join = std::thread::Builder::new()
            .name("inky-ikv-stage".into())
            .spawn(move || {
                while let Ok(job) = job_rx.recv() {
                    if job.cancel_flag.load(Ordering::Acquire) {
                        continue;
                    }
                    let Some(cart) = job.catalog.get(job.cart_idx) else {
                        let _ = msg_tx.send(IkvStageMsg {
                            lane: job.lane,
                            stage_seq: job.stage_seq,
                            budget_bytes: 0,
                            payload: IkvStagePayload::Aborted { elapsed: job.began.elapsed() },
                        });
                        wake_bg.notify();
                        continue;
                    };
                    let mut chan_closed = false;
                    let res = cart.stream_full_span_blocks(
                        job.lane_namespace,
                        job.expected_namespace,
                        job.src_start,
                        job.n_stitch_blks,
                        &job.cancel_flag,
                        |idx, bytes| {
                            let len = bytes.len();
                            if !budget_bg.acquire(len, &job.cancel_flag) {
                                return Ok(());
                            }
                            if job.cancel_flag.load(Ordering::Acquire) {
                                budget_bg.release(len);
                                return Ok(());
                            }
                            if msg_tx
                                .send(IkvStageMsg {
                                    lane: job.lane,
                                    stage_seq: job.stage_seq,
                                    budget_bytes: len,
                                    payload: IkvStagePayload::Block { idx, bytes },
                                })
                                .is_err()
                            {
                                budget_bg.release(len);
                                chan_closed = true;
                                return Err(crate::ikv::IkvError::Quarantined);
                            }
                            wake_bg.notify();
                            Ok(())
                        },
                    );
                    if chan_closed {
                        return;
                    }
                    if job.cancel_flag.load(Ordering::Acquire) {
                        continue;
                    }
                    let payload = match res {
                        Ok(()) => IkvStagePayload::Done { elapsed: job.began.elapsed() },
                        Err(_) => IkvStagePayload::Aborted { elapsed: job.began.elapsed() },
                    };
                    if msg_tx
                        .send(IkvStageMsg {
                            lane: job.lane,
                            stage_seq: job.stage_seq,
                            budget_bytes: 0,
                            payload,
                        })
                        .is_err()
                    {
                        return;
                    }
                    wake_bg.notify();
                }
            })
            .expect("spawn inky-ikv-stage worker");
        Self { job_tx: Some(job_tx), msg_rx, budget, join: Some(join) }
    }
}

impl Drop for IkvStageWorker {
    fn drop(&mut self) {
        self.job_tx.take();
        while let Ok(msg) = self.msg_rx.try_recv() {
            self.budget.release(msg.budget_bytes);
        }
        if let Some(j) = self.join.take() {
            let _ = j.join();
        }
    }
}

struct PendingIkvStage {
    stage_seq: u64,
    plan: StitchSpanPlan,
    reserved_slots: Vec<(Slot, u32)>,
    loaded_blocks: usize,
    cancel_flag: Arc<AtomicBool>,
}

struct PendingRestore {
    restore_seq: u64,
    spill_id: u64,
    namespace: u64,
    pos: usize,
    reasons: u8,
    full_toks: Vec<u32>,
    protected_keys: Vec<SpillKey>,
    held_reused: Vec<(BlockKind, BlockIndex, BlockEntry)>,
    reserved_slots: Vec<(BlockKind, BlockIndex, BlockEntry)>,
    loaded_cs: Option<Vec<u8>>,
    loaded_blocks: usize,
    cancel_flag: Arc<AtomicBool>,
}

/// Only blocks leaving the sliding window during this span need their table entries cleared.
/// A cached prefix binds the still-live window at its checkpoint, so the same range applies on a hit.
fn newly_expired_window_blocks(start: usize, end: usize) -> std::ops::Range<usize> {
    let first_needed = |pos: usize| pos.saturating_sub(EXT - 1) / BLOCK;
    first_needed(start)..first_needed(end)
}

fn to_spill_kind(kind: BlockKind) -> SpillBlockKind {
    match kind {
        BlockKind::Full => SpillBlockKind::Full,
        BlockKind::Window => SpillBlockKind::Window,
    }
}

fn kind_idx(kind: BlockKind) -> usize {
    match kind {
        BlockKind::Window => 0,
        BlockKind::Full => 1,
    }
}

/// True when `end` (a multiple of `BLOCK`) is a periodic `EVERY` checkpoint boundary.
pub fn is_every_checkpoint(end: usize) -> bool {
    if end == 0 || !end.is_multiple_of(BLOCK) {
        return false;
    }
    if end <= EARLY_EVERY_LIMIT {
        end.is_multiple_of(EARLY_EVERY_TOKENS)
    } else {
        end.is_multiple_of(LATE_EVERY_TOKENS)
    }
}

/// Largest `EVERY` checkpoint boundary `<= n`, or `0` if `n < EARLY_EVERY_TOKENS`.
fn max_every_checkpoint_le(n: usize) -> usize {
    if n < EARLY_EVERY_TOKENS {
        0
    } else if n <= EARLY_EVERY_LIMIT {
        (n / EARLY_EVERY_TOKENS) * EARLY_EVERY_TOKENS
    } else {
        (n / LATE_EVERY_TOKENS) * LATE_EVERY_TOKENS
    }
}

fn count_every_checkpoints_le(limit: usize) -> usize {
    if limit < EARLY_EVERY_TOKENS {
        0
    } else if limit <= EARLY_EVERY_LIMIT {
        limit / EARLY_EVERY_TOKENS
    } else {
        EARLY_EVERY_LIMIT / EARLY_EVERY_TOKENS + (limit - EARLY_EVERY_LIMIT) / LATE_EVERY_TOKENS
    }
}

fn every_checkpoint_at(idx: usize) -> usize {
    let early_cnt = EARLY_EVERY_LIMIT / EARLY_EVERY_TOKENS;
    if idx < early_cnt {
        (idx + 1) * EARLY_EVERY_TOKENS
    } else {
        EARLY_EVERY_LIMIT + (idx + 1 - early_cnt) * LATE_EVERY_TOKENS
    }
}

/// Precompute compact cumulative 64-token block rolling hashes (`1 u64` per complete 64-token
/// block, `out.len() == toks.len() / BLOCK`). `out[b]` summarizes `toks[..(b + 1) * BLOCK]` so
/// checkpoint prefix equality reduces to `O(1)` `u64` lookup + binary search with a single
/// boundary slice verification.
pub fn compute_block_hashes(toks: &[u32]) -> Vec<u64> {
    let n_blocks = toks.len() / BLOCK;
    let mut out = Vec::with_capacity(n_blocks);
    let mut h = 0x9e37_79b9_7f4a_7c15u64;
    for b in 0..n_blocks {
        let blk = &toks[b * BLOCK..(b + 1) * BLOCK];
        let mut i = 0usize;
        while i + 2 <= BLOCK {
            let pair = u64::from(blk[i]) | (u64::from(blk[i + 1]) << 32);
            h ^= pair.wrapping_add(0x517c_c1b7_2722_0a95);
            h = h.rotate_left(29).wrapping_mul(0x94d0_49bb_1331_11eb);
            i += 2;
        }
        h ^= h >> 32;
        out.push(h);
    }
    out
}

/// Summary of an active prefilling lane for singleflight leader election and admission accounting.
#[derive(Clone, Copy, Debug)]
pub struct InflightPrefillLane<'a> {
    pub lane: usize,
    pub namespace: u64,
    pub toks: &'a [u32],
    pub block_hashes: Option<&'a [u64]>,
    pub n_past: usize,
    pub pf_end: usize,
    pub runnable: bool,
    pub eligible_follower: bool,
}

/// A producer must share the follower's cache namespace, be strictly ahead in
/// (progress, reverse lane ID), and seal the checkpoint where this follower waits.
fn can_lead_meta(me: &InflightPrefillLane<'_>, producer: &InflightPrefillLane<'_>, next: usize) -> bool {
    if me.namespace != producer.namespace
        || !me.runnable
        || !me.eligible_follower
        || next <= me.n_past
        || next >= me.pf_end
        || !producer.runnable
        || producer.n_past >= next
        || next >= producer.pf_end
    {
        return false;
    }
    let ahead = producer.n_past > me.n_past || (producer.n_past == me.n_past && producer.lane < me.lane);
    let prompt_checkpoint = (producer.pf_end - 1) / BLOCK * BLOCK;
    ahead && (is_every_checkpoint(next) || next == prompt_checkpoint)
}

/// A producer must be strictly ahead in (progress, reverse lane ID) and must seal the
/// checkpoint where this follower actually waits. Use the same rule in admission and scheduling.
fn can_lead(me: &InflightPrefillLane<'_>, producer: &InflightPrefillLane<'_>, next: usize) -> bool {
    if !can_lead_meta(me, producer, next) {
        return false;
    }
    let next_bi = next / BLOCK - 1;
    if let (Some(mh), Some(ph)) =
        (me.block_hashes.and_then(|h| h.get(next_bi)), producer.block_hashes.and_then(|h| h.get(next_bi)))
    {
        if mh != ph {
            return false;
        }
    }
    std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr()) || producer.toks[..next] == me.toks[..next]
}

#[cfg(any(test, standalone_blocks))]
pub fn find_prefill_leader(lanes: &[InflightPrefillLane<'_>], idx: usize) -> Option<usize> {
    let me = lanes.get(idx)?;
    let next = effective_pf_target(me.n_past, me.pf_end);
    lanes.iter().find(|producer| can_lead(me, producer, next)).map(|producer| producer.lane)
}

/// Single-pass leader election across all active prefilling lanes using precomputed 64-token
/// block hashes so followers sharing a `(next, hash)` bucket verify against one canonical leader
/// without all-pairs token slice scans.
pub fn find_prefill_leaders(lanes: &[InflightPrefillLane<'_>]) -> Vec<Option<usize>> {
    let mut out = vec![None; lanes.len()];
    if lanes.len() <= 1 {
        return out;
    }
    let owned: Vec<Vec<u64>> = lanes
        .iter()
        .map(|l| if l.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(l.toks) })
        .collect();
    let hashes_of = |i: usize| -> &[u64] { lanes[i].block_hashes.unwrap_or(&owned[i]) };

    for (idx, me) in lanes.iter().enumerate() {
        let next = effective_pf_target(me.n_past, me.pf_end);
        if !me.runnable || !me.eligible_follower || next <= me.n_past || next >= me.pf_end {
            continue;
        }
        let next_bi = next / BLOCK - 1;
        let Some(&mh) = hashes_of(idx).get(next_bi) else {
            continue;
        };
        for (p_idx, producer) in lanes.iter().enumerate() {
            if !can_lead_meta(me, producer, next) {
                continue;
            }
            if hashes_of(p_idx).get(next_bi) != Some(&mh) {
                continue;
            }
            if std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr()) || producer.toks[..next] == me.toks[..next] {
                out[idx] = Some(producer.lane);
                break;
            }
        }
    }
    out
}

/// Reference exact pair shared checkpoint (used directly as collision fallback).
fn pair_shared_checkpoint_exact(
    me: &InflightPrefillLane<'_>,
    producer: &InflightPrefillLane<'_>,
    next: usize,
    final_checkpoint: usize,
) -> usize {
    if !can_lead(me, producer, next) {
        return 0;
    }
    let limit = me.pf_end.min(producer.pf_end) - 1;
    let common_final = final_checkpoint == (producer.pf_end - 1) / BLOCK * BLOCK;
    if common_final
        && (std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr())
            || me.toks[next..final_checkpoint] == producer.toks[next..final_checkpoint])
    {
        return final_checkpoint;
    }
    let last_periodic = max_every_checkpoint_le(limit);
    if last_periodic >= next {
        if std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr())
            || me.toks[next..last_periodic] == producer.toks[next..last_periodic]
        {
            return last_periodic;
        }
        let before = &me.toks[next..last_periodic];
        let after = &producer.toks[next..last_periodic];
        let common = next + before.iter().zip(after).take_while(|(a, b)| a == b).count();
        return max_every_checkpoint_le(common);
    }
    0
}

/// Candidate checkpoint depth between `(me, me_hashes)` and `(producer, prod_hashes)` using
/// ONLY `O(log(blocks))` `u64` block-hash lookups (zero token-slice comparisons).
fn pair_hash_candidate_checkpoint(
    me: &InflightPrefillLane<'_>,
    me_hashes: &[u64],
    producer: &InflightPrefillLane<'_>,
    prod_hashes: &[u64],
    next: usize,
    final_checkpoint: usize,
) -> usize {
    if !can_lead_meta(me, producer, next) {
        return 0;
    }
    let next_bi = next / BLOCK - 1;
    if me_hashes.get(next_bi) != prod_hashes.get(next_bi) || me_hashes.get(next_bi).is_none() {
        return 0;
    }
    let prod_final = (producer.pf_end - 1) / BLOCK * BLOCK;
    if final_checkpoint == prod_final && final_checkpoint >= next {
        let f_bi = final_checkpoint / BLOCK - 1;
        if me_hashes.get(f_bi).is_some() && me_hashes.get(f_bi) == prod_hashes.get(f_bi) {
            return final_checkpoint;
        }
    }
    let limit = me.pf_end.min(producer.pf_end) - 1;
    let cnt = count_every_checkpoints_le(limit);
    if cnt == 0 {
        return 0;
    }
    let mut lo_start = 0usize;
    while lo_start < cnt && every_checkpoint_at(lo_start) < next {
        lo_start += 1;
    }
    if lo_start >= cnt {
        return 0;
    }
    let first_bi = every_checkpoint_at(lo_start) / BLOCK - 1;
    if me_hashes.get(first_bi).is_none() || me_hashes.get(first_bi) != prod_hashes.get(first_bi) {
        return 0;
    }
    let mut lo = lo_start;
    let mut hi = cnt - 1;
    while lo < hi {
        let mid = lo + (hi - lo).div_ceil(2);
        let bi = every_checkpoint_at(mid) / BLOCK - 1;
        if me_hashes.get(bi).is_some() && me_hashes.get(bi) == prod_hashes.get(bi) {
            lo = mid;
        } else {
            hi = mid - 1;
        }
    }
    every_checkpoint_at(lo)
}

fn shared_checkpoint_against_hashed<'a>(
    me: &InflightPrefillLane<'_>,
    me_hashes: &[u64],
    producers: impl Iterator<Item = (&'a InflightPrefillLane<'a>, &'a [u64])> + Clone,
) -> usize {
    let next = effective_pf_target(me.n_past, me.pf_end);
    if !me.runnable || !me.eligible_follower || next <= me.n_past || next >= me.pf_end {
        return 0;
    }
    let final_checkpoint = me.pf_end.saturating_sub(1) / BLOCK * BLOCK;
    let mut best_ckpt = 0usize;
    let mut best_prod: Option<&InflightPrefillLane<'_>> = None;
    for (prod, ph) in producers.clone() {
        let cand = pair_hash_candidate_checkpoint(me, me_hashes, prod, ph, next, final_checkpoint);
        if cand > best_ckpt {
            best_ckpt = cand;
            best_prod = Some(prod);
            if best_ckpt == final_checkpoint {
                break;
            }
        }
    }
    let Some(winner) = best_prod else {
        return 0;
    };
    if std::ptr::eq(me.toks.as_ptr(), winner.toks.as_ptr()) || me.toks[..best_ckpt] == winner.toks[..best_ckpt] {
        return best_ckpt;
    }
    // Hash-collision fallback: exact check across producers preserves 100% parity.
    let mut exact_best = 0usize;
    for (prod, _) in producers {
        exact_best = exact_best.max(pair_shared_checkpoint_exact(me, prod, next, final_checkpoint));
        if exact_best == final_checkpoint {
            break;
        }
    }
    exact_best
}

/// Furthest checkpoint these lanes will rendezvous at before their inputs diverge.
/// A producer's final, nonperiodic PROMPT checkpoint only counts if the follower also stops there.
#[cfg(any(test, standalone_blocks))]
fn inflight_shared_checkpoint(me: &InflightPrefillLane<'_>, lanes: &[InflightPrefillLane<'_>]) -> usize {
    let me_owned;
    let me_hashes: &[u64] = match me.block_hashes {
        Some(h) => h,
        None => {
            me_owned = compute_block_hashes(me.toks);
            &me_owned
        }
    };
    let owned: Vec<Vec<u64>> = lanes
        .iter()
        .map(|l| if l.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(l.toks) })
        .collect();
    let iter = lanes.iter().enumerate().map(|(i, l)| (l, l.block_hashes.unwrap_or(&owned[i])));
    shared_checkpoint_against_hashed(me, me_hashes, iter)
}

/// Compute the capped prefill target for the current step so `finish_prefill_span` lands
/// cleanly on checkpoint boundaries (`2048`-token / `4096`-token `EVERY` boundaries and the
/// prompt's final `((pf_end - 1) / 64) * 64` `PROMPT` boundary) where `get_cs()` matches `end`.
pub fn effective_pf_target(n_past: usize, pf_end: usize) -> usize {
    if n_past >= pf_end || pf_end == 0 {
        return pf_end;
    }
    let prompt_ckpt = ((pf_end - 1) / BLOCK) * BLOCK;
    if n_past >= prompt_ckpt {
        return pf_end;
    }
    let stride = if n_past < EARLY_EVERY_LIMIT { EARLY_EVERY_TOKENS } else { LATE_EVERY_TOKENS };
    let next_every = ((n_past / stride) + 1) * stride;
    next_every.min(prompt_ckpt)
}

/// Summary of an active lane's remaining `Full` block demand for admission reservation.
#[derive(Clone, Copy, Debug)]
pub struct InflightLaneReserve<'a> {
    pub lane: usize,
    pub namespace: u64,
    pub toks: &'a [u32],
    pub block_hashes: Option<&'a [u64]>,
    pub n_past: usize,
    pub pf_end: usize,
    pub cached: usize,
    pub written: usize,
    pub gen: usize,
    pub max_gen: usize,
    pub runnable: bool,
}

impl<'a> InflightLaneReserve<'a> {
    fn reserved_end(&self) -> usize {
        let prompt_end = self.n_past.max(self.pf_end);
        // The first generated token comes from the final prompt row. For longer
        // replies, keep reserving the next bounded tranche after earlier tokens were emitted.
        prompt_end + self.max_gen.saturating_sub(self.gen.max(1)).min(MAX_ADMIT_DECODE_RESERVE)
    }

    fn as_prefill_lane(&self) -> Option<InflightPrefillLane<'a>> {
        (self.gen == 0 && self.n_past < self.pf_end).then_some(InflightPrefillLane {
            lane: self.lane,
            namespace: self.namespace,
            toks: self.toks,
            block_hashes: self.block_hashes,
            n_past: self.n_past,
            pf_end: self.pf_end,
            runnable: self.runnable,
            eligible_follower: self.n_past == self.cached && self.written == self.n_past,
        })
    }
}

struct PreparedPrefillEntry<'a> {
    pf: InflightPrefillLane<'a>,
    owned_hashes: Vec<u64>,
    written: usize,
    reserved_end_blocks: usize,
    credited: usize,
}

impl<'a> PreparedPrefillEntry<'a> {
    fn hashes(&self) -> &[u64] {
        self.pf.block_hashes.unwrap_or(&self.owned_hashes)
    }

    fn demanded_blocks(&self, credited: usize) -> usize {
        self.reserved_end_blocks - self.written.max(credited).div_ceil(BLOCK)
    }
}

type LastEvalCredited = (usize, u64, usize, usize, usize, usize);

/// Incremental admission cohort precomputed once per scheduler admission pass so each
/// candidate check runs in `O(prefilling_lanes * log(blocks))` with zero all-pairs rescans.
pub struct PreparedInflightCohort<'a> {
    len: usize,
    prefills: Vec<PreparedPrefillEntry<'a>>,
    base_reserved_full: usize,
    base_window_growth: usize,
    base_steady_window: usize,
    /// Cached `(usable_window, available_window, available_full)` headroom so bursts of
    /// candidate checks do not re-scan 10,000+ `BlockPool` records per queued job.
    cached_headroom: std::cell::Cell<Option<(usize, usize, usize)>>,
    /// Memoized `(toks_ptr, namespace, pf_end, n_past, lane, credited)` from the preceding `eval_with_candidate`
    /// so `push_admitted` commits in `O(1)` without repeating the boundary slice check.
    last_eval_credited: std::cell::Cell<Option<LastEvalCredited>>,
}

impl<'a> PreparedInflightCohort<'a> {
    pub fn empty() -> Self {
        Self {
            len: 0,
            prefills: Vec::new(),
            base_reserved_full: 0,
            base_window_growth: 0,
            base_steady_window: 0,
            cached_headroom: std::cell::Cell::new(None),
            last_eval_credited: std::cell::Cell::new(None),
        }
    }

    pub fn invalidate_headroom(&self) {
        self.cached_headroom.set(None);
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn new(active: &[InflightLaneReserve<'a>]) -> Self {
        let mut cohort = Self::empty();
        for &lane in active {
            cohort.push_admitted(lane);
        }
        cohort
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn reserved_full_slots(&self) -> usize {
        self.base_reserved_full
    }

    /// Evaluate total `reserved_inflight_full_slots` if `cand` were added to this cohort,
    /// touching only `O(prefilling_lanes * log(blocks))` hashes and at most one slice check.
    fn eval_with_candidate(&self, cand: &InflightLaneReserve<'_>, cand_hashes: &[u64]) -> (usize, usize, usize) {
        let cand_end = (cand.pf_end + cand.max_gen.saturating_sub(1)).div_ceil(BLOCK);
        let win_growth = self.base_window_growth + (cand_end - cand.written.div_ceil(BLOCK));
        let steady_win = self.base_steady_window + cand_end.min(WINDOW / BLOCK + 1);

        let cand_res_blocks = cand.reserved_end().div_ceil(BLOCK);
        let Some(cand_pf) = cand.as_prefill_lane() else {
            let full = self.base_reserved_full + (cand_res_blocks - cand.written.div_ceil(BLOCK));
            return (full, win_growth, steady_win);
        };

        // 1. Best existing producer for `cand_pf`.
        let cand_credited = if cand_pf.eligible_follower {
            let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
            shared_checkpoint_against_hashed(&cand_pf, cand_hashes, iter)
        } else {
            0
        };
        self.last_eval_credited.set(Some((
            cand.toks.as_ptr() as usize,
            cand.namespace,
            cand.pf_end,
            cand.n_past,
            cand.lane,
            cand_credited,
        )));
        let mut full = self.base_reserved_full + (cand_res_blocks - cand.written.max(cand_credited).div_ceil(BLOCK));

        // 2. Check if `cand_pf` is strictly ahead of any existing eligible follower (e.g. when
        //    reusing a lower-numbered idle lane or binding a deeper cached prefix).
        if cand_pf.runnable {
            for existing in &self.prefills {
                if !existing.pf.runnable || !existing.pf.eligible_follower {
                    continue;
                }
                let ahead = cand_pf.n_past > existing.pf.n_past
                    || (cand_pf.n_past == existing.pf.n_past && cand_pf.lane < existing.pf.lane);
                if !ahead {
                    continue;
                }
                let ex_next = effective_pf_target(existing.pf.n_past, existing.pf.pf_end);
                let ex_final = existing.pf.pf_end.saturating_sub(1) / BLOCK * BLOCK;
                let cand_for_ex = pair_hash_candidate_checkpoint(
                    &existing.pf,
                    existing.hashes(),
                    &cand_pf,
                    cand_hashes,
                    ex_next,
                    ex_final,
                );
                if cand_for_ex > existing.credited {
                    let verified = if std::ptr::eq(existing.pf.toks.as_ptr(), cand_pf.toks.as_ptr())
                        || existing.pf.toks[..cand_for_ex] == cand_pf.toks[..cand_for_ex]
                    {
                        cand_for_ex
                    } else {
                        pair_shared_checkpoint_exact(&existing.pf, &cand_pf, ex_next, ex_final)
                    };
                    let new_cred = existing.credited.max(verified);
                    if new_cred > existing.credited {
                        full = full + existing.demanded_blocks(new_cred) - existing.demanded_blocks(existing.credited);
                    }
                }
            }
        }

        (full, win_growth, steady_win)
    }

    /// Commit an admitted lane into this cohort in `O(prefilling_lanes * log(blocks))`.
    pub fn push_admitted(&mut self, lane: InflightLaneReserve<'a>) {
        self.len += 1;
        let end = (lane.pf_end + lane.max_gen.saturating_sub(1)).div_ceil(BLOCK);
        self.base_window_growth += end - lane.written.div_ceil(BLOCK);
        self.base_steady_window += end.min(WINDOW / BLOCK + 1);

        let res_blocks = lane.reserved_end().div_ceil(BLOCK);
        let Some(pf) = lane.as_prefill_lane() else {
            self.base_reserved_full += res_blocks - lane.written.div_ceil(BLOCK);
            return;
        };

        let owned_hashes = if pf.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(pf.toks) };
        let new_hashes: &[u64] = pf.block_hashes.unwrap_or(&owned_hashes);

        let credited = if pf.eligible_follower {
            if let Some((ptr, ns, len, np, ln, memo_cred)) = self.last_eval_credited.take() {
                if ptr == pf.toks.as_ptr() as usize
                    && ns == pf.namespace
                    && len == pf.pf_end
                    && np == pf.n_past
                    && ln == pf.lane
                {
                    memo_cred
                } else {
                    let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
                    shared_checkpoint_against_hashed(&pf, new_hashes, iter)
                }
            } else {
                let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
                shared_checkpoint_against_hashed(&pf, new_hashes, iter)
            }
        } else {
            self.last_eval_credited.set(None);
            0
        };

        if pf.runnable {
            for existing in &mut self.prefills {
                if !existing.pf.runnable || !existing.pf.eligible_follower {
                    continue;
                }
                let ahead =
                    pf.n_past > existing.pf.n_past || (pf.n_past == existing.pf.n_past && pf.lane < existing.pf.lane);
                if !ahead {
                    continue;
                }
                let ex_next = effective_pf_target(existing.pf.n_past, existing.pf.pf_end);
                let ex_final = existing.pf.pf_end.saturating_sub(1) / BLOCK * BLOCK;
                let ex_h = existing.pf.block_hashes.unwrap_or(&existing.owned_hashes);
                let cand_for_ex =
                    pair_hash_candidate_checkpoint(&existing.pf, ex_h, &pf, new_hashes, ex_next, ex_final);
                if cand_for_ex > existing.credited {
                    let verified = if std::ptr::eq(existing.pf.toks.as_ptr(), pf.toks.as_ptr())
                        || existing.pf.toks[..cand_for_ex] == pf.toks[..cand_for_ex]
                    {
                        cand_for_ex
                    } else {
                        pair_shared_checkpoint_exact(&existing.pf, &pf, ex_next, ex_final)
                    };
                    if verified > existing.credited {
                        let old_blocks = existing.demanded_blocks(existing.credited);
                        existing.credited = verified;
                        let new_blocks = existing.demanded_blocks(existing.credited);
                        self.base_reserved_full = self.base_reserved_full + new_blocks - old_blocks;
                    }
                }
            }
        }

        let entry =
            PreparedPrefillEntry { pf, owned_hashes, written: lane.written, reserved_end_blocks: res_blocks, credited };
        self.base_reserved_full += entry.demanded_blocks(credited);
        self.prefills.push(entry);
    }
}

/// Pool slots not already owned by a lane or covered by a strictly earlier producer.
/// Including the incoming lane in the same election handles reuse of a low-numbered idle lane.
#[cfg(any(test, standalone_blocks))]
pub fn reserved_inflight_full_slots(lanes: &[InflightLaneReserve<'_>]) -> usize {
    let _ = inflight_shared_checkpoint as fn(&InflightPrefillLane<'_>, &[InflightPrefillLane<'_>]) -> usize;
    PreparedInflightCohort::new(lanes).reserved_full_slots()
}

fn entry_is_live_sealed(pools: &BlockPools, kind: BlockKind, e: BlockEntry) -> bool {
    pools.of(kind).record(e.slot()).ok().is_some_and(|r| r.generation() == e.generation() && r.sealed() && r.refs() > 0)
}

pub struct ServeBlockCache {
    tree: EntryTree,
    starts: HashMap<SealedId, RetainedStart>,
    /// Per-slot refcount contributed exclusively by live entries in `self.starts`.
    /// Maintained in lockstep with `add_ref`/`drop_ref` on `RetainedStart` insert/evict
    /// so `free_plus_evictable_slots` is exact and allocation-free.
    start_slot_refs: [Vec<u32>; 2],
    tick: u64,
    stats: CacheStats,
    spill_store: Option<SpillStore>,
    spilled_tree: PrefixTree<u64>,
    spilled_starts: HashMap<u64, SpilledStart>,
    spilled_tips: HashMap<u64, SealedId>,
    spill_key_owners: HashMap<SpillKey, Vec<u64>>,
    entry_spill_keys: HashMap<(u8, u32, u32), SpillKey>,
    spill_key_to_entry: HashMap<SpillKey, (u8, u32, u32)>,
    next_spill_id: u64,
    max_spilled_starts: usize,
    restore_worker: Option<RestoreWorker>,
    pending_restores: HashMap<usize, PendingRestore>,
    in_flight_restore_keys: HashMap<SpillKey, u32>,
    in_flight_restore_spills: HashSet<u64>,
    next_restore_seq: u64,
    shared_wake: Arc<RestoreWake>,
    last_wake_seq: u64,
    retained_host_bytes: u64,
    max_retained_host_bytes: u64,
    spill_write_timeout: Duration,
    spill_full_attn_budget: u64,
    spill_model_fingerprint: u64,
    kv_stitch: bool,
    stitch_index: HashMap<(u64, u64), Vec<(SealedId, u32)>>,
    ikv_namespace: u64,
    ikv_catalog: Option<Arc<crate::ikv::IkvCatalog>>,
    ikv_stage_worker: Option<IkvStageWorker>,
    pending_ikv_stages: HashMap<usize, PendingIkvStage>,
    next_ikv_stage_seq: u64,
}

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

impl ServeBlockCache {
    pub fn new() -> Self {
        Self {
            tree: EntryTree::new(),
            starts: HashMap::new(),
            start_slot_refs: [Vec::new(), Vec::new()],
            tick: 0,
            stats: CacheStats::default(),
            spill_store: None,
            spilled_tree: PrefixTree::new(),
            spilled_starts: HashMap::new(),
            spilled_tips: HashMap::new(),
            spill_key_owners: HashMap::new(),
            entry_spill_keys: HashMap::new(),
            spill_key_to_entry: HashMap::new(),
            next_spill_id: 1,
            max_spilled_starts: DEFAULT_MAX_SPILLED_STARTS,
            restore_worker: None,
            pending_restores: HashMap::new(),
            in_flight_restore_keys: HashMap::new(),
            in_flight_restore_spills: HashSet::new(),
            next_restore_seq: 1,
            shared_wake: Arc::new(RestoreWake::new()),
            last_wake_seq: 0,
            retained_host_bytes: 0,
            max_retained_host_bytes: DEFAULT_MAX_RETAINED_HOST_BYTES,
            spill_write_timeout: DEFAULT_SPILL_WRITE_TIMEOUT,
            spill_full_attn_budget: u64::MAX,
            spill_model_fingerprint: 0,
            kv_stitch: false,
            stitch_index: HashMap::new(),
            ikv_namespace: 0,
            ikv_catalog: None,
            ikv_stage_worker: None,
            pending_ikv_stages: HashMap::new(),
            next_ikv_stage_seq: 1,
        }
    }

    pub fn set_kv_stitch(&mut self, enabled: bool) {
        self.kv_stitch = enabled;
        if !enabled {
            self.stitch_index.clear();
        }
    }

    pub fn kv_stitch_enabled(&self) -> bool {
        self.kv_stitch
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn set_ikv_catalog(&mut self, catalog: Arc<crate::ikv::IkvCatalog>) {
        self.set_ikv_catalog_for_namespace(catalog, 0);
    }

    pub fn set_ikv_catalog_for_namespace(&mut self, catalog: Arc<crate::ikv::IkvCatalog>, namespace: u64) {
        self.stats.ikv_cartridges_loaded = catalog.len() as u64;
        self.stats.ikv_quarantined = catalog.quarantined_count();
        self.ikv_namespace = namespace;
        self.ikv_catalog = Some(catalog);
    }

    #[inline]
    fn sync_ikv_quarantined_stat(&mut self) {
        if let Some(cat) = &self.ikv_catalog {
            self.stats.ikv_quarantined = cat.quarantined_count();
        }
    }

    fn index_retained_start_for_stitch(&mut self, sid: SealedId) {
        if !self.kv_stitch {
            return;
        }
        let Some(st) = self.starts.get(&sid) else {
            return;
        };
        if st.toks.len() < BLOCK {
            return;
        }
        let ns = st.namespace;
        let n_blocks = st.toks.len() / BLOCK;
        for b in 0..n_blocks {
            let h = stitch_hash_64(&st.toks[b * BLOCK..(b + 1) * BLOCK]);
            let bucket = self.stitch_index.entry((ns, h)).or_default();
            if !bucket.contains(&(sid, b as u32)) {
                if bucket.len() >= MAX_STITCH_BUCKET_LEN {
                    bucket.remove(0);
                }
                bucket.push((sid, b as u32));
            }
        }
    }

    fn unindex_retained_start_for_stitch(&mut self, sid: SealedId, namespace: u64, toks: &[u32]) {
        if toks.len() < BLOCK || self.stitch_index.is_empty() {
            return;
        }
        let n_blocks = toks.len() / BLOCK;
        for b in 0..n_blocks {
            let h = stitch_hash_64(&toks[b * BLOCK..(b + 1) * BLOCK]);
            let remove_bucket = if let Some(bucket) = self.stitch_index.get_mut(&(namespace, h)) {
                bucket.retain(|&(id, _)| id != sid);
                bucket.is_empty()
            } else {
                false
            };
            if remove_bucket {
                self.stitch_index.remove(&(namespace, h));
            }
        }
    }

    /// Host-copy byte reserve carved out of `available_kv_budget_bytes` before sizing GPU `BlockPools`.
    pub fn recommended_host_budget_bytes(available_kv_budget_bytes: u64) -> u64 {
        if available_kv_budget_bytes == 0 {
            return 0;
        }
        (available_kv_budget_bytes / 32).clamp(16 << 20, DEFAULT_MAX_RETAINED_HOST_BYTES)
    }

    pub fn set_max_retained_host_bytes(&mut self, max_bytes: u64) {
        self.max_retained_host_bytes = max_bytes;
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn retained_host_bytes(&self) -> u64 {
        self.retained_host_bytes
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn set_spill_write_timeout(&mut self, timeout: Duration) {
        self.spill_write_timeout = timeout;
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn with_spill(store: SpillStore) -> Self {
        Self::with_spill_compat(store, None, 0)
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn with_spill_compat(store: SpillStore, full_attn_budget: Option<usize>, model_fingerprint: u64) -> Self {
        Self::with_spill_compat_sparse(store, full_attn_budget, None, 0, model_fingerprint)
    }

    pub fn with_spill_compat_sparse(
        store: SpillStore,
        full_attn_budget: Option<usize>,
        sparse_topk: Option<usize>,
        sparse_anchors: usize,
        model_fingerprint: u64,
    ) -> Self {
        let mut cache = Self::new();
        cache.spill_full_attn_budget = match sparse_topk {
            Some(topk) => (1u64 << 63) | (((sparse_anchors as u64) & 0x7fff_ffff) << 32) | ((topk as u64) & 0xffff_ffff),
            None => full_attn_budget.map_or(u64::MAX, |b| b as u64),
        };
        cache.spill_model_fingerprint = model_fingerprint;
        cache.spill_store = Some(store);
        cache.load_spill_index_on_open();
        cache
    }

    pub fn spill_store(&self) -> Option<&SpillStore> {
        self.spill_store.as_ref()
    }

    fn pin_inflight_restore_keys(&mut self, spill_id: u64, keys: &[SpillKey]) {
        self.in_flight_restore_spills.insert(spill_id);
        for &k in keys {
            *self.in_flight_restore_keys.entry(k).or_insert(0) += 1;
        }
    }

    fn unpin_inflight_restore_keys(&mut self, spill_id: u64, keys: &[SpillKey]) {
        for &k in keys {
            if let Some(cnt) = self.in_flight_restore_keys.get_mut(&k) {
                *cnt = cnt.saturating_sub(1);
                if *cnt == 0 {
                    self.in_flight_restore_keys.remove(&k);
                }
            }
        }
        let still_active = self.pending_restores.values().any(|pr| pr.spill_id == spill_id);
        if !still_active {
            self.in_flight_restore_spills.remove(&spill_id);
        }
    }

    fn protected_spill_keys(&self, extra: Option<&RestoreSource>) -> HashSet<SpillKey> {
        let mut out: HashSet<SpillKey> = self.in_flight_restore_keys.keys().copied().collect();
        if let Some(source) = extra {
            out.extend(source.keys.iter().copied());
        }
        out
    }

    /// Persist `self.spilled_starts` crash-safely to `spill-index.bin` (pure-Rust binary format
    /// protected by `Sha256`, zero external crates).
    fn persist_spill_index(&mut self) {
        let Some(store) = self.spill_store.as_ref() else {
            return;
        };
        let kvb = store.kvb();
        let mut records: Vec<(u64, &SpilledStart)> = self.spilled_starts.iter().map(|(&id, sp)| (id, sp)).collect();
        records.sort_by_key(|&(id, sp)| (sp.last_used_tick, id));

        let mut payload = Vec::new();
        for (id, sp) in &records {
            if sp.toks.len() != sp.pos || sp.pos == 0 || !sp.pos.is_multiple_of(BLOCK) {
                continue;
            }
            payload.extend_from_slice(&id.to_le_bytes());
            payload.extend_from_slice(&sp.namespace.to_le_bytes());
            payload.extend_from_slice(&(sp.pos as u64).to_le_bytes());
            payload.push(sp.reasons);
            payload.extend_from_slice(&sp.last_used_tick.to_le_bytes());
            payload.push(sp.cs_key.kind as u8);
            payload.extend_from_slice(&sp.cs_key.id.to_le_bytes());
            payload.extend_from_slice(&(sp.toks.len() as u32).to_le_bytes());
            for &t in &sp.toks {
                payload.extend_from_slice(&t.to_le_bytes());
            }
            payload.extend_from_slice(&(sp.entries.len() as u32).to_le_bytes());
            for &(kind, bi, sk) in &sp.entries {
                payload.push(kind_idx(kind) as u8);
                payload.extend_from_slice(&bi.get().to_le_bytes());
                payload.push(sk.kind as u8);
                payload.extend_from_slice(&sk.id.to_le_bytes());
            }
        }
        let valid_count = records
            .iter()
            .filter(|(_, sp)| sp.toks.len() == sp.pos && sp.pos > 0 && sp.pos.is_multiple_of(BLOCK))
            .count() as u32;

        let mut header = [0u8; SPILL_INDEX_HEADER_LEN];
        header[0..8].copy_from_slice(&SPILL_INDEX_MAGIC);
        header[8..12].copy_from_slice(&SPILL_INDEX_VERSION.to_le_bytes());
        header[12..16].copy_from_slice(&kvb.to_le_bytes());
        header[16..24].copy_from_slice(&self.next_spill_id.to_le_bytes());
        header[24..32].copy_from_slice(&self.tick.to_le_bytes());
        header[32..36].copy_from_slice(&valid_count.to_le_bytes());
        header[36..44].copy_from_slice(&self.spill_full_attn_budget.to_le_bytes());
        header[44..52].copy_from_slice(&self.spill_model_fingerprint.to_le_bytes());
        let payload_len = payload.len() as u64;

        let mut hasher = Sha256::new();
        hasher.update(&header[0..SPILL_INDEX_PREFIX_LEN]);
        hasher.update(&payload_len.to_le_bytes());
        hasher.update(&payload);
        let digest = hasher.finalize();
        header[52..84].copy_from_slice(&digest);

        let mut full = Vec::with_capacity(SPILL_INDEX_HEADER_LEN + 8 + payload.len());
        full.extend_from_slice(&header[0..SPILL_INDEX_PREFIX_LEN]);
        full.extend_from_slice(&payload_len.to_le_bytes());
        full.extend_from_slice(&digest);
        full.extend_from_slice(&payload);
        let _ = store.write_index_bytes(&full);
    }

    fn load_spill_index_on_open(&mut self) {
        let Some(raw) = self.spill_store.as_mut().and_then(|s| s.read_index_bytes(MAX_SPILL_INDEX_BYTES)) else {
            if let Some(store) = self.spill_store.as_mut() {
                store.retain_keys(&HashSet::new());
            }
            return;
        };
        let store_kvb = self.spill_store.as_ref().unwrap().kvb();
        let reject = |this: &mut Self| {
            if let Some(store) = this.spill_store.as_mut() {
                store.remove_index(true);
                store.retain_keys(&HashSet::new());
            }
        };
        if raw.len() < SPILL_INDEX_PREFIX_LEN + 8 + 32 {
            reject(self);
            return;
        }
        if raw[0..8] != SPILL_INDEX_MAGIC {
            reject(self);
            return;
        }
        let version = u32::from_le_bytes(raw[8..12].try_into().unwrap());
        let file_kvb = u32::from_le_bytes(raw[12..16].try_into().unwrap());
        let saved_next_spill_id = u64::from_le_bytes(raw[16..24].try_into().unwrap());
        let saved_tick = u64::from_le_bytes(raw[24..32].try_into().unwrap());
        let count = u32::from_le_bytes(raw[32..36].try_into().unwrap()) as usize;
        let file_budget = u64::from_le_bytes(raw[36..44].try_into().unwrap());
        let file_model_fp = u64::from_le_bytes(raw[44..52].try_into().unwrap());
        if version != SPILL_INDEX_VERSION
            || file_kvb != store_kvb
            || file_budget != self.spill_full_attn_budget
            || file_model_fp != self.spill_model_fingerprint
        {
            reject(self);
            return;
        }
        let payload_len = u64::from_le_bytes(raw[52..60].try_into().unwrap());
        let stored_digest: [u8; 32] = raw[60..92].try_into().unwrap();
        let payload = &raw[92..];
        if payload.len() as u64 != payload_len {
            reject(self);
            return;
        }
        let mut hasher = Sha256::new();
        hasher.update(&raw[0..60]);
        hasher.update(payload);
        if hasher.finalize() != stored_digest {
            reject(self);
            return;
        }

        let parse_records = || -> Option<Vec<(u64, SpilledStart)>> {
            let mut cur = 0usize;
            let mut out = Vec::with_capacity(count.min(self.max_spilled_starts + 16));
            for _ in 0..count {
                if cur + 46 > payload.len() {
                    return None;
                }
                let id = u64::from_le_bytes(payload[cur..cur + 8].try_into().ok()?);
                let namespace = u64::from_le_bytes(payload[cur + 8..cur + 16].try_into().ok()?);
                let pos = usize::try_from(u64::from_le_bytes(payload[cur + 16..cur + 24].try_into().ok()?)).ok()?;
                let reasons = payload[cur + 24];
                let last_used_tick = u64::from_le_bytes(payload[cur + 25..cur + 33].try_into().ok()?);
                let cs_kind = SpillBlockKind::from_u32(u32::from(payload[cur + 33]))?;
                let cs_id = u64::from_le_bytes(payload[cur + 34..cur + 42].try_into().ok()?);
                let toks_len = u32::from_le_bytes(payload[cur + 42..cur + 46].try_into().ok()?) as usize;
                cur += 46;
                if pos == 0 || !pos.is_multiple_of(BLOCK) || toks_len != pos {
                    return None;
                }
                let toks_bytes = toks_len.checked_mul(4)?;
                if cur + toks_bytes + 4 > payload.len() {
                    return None;
                }
                let mut toks = Vec::with_capacity(toks_len);
                for i in 0..toks_len {
                    let off = cur + i * 4;
                    toks.push(u32::from_le_bytes(payload[off..off + 4].try_into().ok()?));
                }
                cur += toks_bytes;
                let entries_len = u32::from_le_bytes(payload[cur..cur + 4].try_into().ok()?) as usize;
                cur += 4;
                let entries_bytes = entries_len.checked_mul(14)?;
                if cur + entries_bytes > payload.len() {
                    return None;
                }
                let mut entries = Vec::with_capacity(entries_len);
                for i in 0..entries_len {
                    let off = cur + i * 14;
                    let bk = match payload[off] {
                        0 => BlockKind::Window,
                        1 => BlockKind::Full,
                        _ => return None,
                    };
                    let bi = BlockIndex::new(u32::from_le_bytes(payload[off + 1..off + 5].try_into().ok()?));
                    let sk_kind = SpillBlockKind::from_u32(u32::from(payload[off + 5]))?;
                    let sk_id = u64::from_le_bytes(payload[off + 6..off + 14].try_into().ok()?);
                    entries.push((bk, bi, SpillKey::new(sk_kind, sk_id)));
                }
                cur += entries_bytes;
                out.push((
                    id,
                    SpilledStart {
                        namespace,
                        pos,
                        reasons,
                        cs_key: SpillKey::new(cs_kind, cs_id),
                        entries,
                        toks,
                        last_used_tick,
                    },
                ));
            }
            (cur == payload.len()).then_some(out)
        };

        let Some(mut decoded) = parse_records() else {
            reject(self);
            return;
        };
        decoded.sort_by_key(|&(id, ref sp)| (sp.last_used_tick, id));
        if decoded.len() > self.max_spilled_starts {
            let drop_n = decoded.len() - self.max_spilled_starts;
            decoded.drain(0..drop_n);
        }

        let mut max_id = saved_next_spill_id.max(1);
        let mut max_tick = saved_tick;
        let mut kept_keys = HashSet::new();
        let mut skipped_any = false;
        for (spill_id, sp) in decoded {
            let store = self.spill_store.as_ref().unwrap();
            let all_present = store.contains(sp.cs_key) && sp.entries.iter().all(|&(_, _, sk)| store.contains(sk));
            if !all_present {
                skipped_any = true;
                continue;
            }
            max_id = max_id.max(spill_id.saturating_add(1));
            max_tick = max_tick.max(sp.last_used_tick);
            let n_blocks = sp.pos / BLOCK;
            let mut parent = None;
            for b in 0..n_blocks {
                let id = self
                    .spilled_tree
                    .insert_in_namespace(
                        sp.namespace,
                        parent,
                        b * BLOCK,
                        &sp.toks[b * BLOCK..(b + 1) * BLOCK],
                        spill_id,
                    )
                    .expect("insert loaded spilled block into spilled_tree");
                parent = Some(id);
            }
            let tip = parent.expect("non-empty loaded spilled blocks");
            if self.spilled_tree.start_holders(tip) > 0 {
                if let Some(old_id) = self.spilled_tree.handle(tip) {
                    self.remove_spilled_start_inner(old_id, false);
                }
                let mut p = None;
                for b in 0..n_blocks {
                    let id = self
                        .spilled_tree
                        .insert_in_namespace(sp.namespace, p, b * BLOCK, &sp.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
                        .expect("re-insert loaded spilled block into spilled_tree");
                    p = Some(id);
                }
                let new_tip = p.expect("non-empty loaded spilled blocks");
                let _ = self.spilled_tree.set_handle(new_tip, spill_id);
                self.spilled_tree.retain_start(new_tip).expect("retain loaded spilled start");
                self.spilled_tips.insert(spill_id, new_tip);
            } else {
                let _ = self.spilled_tree.set_handle(tip, spill_id);
                self.spilled_tree.retain_start(tip).expect("retain loaded spilled start");
                self.spilled_tips.insert(spill_id, tip);
            }
            kept_keys.insert(sp.cs_key);
            self.spill_key_owners.entry(sp.cs_key).or_default().push(spill_id);
            for &(_, _, sk) in &sp.entries {
                kept_keys.insert(sk);
                self.spill_key_owners.entry(sk).or_default().push(spill_id);
            }
            self.spilled_starts.insert(spill_id, sp);
        }
        self.next_spill_id = max_id;
        self.tick = self.tick.max(max_tick);
        let swept = self.spill_store.as_mut().map_or(0, |s| s.retain_keys(&kept_keys));
        if skipped_any || swept > 0 {
            self.persist_spill_index();
        }
    }

    /// Bounded host/disk-only maintenance safe to overlap with an in-flight GPU step:
    /// enforces `max_spilled_starts` and `SpillStore` disk budget without touching
    /// `BlockPools`, `BlockTable`, or active RAM pins.
    pub fn maintain_spill_during_gpu(&mut self) -> usize {
        if self.spill_store.is_none() {
            return 0;
        }
        let mut evicted = 0usize;
        let mut index_dirty = false;
        while self.spilled_starts.len() > self.max_spilled_starts {
            let oldest = self
                .spilled_starts
                .iter()
                .filter(|(id, _)| !self.in_flight_restore_spills.contains(id))
                .min_by_key(|(_, sp)| (sp.last_used_tick, std::cmp::Reverse(sp.pos)))
                .map(|(&id, _)| id);
            let Some(oid) = oldest else { break };
            if self.remove_spilled_start_inner(oid, true) {
                index_dirty = true;
            }
            evicted += 1;
        }
        let protected = self.protected_spill_keys(None);
        let gc_evicted = if let Some(store) = self.spill_store.as_mut() {
            if store.used_bytes() > store.max_bytes() {
                store.evict_lru_to_fit(0, &protected)
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };
        if !gc_evicted.is_empty() {
            evicted += gc_evicted.len();
            self.handle_disk_gc_evicted(&gc_evicted);
            index_dirty = false; // handle_disk_gc_evicted persists index when needed
        }
        if index_dirty {
            self.persist_spill_index();
        }
        self.stats.spill_maint_passes += 1;
        self.stats.spill_maint_evictions += evicted as u64;
        evicted
    }

    pub fn spilled_start_count(&self) -> usize {
        self.spilled_starts.len()
    }

    pub fn record_step_deferred_pool_pressure(&mut self) {
        self.stats.step_deferred_pool_pressure += 1;
    }

    pub fn stats(&self) -> CacheStats {
        self.stats
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn retained_start_count(&self) -> usize {
        self.starts.len()
    }

    fn inc_start_slot_ref(&mut self, kind: BlockKind, slot: Slot) {
        let idx = slot.pool_index().get() as usize;
        let v = &mut self.start_slot_refs[kind_idx(kind)];
        if v.len() <= idx {
            v.resize(idx + 1, 0);
        }
        v[idx] = v[idx].checked_add(1).expect("start_slot_refs overflow");
    }

    fn dec_start_slot_ref(&mut self, kind: BlockKind, slot: Slot) {
        let idx = slot.pool_index().get() as usize;
        let v = &mut self.start_slot_refs[kind_idx(kind)];
        debug_assert!(idx < v.len() && v[idx] > 0, "start_slot_refs underflow");
        if idx < v.len() && v[idx] > 0 {
            v[idx] -= 1;
        }
    }

    /// Number of slots in `kind`'s pool that are currently free (`refs == 0`) OR held only by
    /// evictable `RetainedStart` entries (no active lane references them).
    pub fn free_plus_evictable_slots(&self, pools: &BlockPools, kind: BlockKind) -> usize {
        self.pool_headroom(pools, kind).1
    }

    // (non-retired capacity, slots reclaimable before any active lane is released).
    fn pool_headroom(&self, pools: &BlockPools, kind: BlockKind) -> (usize, usize) {
        pools.of(kind).count_usable_and_avail(&self.start_slot_refs[kind_idx(kind)])
    }

    fn resident_start(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> Option<&RetainedStart> {
        if self.starts.is_empty() {
            return None;
        }
        let prefix = toks.get(..toks.len().checked_sub(1)?)?;
        let matched = self.tree.deepest_start_in_namespace(namespace, prefix);
        let st = self.starts.get(&matched.start?)?;
        (st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| entry_is_live_sealed(pools, kind, e)))
            .then_some(st)
    }

    /// Length of the deepest live in-memory checkpoint strictly shorter than the prompt in default namespace `0`.
    #[cfg(any(test, standalone_blocks))]
    pub fn peek_match_len(&self, pools: &BlockPools, toks: &[u32]) -> usize {
        self.peek_match_len_in_namespace(pools, 0, toks)
    }

    /// Length of the deepest live in-memory checkpoint strictly shorter than `toks` in `namespace`.
    #[cfg(any(test, standalone_blocks))]
    pub fn peek_match_len_in_namespace(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> usize {
        self.resident_start(pools, namespace, toks).map_or(0, |st| st.pos)
    }

    /// Check the marginal cost of binding the prospective lane in `namespace` and completing the
    /// bounded outstanding work using a prebuilt [`PreparedInflightCohort`]
    /// (`O(prefilling_lanes * log(blocks))`, zero all-pairs rescans across a burst).
    #[allow(clippy::too_many_arguments)]
    pub fn can_admit_with_cohort_in_namespace(
        &mut self,
        pools: &BlockPools,
        cohort: &PreparedInflightCohort<'_>,
        lane: usize,
        namespace: u64,
        toks: &[u32],
        cand_block_hashes: Option<&[u64]>,
        max_gen: usize,
        chunk: usize,
    ) -> bool {
        // The handler and scheduler backstop enforce each single-lane physical context bound.
        // With no competing jobs, retained-only slots are reclaimable on demand.
        if cohort.is_empty() {
            return true;
        }

        let owned_hashes;
        let cand_hashes: &[u64] = match cand_block_hashes {
            Some(h) => h,
            None => {
                owned_hashes = compute_block_hashes(toks);
                &owned_hashes
            }
        };

        let (usable_window, available_window, available_full) = match cohort.cached_headroom.get() {
            Some(h) => h,
            None => {
                let (uw, aw) = self.pool_headroom(pools, BlockKind::Window);
                let af = self.free_plus_evictable_slots(pools, BlockKind::Full);
                cohort.cached_headroom.set(Some((uw, aw, af)));
                (uw, aw, af)
            }
        };
        let mut pins = [0; 2];
        let mut cached = 0;
        if let Some(st) = self.resident_start(pools, namespace, toks) {
            cached = st.pos;
            for &(kind, _, entry) in &st.entries {
                let i = kind_idx(kind);
                let slot = entry.slot();
                let refs = self.start_slot_refs[i][slot.pool_index().get() as usize];
                if pools.of(kind).record(slot).unwrap().refs() == refs {
                    pins[i] += 1;
                }
            }
        }

        let fits = |start: usize, newly_pinned: [usize; 2]| {
            let cand = InflightLaneReserve {
                lane,
                namespace,
                toks,
                block_hashes: Some(cand_hashes),
                n_past: start,
                pf_end: toks.len(),
                cached: start,
                written: start,
                gen: 0,
                max_gen,
                runnable: true,
            };
            let (base_full, base_win_growth, steady_window) = cohort.eval_with_candidate(&cand, cand_hashes);
            let full = base_full + newly_pinned[kind_idx(BlockKind::Full)];
            let window_growth = base_win_growth + newly_pinned[kind_idx(BlockKind::Window)];
            // Two independent upper bounds: all remaining writes with no pruning, or the
            // whole cohort's rolling windows plus one shared step budget and per-span rounding.
            let peak_window = steady_window + chunk.div_ceil(BLOCK) + (cohort.len + 1);
            let window_ok = window_growth <= available_window || peak_window <= usable_window;
            full <= available_full && window_ok
        };

        let mut ok = fits(cached, pins);
        // A deeper SSD restore can replace the resident start during bind. Budget that outcome
        // too, including the newly pinned restored blocks, without doing disk I/O on a refused job.
        if ok && !toks.is_empty() && !self.spilled_starts.is_empty() {
            let disk = self.spilled_tree.deepest_start_in_namespace(namespace, &toks[..toks.len() - 1]).at;
            if disk > cached {
                let blocks = disk / BLOCK;
                let already_pinned_full = cached / BLOCK - pins[kind_idx(BlockKind::Full)];
                ok = fits(disk, [blocks.min(WINDOW / BLOCK), blocks - already_pinned_full]);
            }
        }
        if !ok {
            self.stats.admit_deferred_pool_pressure += 1;
        }
        ok
    }

    #[cfg(any(test, standalone_blocks))]
    #[allow(clippy::too_many_arguments)]
    pub fn can_admit_with_cohort(
        &mut self,
        pools: &BlockPools,
        cohort: &PreparedInflightCohort<'_>,
        lane: usize,
        toks: &[u32],
        cand_block_hashes: Option<&[u64]>,
        max_gen: usize,
        chunk: usize,
    ) -> bool {
        self.can_admit_with_cohort_in_namespace(pools, cohort, lane, 0, toks, cand_block_hashes, max_gen, chunk)
    }

    /// Check the marginal cost of binding the prospective lane in `namespace` and completing the bounded
    /// outstanding work. Retained-only slots stop being evictable as soon as this job binds.
    #[cfg(any(test, standalone_blocks))]
    #[allow(clippy::too_many_arguments)]
    pub fn can_admit_in_namespace(
        &mut self,
        pools: &BlockPools,
        active: &[InflightLaneReserve<'_>],
        lane: usize,
        namespace: u64,
        toks: &[u32],
        max_gen: usize,
        chunk: usize,
    ) -> bool {
        if active.is_empty() {
            return true;
        }
        let cohort = PreparedInflightCohort::new(active);
        self.can_admit_with_cohort_in_namespace(pools, &cohort, lane, namespace, toks, None, max_gen, chunk)
    }

    /// Check the marginal cost of binding the prospective lane and completing the bounded
    /// outstanding work in default namespace `0`.
    #[cfg(any(test, standalone_blocks))]
    pub fn can_admit(
        &mut self,
        pools: &BlockPools,
        active: &[InflightLaneReserve<'_>],
        lane: usize,
        toks: &[u32],
        max_gen: usize,
        chunk: usize,
    ) -> bool {
        self.can_admit_in_namespace(pools, active, lane, 0, toks, max_gen, chunk)
    }

    /// Rebind an untouched prefilling lane (`state.written == n_past` and no unsealed blocks)
    /// when `EntryTree` now holds a deeper live `RetainedStart` than `n_past` in `state.namespace`.
    /// Validates and stages the deeper start point BEFORE releasing the lane's prior bindings
    /// so a failed or stale candidate leaves `tbl` and `state` completely intact and consistent.
    pub fn rebind_if_deeper_match(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        n_past: usize,
    ) -> Option<(usize, Vec<u8>)> {
        if state.stitched_approx
            || state.written != n_past
            || state.written != state.sealed.len() * BLOCK
            || toks.len() <= 1
        {
            return None;
        }
        let namespace = state.namespace;
        let search = &toks[..toks.len() - 1];
        let mut matched = self.tree.deepest_start_in_namespace(namespace, search);
        loop {
            if matched.at <= n_past {
                return None;
            }
            let sid = matched.start?;
            let all_live = match self.starts.get(&sid) {
                Some(st) => {
                    debug_assert_eq!(st.pos, matched.at);
                    st.namespace == namespace
                        && st.entries.iter().all(|&(kind, _, e)| entry_is_live_sealed(pools, kind, e))
                }
                None => false,
            };
            if all_live {
                break;
            }
            self.evict_start_inner(pools, sid, false, None);
            matched = self.tree.deepest_start_in_namespace(namespace, search);
        }
        let sid = matched.start.expect("validated live start id");
        let (cs, entries) = {
            let st = self.starts.get(&sid).expect("validated live start exists");
            (st.cs.clone(), st.entries.clone())
        };
        // Stage all new block-table bindings and EntryTree pins BEFORE releasing the lane's
        // prior bindings so any failure (such as table-capacity bounds or ref overflow) leaves
        // `tbl` and `state` completely untouched.
        let Ok(mut staged) = BlockTable::new(tbl.blocks_per_kind()) else {
            return None;
        };
        for &(kind, bi, e) in &entries {
            if staged.fill(pools.of_mut(kind), bi, e.slot(), e.generation()).is_err() {
                let _ = staged.clear_entries(pools);
                return None;
            }
        }
        let mut pinned_ids: Vec<SealedId> = Vec::with_capacity(matched.ids.len());
        for &id in &matched.ids {
            if self.tree.pin(id).is_err() {
                for pid in pinned_ids {
                    self.tree.unpin(pid);
                }
                let _ = staged.clear_entries(pools);
                return None;
            }
            pinned_ids.push(id);
        }
        staged.mark_full_sync();

        // Commit: release old bindings only now that the deeper target is 100% staged and pinned.
        tbl.clear_entries(pools).expect("clear lane block table for rebind");
        let old_tip = state.sealed.last().copied();
        for id in state.sealed.drain(..) {
            self.tree.unpin(id);
        }
        if let Some(old_tip) = old_tip {
            if !pinned_ids.contains(&old_tip) {
                self.tree.prune_unreferenced(old_tip);
            }
        }
        self.tick += 1;
        let now = self.tick;
        for &anc in &pinned_ids {
            if let Some(st) = self.starts.get_mut(&anc) {
                st.last_used_tick = now;
            }
        }
        *tbl = staged;
        state.prompt_len = toks.len();
        state.sealed = pinned_ids;
        state.written = matched.at;
        state.stitched_approx = false;
        self.stats.start_matches += 1;
        self.stats.cached_tokens_total += matched.at as u64;
        self.stats.singleflight_rebinds += 1;
        self.stats.singleflight_saved_tokens += (matched.at - n_past) as u64;
        Some((matched.at, cs))
    }

    /// Bind `state` in `namespace` to the deepest live in-RAM or spilled SSD start point strictly
    /// shorter than `toks`.
    #[cfg(any(test, standalone_blocks))]
    pub fn match_and_bind_in_namespace(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        namespace: u64,
        toks: &[u32],
    ) -> Option<(usize, Vec<u8>)> {
        state.namespace = namespace; // MUTANT_ANCHOR_BIND_NAMESPACE
        self.match_and_bind(pools, tbl, state, toks)
    }

    /// Look up the deepest live `RetainedStart` (or spilled SSD start point when deeper than any
    /// in-RAM match) strictly shorter than `toks` in `state.namespace`, bind its `Full` and `Window`
    /// entries into `tbl`, pin its `EntryTree` path on `state`, touch its LRU tick, and return
    /// `Some((matched_at, cs_bytes))`.
    pub fn match_and_bind(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
    ) -> Option<(usize, Vec<u8>)> {
        debug_assert!(state.sealed.is_empty(), "lane must be released before match_and_bind");
        let namespace = state.namespace;
        state.prompt_len = toks.len();
        state.written = 0;
        state.stitched_approx = false;
        if toks.len() <= 1 {
            return None;
        }
        let search = &toks[..toks.len() - 1];
        let mut in_ram = self.tree.deepest_start_in_namespace(namespace, search); // MUTANT_ANCHOR_MATCH_IN_RAM
        if in_ram.at > 0 {
            if let Some(sid) = in_ram.start {
                let all_live = match self.starts.get(&sid) {
                    Some(st) => {
                        debug_assert_eq!(st.pos, in_ram.at);
                        st.namespace == namespace
                            && st.entries.iter().all(|&(kind, _, e)| entry_is_live_sealed(pools, kind, e))
                    }
                    None => false,
                };
                if !all_live {
                    self.evict_start_inner(pools, sid, false, None);
                    in_ram = self.tree.deepest_start_in_namespace(namespace, search);
                }
            } else {
                in_ram.at = 0;
            }
        }
        let mut restored_from_disk = false;
        if self.spill_store.is_some() && !self.spilled_starts.is_empty() {
            let on_disk = self.spilled_tree.deepest_start_in_namespace(namespace, search);
            if on_disk.at > in_ram.at {
                if let Some(&spill_id) = on_disk.blocks.last() {
                    restored_from_disk =
                        self.try_restore_spilled_start(pools, namespace, toks, spill_id, &in_ram).is_some();
                }
            }
        }
        let matched = if restored_from_disk { self.tree.deepest_start_in_namespace(namespace, search) } else { in_ram };
        self.bind_matched_resident_start(pools, tbl, state, toks.len(), matched)
    }

    fn bind_resident_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
    ) -> Option<(usize, Vec<u8>)> {
        state.prompt_len = toks.len();
        state.written = 0;
        if toks.len() <= 1 {
            return None;
        }
        let matched = self.tree.deepest_start_in_namespace(state.namespace, &toks[..toks.len() - 1]);
        self.bind_matched_resident_start(pools, tbl, state, toks.len(), matched)
    }

    fn bind_matched_resident_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        prompt_len: usize,
        matched: crate::prefix::StartMatch<BlockHandles>,
    ) -> Option<(usize, Vec<u8>)> {
        let namespace = state.namespace;
        state.prompt_len = prompt_len;
        if matched.at == 0 {
            return None;
        }
        let sid = matched.start?;
        let st = self.starts.get(&sid)?;
        debug_assert_eq!(st.pos, matched.at);
        let all_live =
            st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| entry_is_live_sealed(pools, kind, e));
        if !all_live {
            self.evict_start_inner(pools, sid, false, None);
            return None;
        }
        self.tick += 1;
        let now = self.tick;
        // Touch the matched start point and any ancestor start points along the hot prefix.
        for &anc in &matched.ids {
            if let Some(st) = self.starts.get_mut(&anc) {
                st.last_used_tick = now;
            }
        }
        let (cs, entries) = {
            let st = self.starts.get(&sid).expect("checked start exists");
            (st.cs.clone(), st.entries.clone())
        };
        for &(kind, bi, e) in &entries {
            tbl.fill(pools.of_mut(kind), bi, e.slot(), e.generation()).expect("install start-point block");
        }
        for &id in &matched.ids {
            self.tree.pin(id).expect("pin matched prefix block");
        }
        state.sealed = matched.ids;
        state.written = matched.at;
        state.stitched_approx = false;
        self.stats.start_matches += 1;
        self.stats.cached_tokens_total += matched.at as u64;
        Some((matched.at, cs))
    }

    fn alloc_spill_key(&mut self, kind: BlockKind) -> SpillKey {
        self.spill_store.as_mut().expect("spill keys require an open store").fresh_key(to_spill_kind(kind))
    }

    fn remove_spilled_start(&mut self, spill_id: u64, delete_from_disk: bool) {
        if self.remove_spilled_start_inner(spill_id, delete_from_disk) {
            self.persist_spill_index();
        }
    }

    fn remove_spilled_start_inner(&mut self, spill_id: u64, delete_from_disk: bool) -> bool {
        let Some(sp) = self.spilled_starts.remove(&spill_id) else {
            return false;
        };
        if let Some(tip) = self.spilled_tips.remove(&spill_id) {
            let _ = self.spilled_tree.release_start(tip);
            self.spilled_tree.prune_unreferenced(tip);
        }
        for sk in std::iter::once(sp.cs_key).chain(sp.entries.iter().map(|&(_, _, k)| k)) {
            let remove_key = if let Some(owners) = self.spill_key_owners.get_mut(&sk) {
                owners.retain(|&id| id != spill_id);
                owners.is_empty()
            } else {
                false
            };
            if remove_key {
                self.spill_key_owners.remove(&sk);
                if let Some(entry_key) = self.spill_key_to_entry.remove(&sk) {
                    self.entry_spill_keys.remove(&entry_key);
                }
                if delete_from_disk && !self.in_flight_restore_keys.contains_key(&sk) {
                    if let Some(store) = self.spill_store.as_mut() {
                        store.remove_block(sk);
                    }
                }
            }
        }
        true
    }

    fn handle_disk_gc_evicted(&mut self, evicted: &[SpillKey]) {
        let mut dirty = false;
        for &gk in evicted {
            if let Some(entry_key) = self.spill_key_to_entry.remove(&gk) {
                self.entry_spill_keys.remove(&entry_key);
            }
            if let Some(owners) = self.spill_key_owners.remove(&gk) {
                for oid in owners {
                    if self.remove_spilled_start_inner(oid, true) {
                        dirty = true;
                    }
                }
            }
        }
        if dirty {
            self.persist_spill_index();
        }
    }

    fn claim_spill_key(&mut self, spill_id: u64, sk: SpillKey, claimed: &mut Vec<SpillKey>) {
        let owners = self.spill_key_owners.entry(sk).or_default();
        if !owners.contains(&spill_id) {
            owners.push(spill_id);
            claimed.push(sk);
        }
    }

    fn abort_spill_claims(&mut self, spill_id: u64, claimed: &[SpillKey]) {
        for &sk in claimed {
            let remove_key = if let Some(owners) = self.spill_key_owners.get_mut(&sk) {
                owners.retain(|&id| id != spill_id);
                owners.is_empty()
            } else {
                false
            };
            if remove_key {
                self.spill_key_owners.remove(&sk);
                if let Some(entry_key) = self.spill_key_to_entry.remove(&sk) {
                    self.entry_spill_keys.remove(&entry_key);
                }
                if let Some(store) = self.spill_store.as_mut() {
                    store.remove_block(sk);
                }
            }
        }
    }

    fn spill_retained_start(&mut self, pools: &BlockPools, st: &RetainedStart, restore: Option<&RestoreSource>) {
        if self.spill_store.is_none()
            || self.max_spilled_starts == 0
            || st.pos == 0
            || !st.pos.is_multiple_of(BLOCK)
            || st.toks.len() != st.pos
            || st.entries.is_empty()
        {
            return;
        }
        if self.spill_write_timeout.is_zero() {
            self.stats.spill_write_timeouts += 1;
            return;
        }
        let deadline = Instant::now() + self.spill_write_timeout;
        for &(kind, _, e) in &st.entries {
            let pool = pools.of(kind);
            if !entry_is_live_sealed(pools, kind, e) || pool.slot_raw_region(e.slot()).is_none() {
                return;
            }
        }

        let spill_id = self.next_spill_id;
        self.next_spill_id = self.next_spill_id.wrapping_add(1).max(1);

        // Claim ownership of all reusable on-disk blocks BEFORE trimming `max_spilled_starts`,
        // writing new blocks, or replacing an existing tip, so concurrent/interleaved eviction
        // can never delete a `.blk` file that `spill_id` is reusing.
        let mut protected = self.protected_spill_keys(restore);
        let mut claimed_keys: Vec<SpillKey> = Vec::with_capacity(st.entries.len() + 1);
        let mut reusable_keys: HashSet<SpillKey> = HashSet::new();
        for &(kind, _, e) in &st.entries {
            let ek = (kind_idx(kind) as u8, e.slot().get(), e.generation());
            if let Some(&sk) = self.entry_spill_keys.get(&ek) {
                if self.spill_store.as_ref().is_some_and(|store| store.contains(sk)) {
                    protected.insert(sk);
                    reusable_keys.insert(sk);
                    self.claim_spill_key(spill_id, sk, &mut claimed_keys);
                }
            }
        }

        while self.spilled_starts.len() >= self.max_spilled_starts && self.max_spilled_starts > 0 {
            let oldest = self
                .spilled_starts
                .iter()
                .filter(|(id, _)| {
                    !restore.is_some_and(|source| source.spill_id == **id)
                        && !self.in_flight_restore_spills.contains(id)
                })
                .min_by_key(|(_, sp)| (sp.last_used_tick, std::cmp::Reverse(sp.pos)))
                .map(|(&id, _)| id);
            let Some(oid) = oldest else {
                self.abort_spill_claims(spill_id, &claimed_keys);
                return;
            };
            self.remove_spilled_start(oid, true);
        }

        let mut spilled_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::with_capacity(st.entries.len());

        for &(kind, bi, e) in &st.entries {
            let ek = (kind_idx(kind) as u8, e.slot().get(), e.generation());
            let (sk, is_new_key) = if let Some(&existing) = self.entry_spill_keys.get(&ek) {
                (existing, false)
            } else {
                (self.alloc_spill_key(kind), true)
            };
            if !is_new_key
                && reusable_keys.contains(&sk)
                && self.spill_store.as_ref().is_some_and(|store| store.contains(sk))
            {
                spilled_entries.push((kind, bi, sk));
                continue;
            }
            if Instant::now() >= deadline {
                self.stats.spill_write_timeouts += 1;
                self.abort_spill_claims(spill_id, &claimed_keys);
                return;
            }
            let kv_bytes = match pools.of(kind).slot_bytes(e.slot()) {
                Ok(b) => b,
                Err(_) => {
                    self.abort_spill_claims(spill_id, &claimed_keys);
                    return;
                }
            };
            let write_res = self.spill_store.as_mut().expect("checked spill_store").write_block(
                sk,
                u64::from(e.generation()),
                kv_bytes,
                None,
                &protected,
            );
            match write_res {
                Ok((WriteOutcome::Written { .. }, gc_evicted)) => {
                    self.handle_disk_gc_evicted(&gc_evicted);
                    if is_new_key {
                        self.entry_spill_keys.insert(ek, sk);
                        self.spill_key_to_entry.insert(sk, ek);
                    }
                    protected.insert(sk);
                    self.claim_spill_key(spill_id, sk, &mut claimed_keys);
                    spilled_entries.push((kind, bi, sk));
                }
                Ok((WriteOutcome::OverBudget, gc_evicted)) => {
                    self.handle_disk_gc_evicted(&gc_evicted);
                    self.abort_spill_claims(spill_id, &claimed_keys);
                    return;
                }
                Err(_) => {
                    self.abort_spill_claims(spill_id, &claimed_keys);
                    return;
                }
            }
        }

        if Instant::now() >= deadline {
            self.stats.spill_write_timeouts += 1;
            self.abort_spill_claims(spill_id, &claimed_keys);
            return;
        }
        let cs_key = self.alloc_spill_key(BlockKind::Full);
        let cs_res = self.spill_store.as_mut().expect("checked spill_store").write_block(
            cs_key,
            1,
            &[],
            Some(&st.cs),
            &protected,
        );
        match cs_res {
            Ok((WriteOutcome::Written { .. }, gc_evicted)) => {
                self.handle_disk_gc_evicted(&gc_evicted);
                protected.insert(cs_key);
                self.claim_spill_key(spill_id, cs_key, &mut claimed_keys);
            }
            Ok((WriteOutcome::OverBudget, gc_evicted)) => {
                self.handle_disk_gc_evicted(&gc_evicted);
                self.abort_spill_claims(spill_id, &claimed_keys);
                return;
            }
            Err(_) => {
                self.abort_spill_claims(spill_id, &claimed_keys);
                return;
            }
        }

        let n_blocks = st.pos / BLOCK;
        let mut parent = None;
        for b in 0..n_blocks {
            let id = self
                .spilled_tree
                .insert_in_namespace(st.namespace, parent, b * BLOCK, &st.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
                .expect("insert spilled block into spilled_tree");
            parent = Some(id);
        }
        let tip = parent.expect("non-empty spilled blocks");
        if self.spilled_tree.start_holders(tip) > 0 {
            if let Some(old_id) = self.spilled_tree.handle(tip) {
                let _ = self.remove_spilled_start_inner(old_id, true);
            }
            // Re-insert path if pruned above so tip holds the new spill_id.
            let mut p = None;
            for b in 0..n_blocks {
                let id = self
                    .spilled_tree
                    .insert_in_namespace(st.namespace, p, b * BLOCK, &st.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
                    .expect("re-insert spilled block into spilled_tree");
                p = Some(id);
            }
            let new_tip = p.expect("non-empty spilled blocks");
            let _ = self.spilled_tree.set_handle(new_tip, spill_id);
            self.spilled_tree.retain_start(new_tip).expect("retain spilled start");
            self.spilled_tips.insert(spill_id, new_tip);
        } else {
            let _ = self.spilled_tree.set_handle(tip, spill_id);
            self.spilled_tree.retain_start(tip).expect("retain spilled start");
            self.spilled_tips.insert(spill_id, tip);
        }

        self.spilled_starts.insert(
            spill_id,
            SpilledStart {
                namespace: st.namespace,
                pos: st.pos,
                reasons: st.reasons,
                cs_key,
                entries: spilled_entries,
                toks: st.toks.clone(),
                last_used_tick: st.last_used_tick,
            },
        );
        self.stats.starts_spilled += 1;
        self.persist_spill_index();
    }

    fn try_restore_spilled_start(
        &mut self,
        pools: &mut BlockPools,
        namespace: u64,
        toks: &[u32],
        spill_id: u64,
        in_ram: &crate::prefix::StartMatch<BlockHandles>,
    ) -> Option<SealedId> {
        let (sp_ns, pos, reasons, cs_key, entries) = {
            let sp = self.spilled_starts.get(&spill_id)?;
            (sp.namespace, sp.pos, sp.reasons, sp.cs_key, sp.entries.clone())
        };
        if sp_ns != namespace || pos == 0 || !pos.is_multiple_of(BLOCK) || pos >= toks.len() {
            if pos == 0 || !pos.is_multiple_of(BLOCK) {
                self.remove_spilled_start(spill_id, true);
            }
            return None;
        }

        let mut reused_full: Vec<(BlockIndex, BlockEntry)> = Vec::new();
        let mut disk_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::new();
        for &(kind, bi, sk) in &entries {
            if kind == BlockKind::Full {
                let b_idx = bi.get() as usize;
                if b_idx < in_ram.blocks.len() {
                    let fe = in_ram.blocks[b_idx].full();
                    if entry_is_live_sealed(pools, BlockKind::Full, fe) {
                        reused_full.push((bi, fe));
                        continue;
                    }
                }
            }
            disk_entries.push((kind, bi, sk));
        }

        let need_full = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Full).count();
        let need_win = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Window).count();

        if (need_full > 0 && pools.full.slab_count() == 0) || (need_win > 0 && pools.window.slab_count() == 0) {
            return None;
        }

        let full_srefs = &self.start_slot_refs[kind_idx(BlockKind::Full)];
        let reused_evictable = reused_full
            .iter()
            .filter(|&&(_, fe)| {
                let idx = fe.slot().pool_index().get() as usize;
                let sref = full_srefs.get(idx).copied().unwrap_or(0);
                pools.full.record(fe.slot()).ok().is_some_and(|r| r.refs() <= sref)
            })
            .count();

        let avail_full = self.free_plus_evictable_slots(pools, BlockKind::Full).saturating_sub(reused_evictable);
        let avail_win = self.free_plus_evictable_slots(pools, BlockKind::Window);
        if need_full > avail_full || need_win > avail_win {
            return None;
        }

        // Recurrent state is needed by every restore and has a separate bounded spill record.
        let restore_began = Instant::now();
        let cs = match self.spill_store.as_mut()?.read_block(cs_key, Some(0)) {
            ReadOutcome::Hit(blk) => match blk.recurrent_state {
                Some(cs) if !cs.is_empty() => cs,
                _ => {
                    self.stats.corrupt_fallbacks += 1;
                    self.remove_spilled_start(spill_id, true);
                    return None;
                }
            },
            ReadOutcome::Miss(_) => {
                self.stats.corrupt_fallbacks += 1;
                self.remove_spilled_start(spill_id, true);
                return None;
            }
        };

        let source = RestoreSource {
            spill_id,
            keys: entries.iter().map(|&(_, _, key)| key).chain(std::iter::once(cs_key)).collect(),
            resident_start: in_ram.start,
        };
        // Reused blocks and newly loaded blocks stay private to the restore until the
        // complete checkpoint is verified. This list owns one temporary ref per entry.
        let mut held = Vec::with_capacity(entries.len());
        for (bi, fe) in reused_full {
            pools.full.record_mut(fe.slot()).unwrap().add_ref().expect("pin reused full block");
            held.push((BlockKind::Full, bi, fe));
        }
        if self.stage_restore_blocks(pools, &source, &disk_entries, &mut held).is_none() {
            Self::release_restore_refs(pools, held);
            return None;
        }
        let elapsed_us = restore_began.elapsed().as_micros().min(u128::from(u64::MAX)) as u64;
        Some(self.publish_restored_checkpoint(
            pools,
            spill_id,
            namespace,
            pos,
            reasons,
            cs,
            &toks[..pos],
            held,
            elapsed_us,
        ))
    }

    #[allow(clippy::too_many_arguments)]
    fn publish_restored_checkpoint(
        &mut self,
        pools: &mut BlockPools,
        spill_id: u64,
        namespace: u64,
        pos: usize,
        reasons: u8,
        cs: Vec<u8>,
        prefix_toks: &[u32],
        held: Vec<(BlockKind, BlockIndex, BlockEntry)>,
        elapsed_us: u64,
    ) -> SealedId {
        // Publish the verified checkpoint, transferring its provisional refs to the retained start.
        let mut full_by_bi: HashMap<u32, BlockEntry> = HashMap::with_capacity(pos / BLOCK);
        let mut win_by_bi: HashMap<u32, BlockEntry> = HashMap::with_capacity(WINDOW / BLOCK);
        for &(kind, bi, e) in &held {
            match kind {
                BlockKind::Full => {
                    full_by_bi.insert(bi.get(), e);
                }
                BlockKind::Window => {
                    win_by_bi.insert(bi.get(), e);
                }
            }
        }

        let n_blocks = pos / BLOCK;
        let win_lo = pos.saturating_sub(WINDOW) / BLOCK;
        let mut parent = None;
        let mut final_entries = Vec::with_capacity(n_blocks + WINDOW / BLOCK);
        for b in 0..n_blocks {
            let bi = BlockIndex::new(b as u32);
            let full_e = *full_by_bi.get(&(b as u32)).expect("restored full entry");
            let win_e_opt = win_by_bi.get(&(b as u32)).copied();
            let handles = BlockHandles::new(full_e, win_e_opt);
            let id = self
                .tree
                .insert_in_namespace(namespace, parent, b * BLOCK, &prefix_toks[b * BLOCK..(b + 1) * BLOCK], handles)
                .expect("insert restored block into EntryTree");
            let canon = self.tree.handle(id).expect("inserted handle");
            let canon_f = canon.full();
            let best_f = if canon_f != full_e && entry_is_live_sealed(pools, BlockKind::Full, canon_f) {
                canon_f
            } else {
                full_e
            };
            let best_w = match (win_e_opt, canon.window()) {
                (Some(we), Some(cw)) if cw != we && entry_is_live_sealed(pools, BlockKind::Window, cw) => Some(cw),
                (Some(we), _) => Some(we),
                (None, Some(cw)) if entry_is_live_sealed(pools, BlockKind::Window, cw) => Some(cw),
                (None, _) => None,
            };
            if best_f != canon_f || best_w != canon.window() {
                let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
            }
            final_entries.push((BlockKind::Full, bi, best_f));
            if b >= win_lo {
                if let Some(we) = best_w {
                    final_entries.push((BlockKind::Window, bi, we));
                }
            }
            parent = Some(id);
        }

        let tip = parent.expect("non-empty restored start");
        self.tick += 1;
        let now = self.tick;
        if let Some(existing) = self.starts.get_mut(&tip) {
            existing.reasons |= reasons;
            existing.last_used_tick = now;
        } else {
            for &(kind, _, e) in &final_entries {
                pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain restored start point ref");
                self.inc_start_slot_ref(kind, e.slot());
            }
            self.tree.retain_start(tip).expect("retain restored start in EntryTree");
            let st = RetainedStart {
                namespace,
                pos,
                cs,
                reasons,
                entries: final_entries,
                toks: prefix_toks.to_vec(),
                last_used_tick: now,
            };
            self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
            self.starts.insert(tip, st);
            self.index_retained_start_for_stitch(tip);
            self.enforce_retained_host_budget(pools, Some(tip));
        }

        Self::release_restore_refs(pools, held); // MUTANT_ANCHOR_RELEASE_RESTORE_REFS
        self.remove_spilled_start(spill_id, true);
        self.stats.starts_restored += 1;
        self.stats.last_restore_us = elapsed_us;
        self.stats.restore_us_total = self.stats.restore_us_total.saturating_add(elapsed_us);
        tip
    }

    pub fn begin_admit_bind_in_namespace(
        &mut self,
        pools: &mut BlockPools,
        lane: usize,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        namespace: u64,
        toks: &[u32],
    ) -> AdmitBindOutcome {
        state.namespace = namespace;
        self.begin_admit_bind(pools, lane, tbl, state, toks)
    }

    /// Begin binding an admitted lane on the scheduler thread without blocking on SSD reads:
    /// - If no deeper SSD checkpoint exists (or pool headroom cannot fit the restore), binds
    ///   any resident RAM checkpoint immediately and returns [`AdmitBindOutcome::Immediate`].
    /// - If a deeper SSD checkpoint exists and fits, atomically pre-reserves all destination
    ///   `(Full, Window)` `BlockPool` slots (`t-l4-restore`), pins source `.blk` keys against
    ///   disk GC, dispatches `pread` + SHA-256 verification to the background restore worker,
    ///   and returns [`AdmitBindOutcome::Restoring`].
    pub fn begin_admit_bind(
        &mut self,
        pools: &mut BlockPools,
        lane: usize,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
    ) -> AdmitBindOutcome {
        debug_assert!(state.sealed.is_empty(), "lane must be released before begin_admit_bind");
        debug_assert!(!self.pending_restores.contains_key(&lane), "lane already restoring");
        debug_assert!(!self.pending_ikv_stages.contains_key(&lane), "lane already staging ikv");
        let namespace = state.namespace;
        state.prompt_len = toks.len();
        state.written = 0;
        state.stitched_approx = false;
        state.bound_lane = Some(lane);
        if toks.len() <= 1 {
            return AdmitBindOutcome::Immediate(None);
        }
        let search = &toks[..toks.len() - 1];
        let mut in_ram = self.tree.deepest_start_in_namespace(namespace, search);
        if in_ram.at > 0 {
            if let Some(sid) = in_ram.start {
                let all_live = match self.starts.get(&sid) {
                    Some(st) => {
                        debug_assert_eq!(st.pos, in_ram.at);
                        st.namespace == namespace
                            && st.entries.iter().all(|&(kind, _, e)| entry_is_live_sealed(pools, kind, e))
                    }
                    None => false,
                };
                if !all_live {
                    self.evict_start_inner(pools, sid, false, None);
                    in_ram = self.tree.deepest_start_in_namespace(namespace, search);
                }
            } else {
                in_ram.at = 0;
            }
        }

        if self.spill_store.is_none() || self.spilled_starts.is_empty() {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }

        let on_disk = self.spilled_tree.deepest_start_in_namespace(namespace, search);
        if on_disk.at <= in_ram.at {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }
        let Some(&spill_id) = on_disk.blocks.last() else {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        };
        if self.in_flight_restore_spills.contains(&spill_id) {
            // Another lane is already restoring this exact spilled start; let singleflight /
            // rebind pick it up once published in RAM rather than double-reading from SSD.
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }
        let Some((sp_ns, pos, reasons, cs_key, entries)) = self
            .spilled_starts
            .get(&spill_id)
            .map(|sp| (sp.namespace, sp.pos, sp.reasons, sp.cs_key, sp.entries.clone()))
        else {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        };
        if sp_ns != namespace || pos == 0 || !pos.is_multiple_of(BLOCK) || pos >= toks.len() {
            if pos == 0 || !pos.is_multiple_of(BLOCK) {
                self.remove_spilled_start(spill_id, true);
            }
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }

        let mut reused_full: Vec<(BlockIndex, BlockEntry)> = Vec::new();
        let mut disk_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::new();
        for &(kind, bi, sk) in &entries {
            if kind == BlockKind::Full {
                let b_idx = bi.get() as usize;
                if b_idx < in_ram.blocks.len() {
                    let fe = in_ram.blocks[b_idx].full();
                    if entry_is_live_sealed(pools, BlockKind::Full, fe) {
                        reused_full.push((bi, fe));
                        continue;
                    }
                }
            }
            disk_entries.push((kind, bi, sk));
        }

        let need_full = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Full).count();
        let need_win = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Window).count();
        if (need_full > 0 && pools.full.slab_count() == 0) || (need_win > 0 && pools.window.slab_count() == 0) {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }

        // Pin reused_full temporarily BEFORE selecting eviction victims so select_eviction_victims
        // sees exact active+provisional references and preserves `in_ram.start`.
        let mut held_reused = Vec::with_capacity(reused_full.len());
        for (bi, fe) in reused_full {
            pools.full.record_mut(fe.slot()).unwrap().add_ref().expect("pin reused full block for async restore");
            held_reused.push((BlockKind::Full, bi, fe));
        }

        let victims = match self.select_eviction_victims(pools, need_win, need_full, in_ram.start) {
            Ok(v) => v,
            Err(_) => {
                Self::release_restore_refs(pools, held_reused);
                return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
            }
        };

        let protected_vec: Vec<SpillKey> = entries.iter().map(|&(_, _, k)| k).chain(std::iter::once(cs_key)).collect();
        let source =
            RestoreSource { spill_id, keys: protected_vec.iter().copied().collect(), resident_start: in_ram.start };
        self.pin_inflight_restore_keys(spill_id, &protected_vec);
        for sid in victims {
            self.evict_start_inner(pools, sid, true, Some(&source));
        }

        let mut reserved_slots = Vec::with_capacity(disk_entries.len());
        let mut blocks_for_worker = Vec::with_capacity(disk_entries.len());
        for (idx, &(kind, bi, sk)) in disk_entries.iter().enumerate() {
            let Ok((slot, generation)) = self.take_zeroed_slot_inner(pools, kind, Some(&source)) else {
                Self::release_restore_refs(pools, reserved_slots);
                Self::release_restore_refs(pools, held_reused);
                self.unpin_inflight_restore_keys(spill_id, &protected_vec);
                return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
            };
            let pool = pools.of_mut(kind);
            let expected_len = pool.stride_bytes() as usize;
            pool.clear_gpu_zero_pending(slot);
            let rec = pool.record_mut(slot).unwrap();
            rec.set_length(BLOCK as u32).expect("set reserved restore block length");
            rec.seal();
            rec.add_ref().expect("pin reserved restore slot");
            let offset = pool.offset(slot).expect("reserved restore slot offset");
            reserved_slots.push((kind, bi, BlockEntry::new(slot, generation, offset, kind, pool.kvb())));
            blocks_for_worker.push((idx, sk, expected_len));
        }

        let (dir, kvb) = {
            let store = self.spill_store.as_ref().expect("checked spill_store");
            (store.dir().to_path_buf(), store.kvb())
        };
        let restore_seq = self.next_restore_seq;
        self.next_restore_seq = self.next_restore_seq.wrapping_add(1).max(1);
        let cancel_flag = Arc::new(AtomicBool::new(false));
        let began = Instant::now();

        self.pending_restores.insert(
            lane,
            PendingRestore {
                restore_seq,
                spill_id,
                namespace,
                pos,
                reasons,
                full_toks: toks.to_vec(),
                protected_keys: protected_vec.clone(),
                held_reused,
                reserved_slots,
                loaded_cs: None,
                loaded_blocks: 0,
                cancel_flag: cancel_flag.clone(),
            },
        );

        let wake = self.shared_wake.clone();
        let worker = self.restore_worker.get_or_insert_with(|| RestoreWorker::spawn(wake));
        if worker
            .job_tx
            .as_ref()
            .and_then(|tx| {
                tx.send(RestoreJob {
                    lane,
                    restore_seq,
                    dir,
                    kvb,
                    cs_key,
                    blocks: blocks_for_worker,
                    cancel_flag,
                    began,
                })
                .ok()
            })
            .is_none()
        {
            self.cancel_restore(pools, lane);
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks));
        }

        AdmitBindOutcome::Restoring { target_pos: pos }
    }

    pub fn has_inflight_restores(&self) -> bool {
        !self.pending_restores.is_empty() || !self.pending_ikv_stages.is_empty()
    }

    pub fn has_pending_ikv_stage(&self, lane: usize) -> bool {
        self.pending_ikv_stages.contains_key(&lane)
    }

    pub fn wait_restore_activity(&mut self, timeout: Duration) {
        let wake = self.shared_wake.clone();
        wake.wait_timeout(&mut self.last_wake_seq, timeout);
    }

    /// Cancel an in-flight background `.ikv` stitch stage on `lane`, releasing all pre-reserved
    /// `BlockPools::full` slots immediately with zero leaks.
    pub fn cancel_ikv_stage(&mut self, pools: &mut BlockPools, lane: usize) -> bool {
        let Some(ps) = self.pending_ikv_stages.remove(&lane) else {
            return false;
        };
        ps.cancel_flag.store(true, Ordering::Release);
        for (slot, _) in ps.reserved_slots {
            pools.full.record_mut(slot).unwrap().drop_ref().expect("drop cancelled ikv stage slot ref");
        }
        true
    }

    /// Cancel an in-flight SSD restore or `.ikv` stage on `lane` (`Restoring -> Cancelled`), immediately
    /// signalling the background worker to stop and releasing all pre-reserved `BlockPool` slots
    /// with zero leaks.
    pub fn cancel_restore(&mut self, pools: &mut BlockPools, lane: usize) -> bool {
        let mut any = self.cancel_ikv_stage(pools, lane);
        if let Some(pr) = self.pending_restores.remove(&lane) {
            pr.cancel_flag.store(true, Ordering::Release);
            Self::release_restore_refs(pools, pr.reserved_slots);
            Self::release_restore_refs(pools, pr.held_reused);
            self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
            any = true;
        }
        any
    }

    pub fn cancel_all_restores(&mut self, pools: &mut BlockPools) {
        let r_lanes: Vec<usize> = self.pending_restores.keys().copied().collect();
        for l in r_lanes {
            self.cancel_restore(pools, l);
        }
        let s_lanes: Vec<usize> = self.pending_ikv_stages.keys().copied().collect();
        for l in s_lanes {
            self.cancel_ikv_stage(pools, l);
        }
    }

    /// Drain verified SSD blocks from the background restore worker into pre-reserved `BlockPool`
    /// slots and bind any completed (or corrupt-fallback) restores (`Restoring -> Ready`).
    pub fn poll_restores<F>(&mut self, pools: &mut BlockPools, mut lane_tables: F) -> Vec<CompletedRestore>
    where
        F: FnMut(usize) -> Option<(&'static (), *mut BlockTable, *mut LaneBlockState)>,
    {
        let mut ready_msgs = Vec::new();
        if let Some(worker) = self.restore_worker.as_ref() {
            while let Ok(msg) = worker.msg_rx.try_recv() {
                worker.budget.release(msg.budget_bytes);
                ready_msgs.push(msg);
            }
        }

        let mut completed = Vec::new();
        for msg in ready_msgs {
            let is_current = self.pending_restores.get(&msg.lane).is_some_and(|pr| pr.restore_seq == msg.restore_seq);
            if !is_current {
                continue;
            }
            match msg.payload {
                RestoreMsgPayload::RecurrentState { key, raw } => {
                    let outcome = self.spill_store.as_mut().map(|s| s.apply_raw_read(key, raw));
                    if let Some(ReadOutcome::Hit(blk)) = outcome {
                        if let Some(pr) = self.pending_restores.get_mut(&msg.lane) {
                            pr.loaded_cs = blk.recurrent_state;
                        }
                    }
                }
                RestoreMsgPayload::Block { idx, key, raw } => {
                    let outcome = self.spill_store.as_mut().map(|s| s.apply_raw_read(key, raw));
                    if let Some(ReadOutcome::Hit(blk)) = outcome {
                        if let Some(pr) = self.pending_restores.get_mut(&msg.lane) {
                            let (kind, _, entry) = pr.reserved_slots[idx];
                            let pool = pools.of_mut(kind);
                            pool.slot_bytes_mut(entry.slot())
                                .expect("reserved restore slot bytes")
                                .copy_from_slice(&blk.kv_bytes);
                            pool.on_slot_restored_from_spill(entry.slot());
                            pr.loaded_blocks += 1;
                        }
                    }
                }
                RestoreMsgPayload::Done { elapsed } => {
                    let pr = self.pending_restores.remove(&msg.lane).unwrap();
                    self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
                    let ok_complete = pr.loaded_cs.as_ref().is_some_and(|c| !c.is_empty())
                        && pr.loaded_blocks == pr.reserved_slots.len();
                    if ok_complete {
                        let mut held = pr.held_reused;
                        held.extend(pr.reserved_slots);
                        let elapsed_us = elapsed.as_micros().min(u128::from(u64::MAX)) as u64;
                        let cs = pr.loaded_cs.unwrap();
                        let _ = self.publish_restored_checkpoint(
                            pools,
                            pr.spill_id,
                            pr.namespace,
                            pr.pos,
                            pr.reasons,
                            cs,
                            &pr.full_toks[..pr.pos],
                            held,
                            elapsed_us,
                        );
                        let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
                            let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
                            st.namespace = pr.namespace;
                            self.bind_resident_start(pools, tbl, st, &pr.full_toks)
                        } else {
                            None
                        };
                        completed.push(CompletedRestore { lane: msg.lane, matched, elapsed, corrupt_fallback: false });
                    } else {
                        Self::release_restore_refs(pools, pr.reserved_slots);
                        Self::release_restore_refs(pools, pr.held_reused);
                        self.stats.corrupt_fallbacks += 1;
                        self.remove_spilled_start(pr.spill_id, true);
                        let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
                            let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
                            st.namespace = pr.namespace;
                            self.bind_resident_start(pools, tbl, st, &pr.full_toks)
                        } else {
                            None
                        };
                        completed.push(CompletedRestore { lane: msg.lane, matched, elapsed, corrupt_fallback: true });
                    }
                }
                RestoreMsgPayload::Aborted { key, raw } => {
                    if let Some(store) = self.spill_store.as_mut() {
                        let _ = store.apply_raw_read(key, raw);
                    }
                    let pr = self.pending_restores.remove(&msg.lane).unwrap();
                    pr.cancel_flag.store(true, Ordering::Release);
                    self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
                    Self::release_restore_refs(pools, pr.reserved_slots);
                    Self::release_restore_refs(pools, pr.held_reused);
                    self.stats.corrupt_fallbacks += 1;
                    self.remove_spilled_start(pr.spill_id, true);
                    let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
                        let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
                        st.namespace = pr.namespace;
                        self.bind_resident_start(pools, tbl, st, &pr.full_toks)
                    } else {
                        None
                    };
                    completed.push(CompletedRestore {
                        lane: msg.lane,
                        matched,
                        elapsed: Duration::ZERO,
                        corrupt_fallback: true,
                    });
                }
            }
        }
        completed
    }

    fn stage_restore_blocks(
        &mut self,
        pools: &mut BlockPools,
        source: &RestoreSource,
        disk_entries: &[(BlockKind, BlockIndex, SpillKey)],
        held: &mut Vec<(BlockKind, BlockIndex, BlockEntry)>,
    ) -> Option<()> {
        let mut verified_before_eviction = false;
        for (i, &(kind, bi, key)) in disk_entries.iter().enumerate() {
            if !verified_before_eviction && pools.of(kind).lowest_free().is_none() {
                // A bad file must not discard a healthy resident checkpoint. Only the
                // restore that needs eviction pays for this extra pass, one block at a time.
                for &(remaining_kind, _, remaining_key) in &disk_entries[i..] {
                    let len = pools.of(remaining_kind).stride_bytes() as usize;
                    self.read_restore_kv(source.spill_id, remaining_key, len)?;
                }
                verified_before_eviction = true;
            }
            let len = pools.of(kind).stride_bytes() as usize;
            let bytes = self.read_restore_kv(source.spill_id, key, len)?;
            let (slot, generation) = self.take_zeroed_slot_inner(pools, kind, Some(source)).ok()?;
            let pool = pools.of_mut(kind);
            pool.slot_bytes_mut(slot).ok()?.copy_from_slice(&bytes);
            pool.clear_gpu_zero_pending(slot);
            let rec = pool.record_mut(slot).unwrap();
            rec.set_length(BLOCK as u32).expect("set restored block length");
            rec.seal();
            rec.add_ref().expect("pin restored block");
            pool.on_slot_restored_from_spill(slot);
            let offset = pool.offset(slot).expect("restored slot offset");
            held.push((kind, bi, BlockEntry::new(slot, generation, offset, kind, pool.kvb())));
        }
        Some(())
    }

    fn read_restore_kv(&mut self, spill_id: u64, key: SpillKey, expected_len: usize) -> Option<Vec<u8>> {
        match self.spill_store.as_mut()?.read_block(key, Some(expected_len)) {
            ReadOutcome::Hit(block) => Some(block.kv_bytes),
            ReadOutcome::Miss(_) => {
                self.stats.corrupt_fallbacks += 1;
                self.remove_spilled_start(spill_id, true);
                None
            }
        }
    }

    fn release_restore_refs(pools: &mut BlockPools, held: Vec<(BlockKind, BlockIndex, BlockEntry)>) {
        for (kind, _, entry) in held {
            pools.of_mut(kind).record_mut(entry.slot()).unwrap().drop_ref().expect("drop restore ref");
        }
    }

    fn free_usable_slots(pool: &crate::blocks::BlockPool) -> usize {
        let mut free = 0usize;
        for i in 0..pool.len() {
            let slot = Slot::new((i + 1) as u32).expect("valid pool slot");
            let rec = pool.record(slot).expect("pool record");
            if rec.refs() == 0 && rec.generation() < u32::MAX {
                free += 1;
            }
        }
        free
    }

    /// Exact count of usable free + evictable slots in `kind`, excluding any slots pinned by
    /// active lanes or `protected_start`.
    fn reclaimable_slots(&self, pools: &BlockPools, kind: BlockKind, protected_start: Option<SealedId>) -> usize {
        let Some(psid) = protected_start else {
            return self.free_plus_evictable_slots(pools, kind);
        };
        let Some(pst) = self.starts.get(&psid) else {
            return self.free_plus_evictable_slots(pools, kind);
        };
        let mut protected_refs: HashMap<u32, u32> = HashMap::new();
        for &(ekind, _, e) in &pst.entries {
            if ekind == kind {
                *protected_refs.entry(e.slot().pool_index().get()).or_insert(0) += 1;
            }
        }
        let pool = pools.of(kind);
        let srefs = &self.start_slot_refs[kind_idx(kind)];
        let mut avail = 0usize;
        for i in 0..pool.len() {
            let slot = Slot::new((i + 1) as u32).expect("valid pool slot");
            let rec = pool.record(slot).expect("pool record");
            if rec.generation() < u32::MAX {
                let held_by_starts = srefs.get(i).copied().unwrap_or(0);
                let held_by_prot = protected_refs.get(&(i as u32)).copied().unwrap_or(0);
                if rec.refs() <= held_by_starts.saturating_sub(held_by_prot) {
                    avail += 1;
                }
            }
        }
        avail
    }

    /// Upfront check + minimal LRU victim prefix selection (`U105`):
    /// - If `need_win > reclaimable(Window)` or `need_full > reclaimable(Full)`, returns
    ///   `Err(CacheError::PoolExhausted(kind))` BEFORE evicting or spilling a single start point!
    /// - Otherwise returns the minimal ordered prefix of LRU `SealedId`s whose eviction brings
    ///   `(free_win, free_full)` to at least `(need_win, need_full)`, skipping any start point
    ///   whose slots are 100% pinned by active lanes.
    fn select_eviction_victims(
        &self,
        pools: &BlockPools,
        need_win: usize,
        need_full: usize,
        protected_start: Option<SealedId>,
    ) -> Result<Vec<SealedId>, CacheError> {
        if need_win > 0 {
            let avail_win = self.reclaimable_slots(pools, BlockKind::Window, protected_start);
            if need_win > avail_win {
                return Err(CacheError::PoolExhausted(BlockKind::Window));
            }
        }
        if need_full > 0 {
            let avail_full = self.reclaimable_slots(pools, BlockKind::Full, protected_start);
            if need_full > avail_full {
                return Err(CacheError::PoolExhausted(BlockKind::Full));
            }
        }

        let mut sim_free = [Self::free_usable_slots(&pools.window), Self::free_usable_slots(&pools.full)];
        if sim_free[0] >= need_win && sim_free[1] >= need_full {
            return Ok(Vec::new());
        }

        let mut protected_slot_refs: [HashMap<u32, u32>; 2] = [HashMap::new(), HashMap::new()];
        if let Some(psid) = protected_start {
            if let Some(pst) = self.starts.get(&psid) {
                for &(k, _, e) in &pst.entries {
                    *protected_slot_refs[kind_idx(k)].entry(e.slot().pool_index().get()).or_insert(0) += 1;
                }
            }
        }

        let mut cands: Vec<(SealedId, u64, usize)> = self
            .starts
            .iter()
            .filter(|(&sid, _)| Some(sid) != protected_start)
            .map(|(&sid, st)| (sid, st.last_used_tick, st.pos))
            .collect();
        cands.sort_by_key(|&(_, tick, pos)| (tick, std::cmp::Reverse(pos)));

        let mut dropped: [HashMap<u32, u32>; 2] = [HashMap::new(), HashMap::new()];
        let mut victims = Vec::new();
        for (sid, _, _) in cands {
            let st = &self.starts[&sid];
            let can_free_any = st.entries.iter().any(|&(kind, _, e)| {
                let ki = kind_idx(kind);
                let idx = e.slot().pool_index().get();
                let Ok(rec) = pools.of(kind).record(e.slot()) else {
                    return false;
                };
                if rec.generation() != e.generation() || rec.generation() == u32::MAX || rec.refs() == 0 {
                    return false;
                }
                let sref = self.start_slot_refs[ki].get(idx as usize).copied().unwrap_or(0);
                let pref = protected_slot_refs[ki].get(&idx).copied().unwrap_or(0);
                rec.refs() <= sref.saturating_sub(pref)
            });
            if !can_free_any {
                continue;
            }
            victims.push(sid);
            for &(kind, _, e) in &st.entries {
                let ki = kind_idx(kind);
                let idx = e.slot().pool_index().get();
                if let Ok(rec) = pools.of(kind).record(e.slot()) {
                    if rec.generation() == e.generation() && rec.generation() < u32::MAX && rec.refs() > 0 {
                        let d = dropped[ki].entry(idx).or_insert(0);
                        *d += 1;
                        if *d == rec.refs() {
                            sim_free[ki] += 1;
                        }
                    }
                }
            }
            if sim_free[0] >= need_win && sim_free[1] >= need_full {
                break;
            }
        }

        if sim_free[0] < need_win {
            return Err(CacheError::PoolExhausted(BlockKind::Window));
        }
        if sim_free[1] < need_full {
            return Err(CacheError::PoolExhausted(BlockKind::Full));
        }
        Ok(victims)
    }

    /// Non-mutating check: returns `true` iff `ensure_span_blocks(pools, tbl, p0, t)` can
    /// currently be satisfied from free + evictable unpinned slots.
    pub fn can_satisfy_span(&self, pools: &BlockPools, tbl: &BlockTable, p0: usize, t: usize) -> bool {
        if t == 0 {
            return true;
        }
        let lo_blk = p0 / BLOCK;
        let hi_blk = (p0 + t - 1) / BLOCK;
        let mut need_win = 0usize;
        let mut need_full = 0usize;
        for b in lo_blk..=hi_blk {
            let bi = BlockIndex::new(b as u32);
            let Ok(w) = tbl.get(BlockKind::Window, bi) else {
                return false;
            };
            if w.is_none() {
                need_win += 1;
            }
            let Ok(f) = tbl.get(BlockKind::Full, bi) else {
                return false;
            };
            if f.is_none() {
                need_full += 1;
            }
        }
        if need_win == 0 && need_full == 0 {
            return true;
        }
        need_win <= self.reclaimable_slots(pools, BlockKind::Window, None)
            && need_full <= self.reclaimable_slots(pools, BlockKind::Full, None)
    }

    #[allow(dead_code)]
    fn evict_start(&mut self, pools: &mut BlockPools, sid: SealedId) -> bool {
        self.evict_start_inner(pools, sid, true, None)
    }

    #[cfg(test)]
    pub(crate) fn evict_all_starts_for_test(&mut self, pools: &mut BlockPools) -> usize {
        let sids: Vec<SealedId> = self.starts.keys().copied().collect();
        let mut n = 0usize;
        for sid in sids {
            if self.evict_start(pools, sid) {
                n += 1;
            }
        }
        n
    }

    fn evict_start_inner(
        &mut self,
        pools: &mut BlockPools,
        sid: SealedId,
        allow_spill: bool,
        restore: Option<&RestoreSource>,
    ) -> bool {
        let Some(st) = self.starts.remove(&sid) else {
            return false;
        };
        self.unindex_retained_start_for_stitch(sid, st.namespace, &st.toks);
        self.retained_host_bytes = self.retained_host_bytes.saturating_sub(st.host_bytes());
        if allow_spill && self.spill_store.is_some() {
            self.spill_retained_start(pools, &st, restore);
        }
        let _ = self.tree.release_start(sid);
        for (kind, _, e) in st.entries {
            self.dec_start_slot_ref(kind, e.slot());
            let pool = pools.of_mut(kind);
            if let Ok(rec) = pool.record(e.slot()) {
                if rec.generation() == e.generation() && rec.refs() > 0 {
                    pool.record_mut(e.slot()).unwrap().drop_ref().unwrap();
                }
            }
        }
        self.tree.prune_unreferenced(sid);
        self.stats.start_points_evicted += 1;
        true
    }

    fn enforce_retained_host_budget(&mut self, pools: &mut BlockPools, protect_sid: Option<SealedId>) {
        while self.retained_host_bytes > self.max_retained_host_bytes {
            let mut victim: Option<(SealedId, u64, usize)> = None;
            for (&sid, st) in &self.starts {
                if protect_sid == Some(sid) && self.max_retained_host_bytes > 0 {
                    continue;
                }
                let better = match victim {
                    None => true,
                    Some((_, best_tick, best_pos)) => {
                        (st.last_used_tick, std::cmp::Reverse(st.pos)) < (best_tick, std::cmp::Reverse(best_pos))
                    }
                };
                if better {
                    victim = Some((sid, st.last_used_tick, st.pos));
                }
            }
            let Some((sid, _, _)) = victim else {
                break;
            };
            self.evict_start_inner(pools, sid, true, None);
        }
    }

    fn evict_one_lru_start_inner(
        &mut self,
        pools: &mut BlockPools,
        allow_spill: bool,
        restore: Option<&RestoreSource>,
    ) -> bool {
        let mut victim: Option<(SealedId, u64, usize)> = None;
        for (&sid, st) in &self.starts {
            if restore.is_some_and(|source| source.resident_start == Some(sid)) {
                continue;
            }
            let better = match victim {
                None => true,
                // Evict oldest LRU tick first; on a tie, evict deeper leaf before shallower shared root.
                Some((_, best_tick, best_pos)) => {
                    (st.last_used_tick, std::cmp::Reverse(st.pos)) < (best_tick, std::cmp::Reverse(best_pos))
                }
            };
            if better {
                victim = Some((sid, st.last_used_tick, st.pos));
            }
        }
        let Some((sid, _, _)) = victim else {
            return false;
        };
        self.evict_start_inner(pools, sid, allow_spill, restore)
    }

    /// Take one slot of `kind` without host-side full-slot CPU memset, evicting LRU retained
    /// start points only when total free + evictable slots can satisfy the request. Never grows
    /// the pool and never empties cached start points on an unsatisfiable request.
    #[cfg(any(test, standalone_blocks))]
    pub fn take_zeroed_slot(&mut self, pools: &mut BlockPools, kind: BlockKind) -> Result<(Slot, u32), CacheError> {
        self.take_zeroed_slot_inner(pools, kind, None)
    }

    fn take_zeroed_slot_inner(
        &mut self,
        pools: &mut BlockPools,
        kind: BlockKind,
        restore: Option<&RestoreSource>,
    ) -> Result<(Slot, u32), CacheError> {
        if let Some(slot) = pools.of(kind).lowest_free() {
            let pool = pools.of_mut(kind);
            let _ = pool.take_unzeroed(slot).expect("take slot");
            let gen = pool.record(slot).unwrap().generation();
            self.stats.slots_taken += 1;
            if gen > 1 {
                self.stats.slots_reused += 1;
            }
            return Ok((slot, gen));
        }
        let need_win = usize::from(kind == BlockKind::Window);
        let need_full = usize::from(kind == BlockKind::Full);
        let victims =
            self.select_eviction_victims(pools, need_win, need_full, restore.and_then(|r| r.resident_start))?;
        for sid in victims {
            self.evict_start_inner(pools, sid, true, restore);
        }
        let Some(slot) = pools.of(kind).lowest_free() else {
            return Err(CacheError::PoolExhausted(kind));
        };
        let pool = pools.of_mut(kind);
        let _ = pool.take_unzeroed(slot).expect("take slot");
        let gen = pool.record(slot).unwrap().generation();
        self.stats.slots_taken += 1;
        if gen > 1 {
            self.stats.slots_reused += 1;
        }
        Ok((slot, gen))
    }

    /// Ensure every `(Full, Window)` block covering span `[p0, p0 + t)` is allocated and unsealed
    /// in `tbl`, taking zeroed slots (with bounded LRU eviction if needed). Transactional on
    /// `PoolExhausted` and mid-span rollback: verifies upfront across BOTH `Window` and `Full`
    /// that `free + evictable >= needed` before evicting or spilling a single cached start point,
    /// evicts only the minimal LRU victim prefix needed, and leaves the cache untouched if aborted.
    pub fn ensure_span_blocks(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        p0: usize,
        t: usize,
    ) -> Result<(), CacheError> {
        self.try_ensure_span_blocks_with(pools, tbl, p0, t, |_, _| Ok(())).map(|_| ())
    }

    /// Transactional `ensure_span_blocks` returning the list of `(BlockKind, BlockIndex)` blocks
    /// newly allocated for `[p0, p0 + t)` so a speculative verify step can release any rejected
    /// draft blocks strictly past `p0 + n_keep` without violating `ServeOwnershipTrace` ref counts.
    pub fn ensure_span_blocks_tracking(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        p0: usize,
        t: usize,
    ) -> Result<Vec<(BlockKind, BlockIndex)>, CacheError> {
        self.try_ensure_span_blocks_with(pools, tbl, p0, t, |_, _| Ok(()))
    }

    pub(crate) fn try_ensure_span_blocks_with<F>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        p0: usize,
        t: usize,
        mut pre_step: F,
    ) -> Result<Vec<(BlockKind, BlockIndex)>, CacheError>
    where
        F: FnMut(usize, BlockKind) -> Result<(), CacheError>,
    {
        debug_assert!(t >= 1);
        let lo_blk = p0 / BLOCK;
        let hi_blk = (p0 + t - 1) / BLOCK;
        let mut missing: Vec<(BlockKind, BlockIndex)> = Vec::new();
        let mut need_win = 0usize;
        let mut need_full = 0usize;

        for b in lo_blk..=hi_blk {
            let bi = BlockIndex::new(b as u32);
            for kind in KINDS {
                let existing = tbl.get(kind, bi).expect("block in table range");
                if let Some(entry) = existing {
                    let rec = pools.of(kind).record(entry.slot()).expect("existing slot record");
                    assert_eq!(rec.generation(), entry.generation(), "stale entry in active lane table");
                    assert!(!rec.sealed(), "attempt to write into sealed {kind:?} block {b}");
                } else {
                    missing.push((kind, bi));
                    match kind {
                        BlockKind::Window => need_win += 1,
                        BlockKind::Full => need_full += 1,
                    }
                }
            }
        }
        if missing.is_empty() {
            return Ok(Vec::new());
        }

        // Phase 1: Upfront bounded capacity check + minimal victim selection BEFORE any eviction/spill.
        let victims = self.select_eviction_victims(pools, need_win, need_full, None)?;

        // Phase 2: Allocate from already-free slots first while running `pre_step`; defer victim
        // eviction until all pre-checks succeed (or take free slots up to the point where eviction
        // is required, rolling back taken free slots with zero cache evictions if `pre_step` aborts!).
        let mut newly_allocated: Vec<(BlockKind, BlockIndex)> = Vec::with_capacity(missing.len());
        let mut deferred_after_eviction: Vec<(BlockKind, BlockIndex)> = Vec::new();
        for (kind, bi) in missing {
            if let Err(err) = pre_step(bi.get() as usize, kind) {
                for (rk, rbi) in newly_allocated.into_iter().rev() {
                    tbl.clear_kind_entry(pools.of_mut(rk), rbi) // MUTANT_ANCHOR_SPAN_ROLLBACK
                        .expect("rollback newly allocated block entry");
                }
                return Err(err);
            }
            if let Some(slot) = pools.of(kind).lowest_free() {
                let pool = pools.of_mut(kind);
                let _ = pool.take_unzeroed(slot).expect("take slot");
                let gen = pool.record(slot).unwrap().generation();
                self.stats.slots_taken += 1;
                if gen > 1 {
                    self.stats.slots_reused += 1;
                }
                tbl.fill(pool, bi, slot, gen).expect("fill newly taken free slot");
                newly_allocated.push((kind, bi));
            } else {
                deferred_after_eviction.push((kind, bi));
            }
        }

        if !deferred_after_eviction.is_empty() {
            for sid in victims {
                self.evict_start_inner(pools, sid, true, None);
            }
            for (kind, bi) in deferred_after_eviction {
                let Some(slot) = pools.of(kind).lowest_free() else {
                    for (rk, rbi) in newly_allocated.into_iter().rev() {
                        tbl.clear_kind_entry(pools.of_mut(rk), rbi).expect("rollback newly allocated block entry");
                    }
                    return Err(CacheError::PoolExhausted(kind));
                };
                let pool = pools.of_mut(kind);
                let _ = pool.take_unzeroed(slot).expect("take slot");
                let gen = pool.record(slot).unwrap().generation();
                self.stats.slots_taken += 1;
                if gen > 1 {
                    self.stats.slots_reused += 1;
                }
                tbl.fill(pool, bi, slot, gen).expect("fill newly evicted slot");
                newly_allocated.push((kind, bi));
            }
        }

        Ok(newly_allocated)
    }

    fn prune_expired_window(&mut self, pools: &mut BlockPools, tbl: &mut BlockTable, start: usize, end: usize) {
        for b in newly_expired_window_blocks(start, end) {
            let bi = BlockIndex::new(b as u32);
            if tbl.get(BlockKind::Window, bi).expect("window block in range").is_some() {
                tbl.clear_kind_entry(&mut pools.window, bi).expect("prune expired window block");
                self.stats.window_pruned += 1;
            }
        }
    }

    /// Post-prefill bookkeeping: update lengths, seal completed 64-token blocks into `EntryTree`,
    /// deduplicate against live canonical blocks, retain `EVERY` / `PROMPT` start points, and
    /// prune expired sliding-window blocks.
    pub fn finish_prefill_span<F>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        p0: usize,
        t: usize,
        read_cs: F,
    ) where
        F: FnOnce() -> Vec<u8>,
    {
        let end = p0 + t;
        state.written = end;
        let lo_blk = p0 / BLOCK;
        let hi_blk = (end - 1) / BLOCK;
        for b in lo_blk..=hi_blk {
            let bi = BlockIndex::new(b as u32);
            let block_len = (end - b * BLOCK).min(BLOCK) as u32;
            let full_e = tbl.get(BlockKind::Full, bi).unwrap().expect("full entry");
            let win_e = tbl.get(BlockKind::Window, bi).unwrap().expect("window entry");
            for (kind, e) in [(BlockKind::Full, full_e), (BlockKind::Window, win_e)] {
                let rec = pools.of_mut(kind).record_mut(e.slot()).unwrap();
                rec.set_length(block_len).expect("set block length");
                if block_len == BLOCK as u32 {
                    rec.seal();
                }
            }
            if block_len == BLOCK as u32 {
                self.stats.blocks_sealed += 1;
                if !state.stitched_approx && (b == 0 || state.sealed.len() == b) {
                    let parent = if b == 0 { None } else { state.sealed.get(b - 1).copied() };
                    let blk_toks = &toks[b * BLOCK..(b + 1) * BLOCK];
                    let handles = BlockHandles::new(full_e, Some(win_e));
                    let id = self
                        .tree
                        .insert_in_namespace(state.namespace, parent, b * BLOCK, blk_toks, handles)
                        .expect("insert sealed block into EntryTree");
                    let canon = self.tree.handle(id).expect("inserted handle");
                    let canon_f = canon.full();
                    let canon_w = canon.window();
                    let mut best_f = full_e;
                    let mut best_w = win_e;
                    if canon_f != full_e && entry_is_live_sealed(pools, BlockKind::Full, canon_f) {
                        tbl.fill(&mut pools.full, bi, canon_f.slot(), canon_f.generation())
                            .expect("share canonical full block");
                        best_f = canon_f;
                        self.stats.shared_dedups += 1;
                    }
                    if let Some(canon_w) =
                        canon_w.filter(|&w| w != win_e && entry_is_live_sealed(pools, BlockKind::Window, w))
                    {
                        tbl.fill(&mut pools.window, bi, canon_w.slot(), canon_w.generation())
                            .expect("share canonical window block");
                        best_w = canon_w;
                    }
                    if best_f != canon_f || Some(best_w) != canon_w {
                        let _ = self.tree.set_handle(id, BlockHandles::new(best_f, Some(best_w)));
                    }
                    self.tree.pin(id).expect("pin newly sealed block");
                    if state.sealed.len() == b {
                        state.sealed.push(id);
                    } else {
                        let old = state.sealed[b];
                        if old != id {
                            self.tree.unpin(old);
                        }
                        state.sealed[b] = id;
                    }
                }
            }
        }
        // Retain start points on 64-token boundaries ONLY on genuine exact prefill lanes (`!state.stitched_approx`).
        // Stitched lanes hold their blocks privately until `release_lane` so `EntryTree` and `starts` stay 100% exact
        // and stitches never chain onto stitches.
        if !state.stitched_approx && end > 0 && end.is_multiple_of(BLOCK) && state.sealed.len() == end / BLOCK {
            let prompt_ckpt = ((state.prompt_len.saturating_sub(1)) / BLOCK) * BLOCK;
            let mut reasons = 0u8;
            if (prompt_ckpt > 0 && end == prompt_ckpt) || end == state.prompt_len {
                reasons |= PROMPT;
            }
            if is_every_checkpoint(end) {
                reasons |= EVERY;
            }
            if reasons != 0 {
                let tip = *state.sealed.last().unwrap();
                self.tick += 1;
                let now = self.tick;
                let keep_toks = self.spill_store.is_some() || self.kv_stitch;
                let mut check_host_budget = false;
                if let Some(existing) = self.starts.get_mut(&tip) {
                    existing.reasons |= reasons;
                    existing.last_used_tick = now;
                    if keep_toks && existing.toks.is_empty() {
                        let added = (end as u64).saturating_mul(4);
                        existing.toks = toks[..end].to_vec();
                        self.retained_host_bytes = self.retained_host_bytes.saturating_add(added);
                        self.index_retained_start_for_stitch(tip);
                        check_host_budget = true;
                    }
                } else {
                    let cs = read_cs();
                    let mut entries = Vec::with_capacity(end / BLOCK + WINDOW / BLOCK);
                    for b in 0..(end / BLOCK) {
                        let bi = BlockIndex::new(b as u32);
                        let fe = tbl.get(BlockKind::Full, bi).unwrap().expect("start point full block");
                        entries.push((BlockKind::Full, bi, fe));
                    }
                    let win_lo = end.saturating_sub(WINDOW) / BLOCK;
                    for b in win_lo..(end / BLOCK) {
                        let bi = BlockIndex::new(b as u32);
                        let we = tbl.get(BlockKind::Window, bi).unwrap().expect("start point window block");
                        entries.push((BlockKind::Window, bi, we));
                    }
                    for &(kind, _, e) in &entries {
                        pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain start point ref");
                        self.inc_start_slot_ref(kind, e.slot()); // MUTANT_ANCHOR_START_SLOT_REF
                    }
                    self.tree.retain_start(tip).expect("retain start in EntryTree");
                    let st = RetainedStart {
                        namespace: state.namespace,
                        pos: end,
                        cs,
                        reasons,
                        entries,
                        toks: if keep_toks { toks[..end].to_vec() } else { Vec::new() },
                        last_used_tick: now,
                    };
                    self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
                    self.starts.insert(tip, st);
                    self.index_retained_start_for_stitch(tip);
                    self.stats.start_points_saved += 1;
                    check_host_budget = true;
                }
                if check_host_budget {
                    self.enforce_retained_host_budget(pools, Some(tip));
                }
            }
        }
        self.prune_expired_window(pools, tbl, p0, end);
    }

    /// Post-decode bookkeeping: update unsealed block length (never sealed into `EntryTree`)
    /// and prune expired sliding-window blocks.
    pub fn finish_decode_span(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        pos: usize,
    ) {
        let end = pos + 1;
        state.written = end;
        let b = pos / BLOCK;
        let bi = BlockIndex::new(b as u32);
        let block_len = (end - b * BLOCK).min(BLOCK) as u32;
        for kind in KINDS {
            let e = tbl.get(kind, bi).unwrap().expect("decode block entry");
            // Decode-written blocks stay private to the lane and are never sealed into EntryTree.
            pools.of_mut(kind).record_mut(e.slot()).unwrap().set_length(block_len).expect("set decode length");
        }
        self.prune_expired_window(pools, tbl, pos, end);
    }

    /// Post-verify bookkeeping after `Engine::rollback_verify(..., n_keep)`:
    /// - Releases any newly allocated unsealed draft blocks strictly past `p0 + n_keep`
    ///   (or all newly allocated blocks when `n_keep == 0`) back to `BlockPools`, preserving
    ///   `ServeOwnershipTrace` `PoolRefConservation` identically.
    /// - Updates unsealed `SlotRecord::length` for retained blocks in `[p0, p0 + n_keep)` without
    ///   ever sealing speculative/decode blocks into `EntryTree`.
    /// - Prunes expired `Window` blocks ONLY up to `p0 + n_keep` (never to the rejected draft end).
    pub fn finish_verify_span(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        allocated: &[(BlockKind, BlockIndex)],
        p0: usize,
        n_keep: usize,
    ) {
        if n_keep == 0 {
            for &(kind, bi) in allocated.iter().rev() {
                tbl.clear_kind_entry(pools.of_mut(kind), bi).expect("release aborted verify draft block");
            }
            return;
        }
        let accepted_end = p0 + n_keep;
        for &(kind, bi) in allocated.iter().rev() {
            let blk_start = (bi.get() as usize) * BLOCK;
            if blk_start >= accepted_end {
                tbl.clear_kind_entry(pools.of_mut(kind), bi).expect("release rejected verify draft block");
            }
        }
        let lo_blk = p0 / BLOCK;
        let hi_blk = (accepted_end - 1) / BLOCK;
        for b in lo_blk..=hi_blk {
            let bi = BlockIndex::new(b as u32);
            let block_len = (accepted_end - b * BLOCK).min(BLOCK) as u32;
            for kind in KINDS {
                let e = tbl.get(kind, bi).unwrap().expect("retained verify block entry");
                let rec = pools.of_mut(kind).record_mut(e.slot()).unwrap();
                assert!(!rec.sealed(), "verify must never seal {kind:?} block {b}");
                rec.set_length(block_len).expect("set verify block length");
            }
        }
        state.written = accepted_end;
        self.prune_expired_window(pools, tbl, p0, accepted_end);
    }

    /// Plan non-overlapping Zero-RoPE shifted-span `Full`-KV stitches (`>= MIN_STITCH_TOKENS` = `2,688`)
    /// across `toks[matched_pos .. toks.len()]` in `namespace` at **any** aligned or unaligned token offset.
    /// Donors are strictly genuine exact `RetainedStart`s in the same `namespace` or verified, non-quarantined
    /// `.ikv` cartridges in `self.ikv_namespace`. Each plan reserves `stitch_start - span_start >= LEFT_HEAL_TOKENS`
    /// (`1,024` tokens) at the left SWA boundary and `span_end - heal_start >= MIN_HEAL_TOKENS` (`1,536` tokens)
    /// at the right approximate SWA + `cs` boundary-convergence ramp.
    pub fn plan_stitches(
        &self,
        pools: &BlockPools,
        namespace: u64,
        toks: &[u32],
        matched_pos: usize,
    ) -> Vec<StitchSpanPlan> {
        if !self.kv_stitch || toks.len() < matched_pos.saturating_add(MIN_STITCH_TOKENS) || toks.len() < BLOCK {
            return Vec::new();
        }
        let has_ikv = namespace == self.ikv_namespace // MUTANT_ANCHOR_STITCH_IKV_NS
            && pools.full.slab_count() > 0
            && self.ikv_catalog.as_ref().is_some_and(|c| !c.is_empty());
        if !has_ikv && self.stitch_index.is_empty() {
            return Vec::new();
        }

        let mut plans = Vec::new();
        let mut min_start = matched_pos;
        let last_anchor_pos = toks.len() - BLOCK;
        if min_start > last_anchor_pos {
            return plans;
        }
        let mut covered_ret_diags: HashMap<(SealedId, usize), usize> = HashMap::new();
        let mut covered_ikv_diags: HashMap<(usize, usize), usize> = HashMap::new();

        let mut i = min_start;
        let mut h = stitch_hash_64(&toks[i..i + BLOCK]);
        loop {
            let mut best: Option<(usize, bool, usize, StitchSpanPlan)> = None;

            if has_ikv {
                if let Some(cat) = &self.ikv_catalog {
                    if let Some(cands) = cat.lookup_anchor(h) {
                        for &(cart_idx, page_idx) in cands {
                            let src_anchor = (page_idx as usize) * BLOCK;
                            let diag = i.wrapping_sub(src_anchor);
                            if covered_ikv_diags.get(&(cart_idx, diag)).is_some_and(|&cov_end| i < cov_end) {
                                continue;
                            }
                            let Some(cart) = cat.get(cart_idx) else {
                                continue;
                            };
                            if cart.is_quarantined() {
                                continue;
                            }
                            let ctoks = cart.tokens();
                            if src_anchor + BLOCK > ctoks.len()
                                || ctoks[src_anchor..src_anchor + BLOCK] != toks[i..i + BLOCK]
                            {
                                continue;
                            }
                            let mut s_start = i;
                            let mut c_start = src_anchor;
                            while s_start > min_start && c_start > 0 && toks[s_start - 1] == ctoks[c_start - 1] {
                                s_start -= 1;
                                c_start -= 1;
                            }
                            let mut s_end = i + BLOCK;
                            let mut c_end = src_anchor + BLOCK;
                            while s_end < toks.len() && c_end < ctoks.len() && toks[s_end] == ctoks[c_end] {
                                s_end += 1;
                                c_end += 1;
                            }
                            let cov = covered_ikv_diags.entry((cart_idx, diag)).or_insert(0);
                            *cov = (*cov).max(s_end);
                            if s_end - s_start >= MIN_STITCH_TOKENS {
                                let stitch_start = (s_start + LEFT_HEAL_TOKENS).div_ceil(BLOCK) * BLOCK;
                                let heal_start = (s_end.saturating_sub(MIN_HEAL_TOKENS) / BLOCK) * BLOCK;
                                if heal_start >= stitch_start + BLOCK {
                                    let src_start = c_start + (stitch_start - s_start);
                                    let stitched = heal_start - stitch_start;
                                    let cand = StitchSpanPlan {
                                        span_start: s_start,
                                        stitch_start,
                                        heal_start,
                                        span_end: s_end,
                                        source: StitchSource::Ikv { cart_idx, src_start },
                                    };
                                    if best.is_none_or(|(bs, bzc, _, _)| (stitched, false) > (bs, bzc)) {
                                        best = Some((stitched, false, s_end, cand));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if let Some(cands) = self.stitch_index.get(&(namespace, h)) {
                for &(sid, blk_idx) in cands {
                    let src_anchor = (blk_idx as usize) * BLOCK;
                    let diag = i.wrapping_sub(src_anchor);
                    if covered_ret_diags.get(&(sid, diag)).is_some_and(|&cov_end| i < cov_end) {
                        continue;
                    }
                    let Some(st) = self.starts.get(&sid) else {
                        continue;
                    };
                    if st.namespace != namespace || src_anchor + BLOCK > st.toks.len() {
                        continue;
                    }
                    if st.toks[src_anchor..src_anchor + BLOCK] != toks[i..i + BLOCK] {
                        continue;
                    }
                    let full_cnt = st.pos / BLOCK;
                    if st.entries.len() < full_cnt {
                        continue;
                    }
                    let mut s_start = i;
                    let mut a_start = src_anchor;
                    while s_start > min_start && a_start > 0 && toks[s_start - 1] == st.toks[a_start - 1] {
                        s_start -= 1;
                        a_start -= 1;
                    }
                    let mut s_end = i + BLOCK;
                    let mut a_end = src_anchor + BLOCK;
                    while s_end < toks.len() && a_end < st.toks.len() && toks[s_end] == st.toks[a_end] {
                        s_end += 1;
                        a_end += 1;
                    }
                    let cov = covered_ret_diags.entry((sid, diag)).or_insert(0);
                    *cov = (*cov).max(s_end);
                    if s_end - s_start >= MIN_STITCH_TOKENS {
                        let stitch_start = (s_start + LEFT_HEAL_TOKENS).div_ceil(BLOCK) * BLOCK; // MUTANT_ANCHOR_STITCH_LEFT_HEAL
                        let heal_start = (s_end.saturating_sub(MIN_HEAL_TOKENS) / BLOCK) * BLOCK; // MUTANT_ANCHOR_STITCH_HEAL_START
                        if heal_start >= stitch_start + BLOCK {
                            let src_start = a_start + (stitch_start - s_start);
                            let src_end = src_start + (heal_start - stitch_start);
                            let lo_sb = src_start / BLOCK;
                            let hi_sb = (src_end - 1) / BLOCK;
                            let is_zc = src_start.is_multiple_of(BLOCK);
                            if !is_zc && pools.full.slab_count() == 0 {
                                continue;
                            }
                            let all_live = hi_sb < full_cnt
                                && st.entries[lo_sb..=hi_sb].iter().enumerate().all(|(off, &(k, bi, fe))| {
                                    k == BlockKind::Full
                                        && bi.get() as usize == lo_sb + off
                                        && entry_is_live_sealed(pools, BlockKind::Full, fe)
                                });
                            if all_live {
                                let stitched = heal_start - stitch_start;
                                let cand = StitchSpanPlan {
                                    span_start: s_start,
                                    stitch_start,
                                    heal_start,
                                    span_end: s_end,
                                    source: StitchSource::Retained { sid, src_start },
                                };
                                if best.is_none_or(|(bs, bzc, _, _)| (stitched, is_zc) > (bs, bzc)) {
                                    best = Some((stitched, is_zc, s_end, cand));
                                }
                            }
                        }
                    }
                }
            }

            if let Some((_, _, s_end, plan)) = best {
                plans.push(plan);
                min_start = s_end;
                covered_ret_diags.clear();
                covered_ikv_diags.clear();
                if min_start > last_anchor_pos {
                    break;
                }
                i = min_start;
                h = stitch_hash_64(&toks[i..i + BLOCK]);
                continue;
            }

            if i >= last_anchor_pos {
                break;
            }
            h = slide_stitch_hash_64(h, toks[i], toks[i + BLOCK]);
            i += 1;
        }
        plans
    }

    fn finish_binding_stitched_lane(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        plan: &StitchSpanPlan,
        missing_win_blks: Vec<BlockIndex>,
    ) -> usize {
        self.prune_expired_window(pools, tbl, plan.stitch_start, plan.heal_start);
        if !missing_win_blks.is_empty() {
            let w_slot = pools.window.lowest_free().expect("verified free window slot for stitch healing");
            let _ = pools.window.take(w_slot).expect("take zero-filled window slot for stitch healing");
            let w_gen = pools.window.record(w_slot).unwrap().generation();
            self.stats.slots_taken += 1;
            if w_gen > 1 {
                self.stats.slots_reused += 1;
            }
            {
                let w_rec = pools.window.record_mut(w_slot).unwrap();
                w_rec.set_length(BLOCK as u32).expect("set zeroed window length");
                w_rec.seal();
            }
            for bi in missing_win_blks {
                tbl.fill(&mut pools.window, bi, w_slot, w_gen).expect("bind zeroed window slot for stitch healing");
            }
        }
        // Provenance isolation: mark lane approximate so neither stitched blocks nor post-stitch
        // prefill blocks ever enter `EntryTree` or `starts`, and keep `cached_tokens_total` strictly exact.
        state.stitched_approx = true; // MUTANT_ANCHOR_STITCH_PROVENANCE
        state.written = plan.heal_start;
        let stitched_tokens = plan.heal_start - plan.stitch_start;
        self.stats.stitch_hits += 1;
        self.stats.stitched_tokens_total += stitched_tokens as u64;
        stitched_tokens
    }

    /// Start a stitch plan without blocking active GPU decode ticks on disk I/O:
    /// - `StitchSource::Retained`: applies immediately in RAM (`StitchStartOutcome::Applied`).
    /// - `StitchSource::Ikv`: pre-reserves destination `BlockPools::full` slots and streams
    ///   `F_NOCACHE` `pread` + per-page `SHA-256` verification on the background `IkvStageWorker`
    ///   (`StitchStartOutcome::Staging`), completing via [`Self::poll_ikv_stages`].
    pub fn start_stitch_plan(
        &mut self,
        pools: &mut BlockPools,
        lane: usize,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        plan: &StitchSpanPlan,
    ) -> StitchStartOutcome {
        if self.pending_ikv_stages.contains_key(&lane) {
            return StitchStartOutcome::Staging;
        }
        let StitchSource::Ikv { cart_idx, src_start } = plan.source else {
            return match self.apply_stitch_plan(pools, tbl, state, toks, plan) {
                StitchApplyOutcome::Applied { stitched_tokens, zero_copy_blocks } => {
                    StitchStartOutcome::Applied { stitched_tokens, zero_copy_blocks }
                }
                StitchApplyOutcome::SourceGone => StitchStartOutcome::SourceGone,
                StitchApplyOutcome::PoolBusy => StitchStartOutcome::PoolBusy,
            };
        };

        if !self.kv_stitch
            || plan.stitch_start >= plan.heal_start
            || !plan.stitch_start.is_multiple_of(BLOCK)
            || !plan.heal_start.is_multiple_of(BLOCK)
            || state.written != plan.stitch_start
            || plan.heal_start >= toks.len()
            || state.namespace != self.ikv_namespace
            || pools.full.slab_count() == 0
        {
            return StitchStartOutcome::SourceGone;
        }
        let lo_blk = plan.stitch_start / BLOCK;
        let hi_blk = plan.heal_start / BLOCK;
        let n_stitch_blks = hi_blk - lo_blk;
        for b in lo_blk..hi_blk {
            match tbl.get(BlockKind::Full, BlockIndex::new(b as u32)) {
                Ok(None) => {}
                _ => return StitchStartOutcome::SourceGone,
            }
        }
        let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
        let mut need_win = 0usize;
        for b in lo_blk.max(lo_win_blk)..hi_blk {
            match tbl.get(BlockKind::Window, BlockIndex::new(b as u32)) {
                Ok(None) => need_win = 1,
                Ok(Some(_)) => {}
                Err(_) => return StitchStartOutcome::SourceGone,
            }
        }
        if need_win > 0 && pools.window.slab_count() == 0 {
            return StitchStartOutcome::SourceGone;
        }
        let (usable_win, _) = self.pool_headroom(pools, BlockKind::Window);
        let (usable_full, _) = self.pool_headroom(pools, BlockKind::Full);
        if need_win > usable_win || n_stitch_blks > usable_full {
            return StitchStartOutcome::SourceGone;
        }
        let Some(cat) = self.ikv_catalog.clone() else {
            return StitchStartOutcome::SourceGone;
        };
        let Some(cart) = cat.get(cart_idx) else {
            return StitchStartOutcome::SourceGone;
        };
        let src_end = src_start + n_stitch_blks * BLOCK;
        if cart.is_quarantined()
            || cart.header().kvb != pools.full.kvb()
            || src_end > cart.n_tokens()
            || cart.tokens()[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
        {
            return StitchStartOutcome::SourceGone;
        }
        let Ok(victims) = self.select_eviction_victims(pools, need_win, n_stitch_blks, None) else {
            return StitchStartOutcome::PoolBusy;
        };
        for v in victims {
            self.evict_start_inner(pools, v, true, None);
        }
        let mut reserved_slots: Vec<(Slot, u32)> = Vec::with_capacity(n_stitch_blks);
        for _ in 0..n_stitch_blks {
            let Some(slot) = pools.full.lowest_free() else {
                for (s, _) in reserved_slots {
                    let _ = pools.full.record_mut(s).unwrap().drop_ref();
                }
                return StitchStartOutcome::PoolBusy;
            };
            let _ = pools.full.take_unzeroed(slot).expect("take slot for async ikv stage");
            let gen = pools.full.record(slot).unwrap().generation();
            pools.full.record_mut(slot).unwrap().add_ref().expect("reserve slot for async ikv stage");
            self.stats.slots_taken += 1;
            if gen > 1 {
                self.stats.slots_reused += 1;
            }
            reserved_slots.push((slot, gen));
        }

        state.bound_lane = Some(lane);
        let stage_seq = self.next_ikv_stage_seq;
        self.next_ikv_stage_seq = self.next_ikv_stage_seq.wrapping_add(1).max(1);
        let cancel_flag = Arc::new(AtomicBool::new(false));
        let began = Instant::now();
        self.pending_ikv_stages.insert(
            lane,
            PendingIkvStage {
                stage_seq,
                plan: *plan,
                reserved_slots,
                loaded_blocks: 0,
                cancel_flag: cancel_flag.clone(),
            },
        );
        let wake = self.shared_wake.clone();
        let worker = self.ikv_stage_worker.get_or_insert_with(|| IkvStageWorker::spawn(wake));
        if worker
            .job_tx
            .as_ref()
            .and_then(|tx| {
                tx.send(IkvStageJob {
                    lane,
                    stage_seq,
                    lane_namespace: state.namespace,
                    expected_namespace: self.ikv_namespace,
                    catalog: cat,
                    cart_idx,
                    src_start,
                    n_stitch_blks,
                    cancel_flag,
                    began,
                })
                .ok()
            })
            .is_none()
        {
            self.cancel_ikv_stage(pools, lane);
            return StitchStartOutcome::SourceGone;
        }
        StitchStartOutcome::Staging
    }

    /// Drain verified `.ikv` 64-token blocks from the background `IkvStageWorker` into pre-reserved
    /// `BlockPools::full` slots and complete ready (or quarantined-fallback) `.ikv` stitches.
    pub fn poll_ikv_stages<F>(&mut self, pools: &mut BlockPools, mut lane_tables: F) -> Vec<CompletedIkvStage>
    where
        F: FnMut(usize) -> Option<(&'static (), *mut BlockTable, *mut LaneBlockState)>,
    {
        let mut ready_msgs = Vec::new();
        if let Some(worker) = self.ikv_stage_worker.as_ref() {
            while let Ok(msg) = worker.msg_rx.try_recv() {
                worker.budget.release(msg.budget_bytes);
                ready_msgs.push(msg);
            }
        }
        let mut completed = Vec::new();
        for msg in ready_msgs {
            let is_current = self.pending_ikv_stages.get(&msg.lane).is_some_and(|ps| ps.stage_seq == msg.stage_seq);
            if !is_current {
                continue;
            }
            match msg.payload {
                IkvStagePayload::Block { idx, bytes } => {
                    if let Some(ps) = self.pending_ikv_stages.get_mut(&msg.lane) {
                        if let Some(&(slot, _)) = ps.reserved_slots.get(idx) {
                            pools
                                .full
                                .slot_bytes_mut(slot)
                                .expect("reserved ikv stage slot bytes")
                                .copy_from_slice(&bytes);
                            ps.loaded_blocks += 1;
                        }
                    }
                }
                IkvStagePayload::Done { elapsed } => {
                    let ps = self.pending_ikv_stages.remove(&msg.lane).unwrap();
                    let plan = ps.plan;
                    let lo_blk = plan.stitch_start / BLOCK;
                    let hi_blk = plan.heal_start / BLOCK;
                    let all_loaded = ps.loaded_blocks == ps.reserved_slots.len();
                    if !all_loaded {
                        for (s, _) in ps.reserved_slots {
                            let _ = pools.full.record_mut(s).unwrap().drop_ref();
                        }
                        self.stats.corrupt_fallbacks += 1;
                        self.sync_ikv_quarantined_stat();
                        completed.push(CompletedIkvStage {
                            lane: msg.lane,
                            stitched_tokens: None,
                            heal_start: plan.heal_start,
                            elapsed,
                            corrupt_fallback: true,
                        });
                        continue;
                    }
                    let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) else {
                        for (s, _) in ps.reserved_slots {
                            let _ = pools.full.record_mut(s).unwrap().drop_ref();
                        }
                        continue;
                    };
                    let (tbl, state) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
                    let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
                    let mut missing_win_blks = Vec::new();
                    let mut valid_tbl = state.written == plan.stitch_start;
                    for b in lo_blk.max(lo_win_blk)..hi_blk {
                        let bi = BlockIndex::new(b as u32);
                        match tbl.get(BlockKind::Window, bi) {
                            Ok(None) => missing_win_blks.push(bi),
                            Ok(Some(_)) => {}
                            Err(_) => valid_tbl = false,
                        }
                    }
                    let need_win = usize::from(!missing_win_blks.is_empty());
                    if valid_tbl && need_win > 0 && pools.window.lowest_free().is_none() {
                        if let Ok(victims) = self.select_eviction_victims(pools, need_win, 0, None) {
                            for v in victims {
                                self.evict_start_inner(pools, v, true, None);
                            }
                        } else {
                            valid_tbl = false;
                        }
                    }
                    if !valid_tbl || (need_win > 0 && pools.window.lowest_free().is_none()) {
                        for (s, _) in ps.reserved_slots {
                            let _ = pools.full.record_mut(s).unwrap().drop_ref();
                        }
                        completed.push(CompletedIkvStage {
                            lane: msg.lane,
                            stitched_tokens: None,
                            heal_start: plan.heal_start,
                            elapsed,
                            corrupt_fallback: false,
                        });
                        continue;
                    }
                    for (k, (slot, gen)) in ps.reserved_slots.into_iter().enumerate() {
                        pools.full.clear_gpu_zero_pending(slot);
                        {
                            let rec = pools.full.record_mut(slot).unwrap();
                            rec.set_length(BLOCK as u32).expect("set ikv staged block length");
                            rec.seal();
                        }
                        pools.full.on_slot_restored_from_spill(slot);
                        let bi = BlockIndex::new((lo_blk + k) as u32);
                        tbl.fill(&mut pools.full, bi, slot, gen).expect("bind staged ikv full block");
                        pools.full.record_mut(slot).unwrap().drop_ref().expect("drop provisional ikv stage ref");
                    }
                    let stitched_tokens = self.finish_binding_stitched_lane(pools, tbl, state, &plan, missing_win_blks);
                    completed.push(CompletedIkvStage {
                        lane: msg.lane,
                        stitched_tokens: Some(stitched_tokens),
                        heal_start: plan.heal_start,
                        elapsed,
                        corrupt_fallback: false,
                    });
                }
                IkvStagePayload::Aborted { elapsed } => {
                    let ps = self.pending_ikv_stages.remove(&msg.lane).unwrap();
                    ps.cancel_flag.store(true, Ordering::Release);
                    for (s, _) in ps.reserved_slots {
                        let _ = pools.full.record_mut(s).unwrap().drop_ref();
                    }
                    self.stats.corrupt_fallbacks += 1;
                    self.sync_ikv_quarantined_stat();
                    completed.push(CompletedIkvStage {
                        lane: msg.lane,
                        stitched_tokens: None,
                        heal_start: ps.plan.heal_start,
                        elapsed,
                        corrupt_fallback: true,
                    });
                }
            }
        }
        completed
    }

    /// Execute one planned `Full`-KV stitch `[plan.stitch_start .. plan.heal_start)` into `tbl` and `state`:
    /// - Zero-copy shares sealed `BlockPools::full` slots when `src_start % 64 == 0` on a live `RetainedStart`.
    /// - Copies exact K/V rows across all `128` `(pass, plane, head)` slices when unaligned (`1..63`) or reading `.ikv`.
    /// - Prunes expired `Window` blocks `< lo_win_blk` and binds one zero-filled sealed `Window` guard slot across
    ///   missing `Window` positions in `[lo_win_blk .. heal_blk)` so `encode_spans` runs the `>= 1,024`-token
    ///   approximate SWA + `cs` boundary-convergence ramp `[heal_start .. span_end)`.
    /// - Marks `state.stitched_approx = true` so neither stitched blocks nor post-stitch prefill blocks ever
    ///   enter `EntryTree` or `starts`.
    pub fn apply_stitch_plan(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        plan: &StitchSpanPlan,
    ) -> StitchApplyOutcome {
        if !self.kv_stitch
            || plan.stitch_start >= plan.heal_start
            || !plan.stitch_start.is_multiple_of(BLOCK)
            || !plan.heal_start.is_multiple_of(BLOCK)
            || state.written != plan.stitch_start
            || plan.heal_start >= toks.len()
        {
            return StitchApplyOutcome::SourceGone;
        }
        let lo_blk = plan.stitch_start / BLOCK;
        let hi_blk = plan.heal_start / BLOCK;
        let n_stitch_blks = hi_blk - lo_blk;
        for b in lo_blk..hi_blk {
            match tbl.get(BlockKind::Full, BlockIndex::new(b as u32)) {
                Ok(None) => {}
                _ => return StitchApplyOutcome::SourceGone,
            }
        }
        let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
        let mut missing_win_blks = Vec::new();
        for b in lo_blk.max(lo_win_blk)..hi_blk {
            let bi = BlockIndex::new(b as u32);
            match tbl.get(BlockKind::Window, bi) {
                Ok(None) => missing_win_blks.push(bi),
                Ok(Some(_)) => {}
                Err(_) => return StitchApplyOutcome::SourceGone,
            }
        }
        let need_win = usize::from(!missing_win_blks.is_empty());
        if need_win > 0 && pools.window.slab_count() == 0 {
            return StitchApplyOutcome::SourceGone;
        }
        let (usable_win, _) = self.pool_headroom(pools, BlockKind::Window);
        let (usable_full, _) = self.pool_headroom(pools, BlockKind::Full);
        if need_win > usable_win {
            return StitchApplyOutcome::SourceGone;
        }

        let mut zero_copy_blocks = 0usize;
        match plan.source {
            StitchSource::Retained { sid, src_start } if src_start.is_multiple_of(BLOCK) => {
                let src_entries: Vec<BlockEntry> = {
                    let Some(st) = self.starts.get(&sid) else {
                        return StitchApplyOutcome::SourceGone;
                    };
                    let src_end = src_start + n_stitch_blks * BLOCK;
                    let full_cnt = st.pos / BLOCK;
                    if st.namespace != state.namespace // MUTANT_ANCHOR_STITCH_APPLY_NS_ZC
                        || src_end > st.toks.len()
                        || st.entries.len() < full_cnt
                        || st.toks[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
                    {
                        return StitchApplyOutcome::SourceGone;
                    }
                    let lo_sb = src_start / BLOCK;
                    let mut out = Vec::with_capacity(n_stitch_blks);
                    for k in 0..n_stitch_blks {
                        let (kind, bi, fe) = st.entries[lo_sb + k];
                        if kind != BlockKind::Full
                            || bi.get() as usize != lo_sb + k
                            || !entry_is_live_sealed(pools, BlockKind::Full, fe)
                        {
                            return StitchApplyOutcome::SourceGone;
                        }
                        out.push(fe);
                    }
                    out
                };
                if need_win > 0 {
                    let Ok(victims) = self.select_eviction_victims(pools, need_win, 0, Some(sid)) else {
                        return StitchApplyOutcome::PoolBusy;
                    };
                    for v in victims {
                        self.evict_start_inner(pools, v, true, None);
                    }
                }
                self.tick += 1;
                if let Some(st) = self.starts.get_mut(&sid) {
                    st.last_used_tick = self.tick;
                }
                for (k, fe) in src_entries.into_iter().enumerate() {
                    if !pools.full.has_gpu_storage()
                        && pools.full.has_sketches()
                        && pools.full.slot_sketch_valid_len(fe.slot()).unwrap_or(BLOCK as u8) < BLOCK as u8
                    {
                        pools.full.on_slot_restored_from_spill(fe.slot());
                    }
                    let bi = BlockIndex::new((lo_blk + k) as u32);
                    tbl.fill(&mut pools.full, bi, fe.slot(), fe.generation()) // MUTANT_ANCHOR_STITCH_ZC_FILL
                        .expect("bind zero-copy stitched full block");
                }
                zero_copy_blocks = n_stitch_blks;
            }
            StitchSource::Retained { sid, src_start } => {
                if pools.full.slab_count() == 0 || n_stitch_blks > usable_full {
                    return StitchApplyOutcome::SourceGone;
                }
                let src_entries: Vec<BlockEntry> = {
                    let Some(st) = self.starts.get(&sid) else {
                        return StitchApplyOutcome::SourceGone;
                    };
                    let src_end = src_start + n_stitch_blks * BLOCK;
                    let full_cnt = st.pos / BLOCK;
                    if st.namespace != state.namespace
                        || src_end > st.toks.len()
                        || st.entries.len() < full_cnt
                        || st.toks[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
                    {
                        return StitchApplyOutcome::SourceGone;
                    }
                    let lo_sb = src_start / BLOCK;
                    let hi_sb = (src_end - 1) / BLOCK;
                    let mut out = Vec::with_capacity(hi_sb - lo_sb + 1);
                    for sb in lo_sb..=hi_sb {
                        let (kind, bi, fe) = st.entries[sb];
                        if kind != BlockKind::Full
                            || bi.get() as usize != sb
                            || !entry_is_live_sealed(pools, BlockKind::Full, fe)
                        {
                            return StitchApplyOutcome::SourceGone;
                        }
                        out.push(fe);
                    }
                    out
                };
                let Ok(victims) = self.select_eviction_victims(pools, need_win, n_stitch_blks, Some(sid)) else {
                    return StitchApplyOutcome::PoolBusy;
                };
                for v in victims {
                    self.evict_start_inner(pools, v, true, None);
                }
                self.tick += 1;
                if let Some(st) = self.starts.get_mut(&sid) {
                    st.last_used_tick = self.tick;
                }
                let kvb = pools.full.kvb();
                let stride = pools.full.stride_bytes() as usize;
                let rem = src_start % BLOCK;
                let first_part = BLOCK - rem;
                let mut assembled = vec![0u8; stride];
                for k in 0..n_stitch_blks {
                    {
                        let s0 = pools.full.slot_bytes(src_entries[k].slot()).expect("src slot 0 bytes");
                        copy_full_slot_rows(s0, rem, &mut assembled, 0, first_part, kvb);
                        let s1 = pools.full.slot_bytes(src_entries[k + 1].slot()).expect("src slot 1 bytes");
                        copy_full_slot_rows(s1, 0, &mut assembled, first_part, rem, kvb);
                    }
                    let slot = pools.full.lowest_free().expect("verified free full slot for unaligned stitch");
                    let _ = pools.full.take_unzeroed(slot).expect("take unzeroed full slot for stitch");
                    let gen = pools.full.record(slot).unwrap().generation();
                    self.stats.slots_taken += 1;
                    if gen > 1 {
                        self.stats.slots_reused += 1;
                    }
                    pools.full.slot_bytes_mut(slot).expect("dst stitch slot bytes").copy_from_slice(&assembled);
                    pools.full.clear_gpu_zero_pending(slot);
                    {
                        let rec = pools.full.record_mut(slot).unwrap();
                        rec.set_length(BLOCK as u32).expect("set stitched full length");
                        rec.seal();
                    }
                    pools.full.on_slot_restored_from_spill(slot);
                    let bi = BlockIndex::new((lo_blk + k) as u32);
                    tbl.fill(&mut pools.full, bi, slot, gen).expect("bind unaligned stitched full block");
                }
            }
            StitchSource::Ikv { cart_idx, src_start } => {
                if state.namespace != self.ikv_namespace || pools.full.slab_count() == 0 || n_stitch_blks > usable_full
                {
                    return StitchApplyOutcome::SourceGone;
                }
                let Some(cat) = self.ikv_catalog.clone() else {
                    return StitchApplyOutcome::SourceGone;
                };
                let Some(cart) = cat.get(cart_idx) else {
                    return StitchApplyOutcome::SourceGone;
                };
                let src_end = src_start + n_stitch_blks * BLOCK;
                if cart.is_quarantined()
                    || cart.header().kvb != pools.full.kvb()
                    || src_end > cart.n_tokens()
                    || cart.tokens()[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
                {
                    return StitchApplyOutcome::SourceGone;
                }
                let Ok(victims) = self.select_eviction_victims(pools, need_win, n_stitch_blks, None) else {
                    return StitchApplyOutcome::PoolBusy;
                };
                for v in victims {
                    self.evict_start_inner(pools, v, true, None);
                }
                let mut staged_slots: Vec<(Slot, u32)> = Vec::with_capacity(n_stitch_blks);
                for _ in 0..n_stitch_blks {
                    let Some(slot) = pools.full.lowest_free() else {
                        for (s, _) in staged_slots {
                            let _ = pools.full.record_mut(s).unwrap().drop_ref();
                        }
                        return StitchApplyOutcome::PoolBusy;
                    };
                    let _ = pools.full.take_unzeroed(slot).expect("take slot for ikv stitch");
                    let gen = pools.full.record(slot).unwrap().generation();
                    pools.full.record_mut(slot).unwrap().add_ref().expect("provisional ikv stitch ref");
                    self.stats.slots_taken += 1;
                    if gen > 1 {
                        self.stats.slots_reused += 1;
                    }
                    staged_slots.push((slot, gen));
                }
                let read_res = cart.read_full_span_into_blocks(
                    state.namespace,
                    self.ikv_namespace,
                    src_start,
                    n_stitch_blks,
                    |k, blk_bytes| {
                        let (slot, _) = staged_slots[k];
                        pools
                            .full
                            .slot_bytes_mut(slot)
                            .expect("staged ikv slot bytes")
                            .copy_from_slice(blk_bytes);
                        Ok(())
                    },
                );
                if read_res.is_err() {
                    for (s, _) in staged_slots {
                        let _ = pools.full.record_mut(s).unwrap().drop_ref();
                    }
                    self.stats.corrupt_fallbacks += 1;
                    self.sync_ikv_quarantined_stat();
                    return StitchApplyOutcome::SourceGone;
                }
                for (k, (slot, gen)) in staged_slots.into_iter().enumerate() {
                    pools.full.clear_gpu_zero_pending(slot);
                    {
                        let rec = pools.full.record_mut(slot).unwrap();
                        rec.set_length(BLOCK as u32).expect("set ikv stitched block length");
                        rec.seal();
                    }
                    pools.full.on_slot_restored_from_spill(slot);
                    let bi = BlockIndex::new((lo_blk + k) as u32);
                    tbl.fill(&mut pools.full, bi, slot, gen).expect("bind ikv stitched full block");
                    pools.full.record_mut(slot).unwrap().drop_ref().expect("drop provisional ikv stitch ref");
                }
            }
        }

        let stitched_tokens = self.finish_binding_stitched_lane(pools, tbl, state, plan, missing_win_blks);
        StitchApplyOutcome::Applied { stitched_tokens, zero_copy_blocks }
    }

    /// Release a lane's block-table references and unpin its `EntryTree` path so private/unsealed
    /// blocks immediately return to `refs == 0` while retained start points stay live.
    pub fn release_lane(&mut self, pools: &mut BlockPools, tbl: &mut BlockTable, state: &mut LaneBlockState) {
        if let Some(lane_idx) = state.bound_lane.take() {
            self.cancel_ikv_stage(pools, lane_idx);
        }
        tbl.clear_entries(pools).expect("clear lane block table");
        let tip = state.sealed.last().copied();
        for id in state.sealed.drain(..) {
            self.tree.unpin(id);
        }
        if let Some(tip) = tip {
            self.tree.prune_unreferenced(tip);
        }
        state.namespace = 0;
        state.prompt_len = 0;
        state.written = 0;
        state.stitched_approx = false;
        self.stats.lanes_released += 1;
    }

    /// Evict every retained start point and cancel any in-flight restores so all pool
    /// references drain cleanly on shutdown.
    pub fn shutdown(&mut self, pools: &mut BlockPools) {
        self.cancel_all_restores(pools);
        while self.evict_one_lru_start_inner(pools, false, None) {}
    }
}

#[cfg(standalone_blocks)]
#[derive(Clone, Debug)]
pub struct OwnershipSnapshot {
    pub num_full: usize,
    pub num_win: usize,
    pub full_refs: Vec<u32>,
    pub win_refs: Vec<u32>,
    pub full_gen: Vec<u32>,
    pub win_gen: Vec<u32>,
    pub start_full_refs: Vec<u32>,
    pub start_win_refs: Vec<u32>,
    pub actual_start_full_refs: Vec<u32>,
    pub actual_start_win_refs: Vec<u32>,
    pub table_full_refs: Vec<u32>,
    pub table_win_refs: Vec<u32>,
    pub free_plus_evict_full: usize,
    pub free_plus_evict_win: usize,
    pub lane_full_blocks: Vec<Vec<u32>>,
    pub lane_win_blocks: Vec<Vec<u32>>,
    pub lane_win_count: Vec<usize>,
    pub all_lane_entries_live: bool,
    pub all_start_entries_live_sealed: bool,
    pub tree_start_holders_match: bool,
    pub tree_pins_match_lanes: bool,
    pub expired_win_present: bool,
    pub spill_owners_consistent: bool,
    pub spilled_tips_consistent: bool,
    pub retained_starts: usize,
    pub spilled_starts: usize,
    pub tree_nodes: usize,
    pub stitch_index_buckets: usize,
}

#[cfg(standalone_blocks)]
impl ServeBlockCache {
    /// Compute the exact ownership, generation, EntryTree, sliding-window, and SpillStore
    /// consistency snapshot across `pools`, `self`, and all active `lanes`.
    pub fn ownership_snapshot(
        &self,
        pools: &BlockPools,
        lanes: &[(&BlockTable, &LaneBlockState)],
    ) -> OwnershipSnapshot {
        let num_full = pools.full.len();
        let num_win = pools.window.len();
        let mut full_refs = Vec::with_capacity(num_full);
        let mut full_gen = Vec::with_capacity(num_full);
        for i in 0..num_full {
            let slot = Slot::new((i + 1) as u32).unwrap();
            let r = pools.full.record(slot).unwrap();
            full_refs.push(r.refs());
            full_gen.push(r.generation());
        }
        let mut win_refs = Vec::with_capacity(num_win);
        let mut win_gen = Vec::with_capacity(num_win);
        for i in 0..num_win {
            let slot = Slot::new((i + 1) as u32).unwrap();
            let r = pools.window.record(slot).unwrap();
            win_refs.push(r.refs());
            win_gen.push(r.generation());
        }

        let mut start_full_refs = vec![0u32; num_full];
        for (i, &c) in self.start_slot_refs[kind_idx(BlockKind::Full)].iter().enumerate() {
            if i < num_full {
                start_full_refs[i] = c;
            }
        }
        let mut start_win_refs = vec![0u32; num_win];
        for (i, &c) in self.start_slot_refs[kind_idx(BlockKind::Window)].iter().enumerate() {
            if i < num_win {
                start_win_refs[i] = c;
            }
        }

        let mut actual_start_full_refs = vec![0u32; num_full];
        let mut actual_start_win_refs = vec![0u32; num_win];
        let mut all_start_entries_live_sealed = true;
        for st in self.starts.values() {
            if st.reasons == 0 {
                all_start_entries_live_sealed = false;
            }
            for &(kind, _, e) in &st.entries {
                if !entry_is_live_sealed(pools, kind, e) {
                    all_start_entries_live_sealed = false;
                }
                let idx = e.slot().pool_index().get() as usize;
                match kind {
                    BlockKind::Full => actual_start_full_refs[idx] += 1,
                    BlockKind::Window => actual_start_win_refs[idx] += 1,
                }
            }
        }

        let mut table_full_refs = vec![0u32; num_full];
        let mut table_win_refs = vec![0u32; num_win];
        let mut lane_full_blocks = Vec::with_capacity(lanes.len());
        let mut lane_win_blocks = Vec::with_capacity(lanes.len());
        let mut lane_win_count = Vec::with_capacity(lanes.len());
        let mut all_lane_entries_live = true;
        let mut expired_win_present = false;
        let mut expected_pins: HashMap<SealedId, u32> = HashMap::new();

        for &(tbl, st) in lanes {
            let mut f_blks = Vec::new();
            let mut w_blks = Vec::new();
            let min_live_win_blk = if st.written > 0 { st.written.saturating_sub(EXT - 1) / BLOCK } else { 0 };
            for (bi, e) in tbl.entries() {
                let pool = pools.of(e.kind());
                match pool.record(e.slot()) {
                    Ok(rec) if rec.generation() == e.generation() && rec.refs() > 0 => {}
                    _ => all_lane_entries_live = false,
                }
                let idx = e.slot().pool_index().get() as usize;
                match e.kind() {
                    BlockKind::Full => {
                        table_full_refs[idx] += 1;
                        f_blks.push(bi.get());
                    }
                    BlockKind::Window => {
                        table_win_refs[idx] += 1;
                        w_blks.push(bi.get());
                        if st.written > 0 && (bi.get() as usize) < min_live_win_blk {
                            expired_win_present = true;
                        }
                    }
                }
            }
            lane_win_count.push(w_blks.len());
            lane_full_blocks.push(f_blks);
            lane_win_blocks.push(w_blks);
            for &sid in &st.sealed {
                *expected_pins.entry(sid).or_insert(0) += 1;
            }
        }

        let mut tree_start_holders_match = true;
        let mut tree_pins_match_lanes = true;
        let tree_entries = self.tree.entries();
        let tree_ids: HashSet<SealedId> = tree_entries.iter().map(|&(id, _)| id).collect();
        for &sid in self.starts.keys() {
            if !tree_ids.contains(&sid) || self.tree.start_holders(sid) == 0 {
                tree_start_holders_match = false;
            }
        }
        for (&sid, &want) in &expected_pins {
            if !tree_ids.contains(&sid) || self.tree.pin_count(sid) != want {
                tree_pins_match_lanes = false;
            }
        }
        for (sid, _) in tree_entries {
            let want_start = u32::from(self.starts.contains_key(&sid));
            if self.tree.start_holders(sid) != want_start {
                tree_start_holders_match = false;
            }
            let want_pin = expected_pins.get(&sid).copied().unwrap_or(0);
            if self.tree.pin_count(sid) != want_pin {
                tree_pins_match_lanes = false;
            }
        }

        let mut expected_owners: HashMap<SpillKey, Vec<u64>> = HashMap::new();
        let mut spilled_tips_consistent = self.spilled_tips.len() == self.spilled_starts.len();
        for (&spill_id, sp) in &self.spilled_starts {
            if sp.reasons == 0 {
                spilled_tips_consistent = false;
            }
            match self.spilled_tips.get(&spill_id) {
                Some(&tip) => {
                    if self.spilled_tree.start_holders(tip) == 0 || self.spilled_tree.handle(tip) != Some(spill_id) {
                        spilled_tips_consistent = false;
                    }
                }
                None => spilled_tips_consistent = false,
            }
            for sk in std::iter::once(sp.cs_key).chain(sp.entries.iter().map(|&(_, _, k)| k)) {
                expected_owners.entry(sk).or_default().push(spill_id);
            }
        }
        let mut spill_owners_consistent = expected_owners.len() == self.spill_key_owners.len();
        if spill_owners_consistent {
            for (sk, mut want) in expected_owners {
                want.sort_unstable();
                match self.spill_key_owners.get(&sk) {
                    Some(got_raw) => {
                        let mut got = got_raw.clone();
                        got.sort_unstable();
                        if got != want {
                            spill_owners_consistent = false;
                            break;
                        }
                        if let Some(store) = &self.spill_store {
                            if !store.contains(sk) {
                                spill_owners_consistent = false;
                                break;
                            }
                        }
                    }
                    None => {
                        spill_owners_consistent = false;
                        break;
                    }
                }
            }
        }

        OwnershipSnapshot {
            num_full,
            num_win,
            full_refs,
            win_refs,
            full_gen,
            win_gen,
            start_full_refs,
            start_win_refs,
            actual_start_full_refs,
            actual_start_win_refs,
            table_full_refs,
            table_win_refs,
            free_plus_evict_full: self.free_plus_evictable_slots(pools, BlockKind::Full),
            free_plus_evict_win: self.free_plus_evictable_slots(pools, BlockKind::Window),
            lane_full_blocks,
            lane_win_blocks,
            lane_win_count,
            all_lane_entries_live,
            all_start_entries_live_sealed,
            tree_start_holders_match,
            tree_pins_match_lanes,
            expired_win_present,
            spill_owners_consistent,
            spilled_tips_consistent,
            retained_starts: self.starts.len(),
            spilled_starts: self.spilled_starts.len(),
            tree_nodes: self.tree.entries().len(),
            stitch_index_buckets: self.stitch_index.len(),
        }
    }

    /// Deepest live checkpoint across BOTH resident RAM starts and valid uncorrupted SSD spilled starts
    /// strictly shorter than `toks` in `namespace` (ground-truth oracle for `ServeOwnershipTrace`).
    pub fn expected_deepest_live_at(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> usize {
        if toks.len() <= 1 {
            return 0;
        }
        let prefix = &toks[..toks.len() - 1];
        let mut best = 0usize;
        for st in self.starts.values() {
            if st.namespace == namespace
                && st.pos <= prefix.len()
                && !st.toks.is_empty()
                && prefix.starts_with(&st.toks)
                && st.entries.iter().all(|&(k, _, e)| entry_is_live_sealed(pools, k, e))
            {
                best = best.max(st.pos);
            }
        }
        // Also scan EntryTree nodes directly in case spill_store is None (st.toks empty).
        let ram = self.peek_match_len_in_namespace(pools, namespace, toks);
        best = best.max(ram);
        for (&sid, st) in &self.starts {
            if st.namespace == namespace && st.pos > best && st.pos <= prefix.len() {
                // Verify exact prefix via tree handle chain if st.toks was not populated.
                let _ = sid;
            }
        }
        if self.spill_store.is_some() {
            let disk = self.spilled_tree.deepest_start_in_namespace(namespace, prefix).at;
            best = best.max(disk);
        }
        best
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod spill_model;

    fn fake_cs(tag: u8) -> Vec<u8> {
        vec![tag; 16]
    }

    #[test]
    fn window_pruning_visits_each_expired_block_once() {
        // A cold prefill or a single span that advances a restored checkpoint.
        assert_eq!(newly_expired_window_blocks(0, 2048), 0..16);
        assert_eq!(newly_expired_window_blocks(2048, 4096), 16..48);
        // At 128K context, 64 consecutive decode steps expire exactly one block.
        let pos = 131072;
        let first_live = (pos - EXT) / BLOCK;
        let visited: Vec<_> = (pos..pos + BLOCK).flat_map(|p| newly_expired_window_blocks(p, p + 1)).collect();
        assert_eq!(visited, vec![first_live]);
        assert_eq!(newly_expired_window_blocks(pos, pos + BLOCK - 2), first_live..first_live);
        assert_eq!(newly_expired_window_blocks(pos + BLOCK - 2, pos + BLOCK - 1), first_live..first_live + 1);
    }

    #[test]
    fn effective_pf_target_stops_at_every_and_prompt_boundaries() {
        // Short prompt (< 64): single step straight to pf_end.
        assert_eq!(effective_pf_target(0, 18), 18);
        assert_eq!(effective_pf_target(0, 64), 64);

        // OpenCode-sized prompt (8266): 2048, 4096, 6144, 8192, 8256, 8266.
        let mut p = 0;
        let mut stops = Vec::new();
        while p < 8266 {
            let next = effective_pf_target(p, 8266);
            assert!(next > p && next <= 8266);
            stops.push(next);
            p = next;
        }
        assert_eq!(stops, vec![2048, 4096, 6144, 8192, 8256, 8266]);

        // Exact 64-token multiple (8256): stops at 8192 (prompt_ckpt) then finishes at 8256.
        assert_eq!(effective_pf_target(6144, 8256), 8192);
        assert_eq!(effective_pf_target(8192, 8256), 8256);

        // Above 16384: widens to 4096-token chunks.
        assert_eq!(effective_pf_target(16384, 25000), 20480);
        assert_eq!(effective_pf_target(20480, 25000), 24576);
        assert_eq!(effective_pf_target(24576, 25000), 24960);
        assert_eq!(effective_pf_target(24960, 25000), 25000);
    }

    #[test]
    fn multiturn_reuse_and_cross_card_sharing_with_zero_leaks() {
        // Host pools: 512 full slots, 256 window slots.
        let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut tbl = BlockTable::new(512).unwrap();
        let mut st = LaneBlockState::default();

        // Turn 1: 8,266 tokens (> EXT = 1024).
        let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn1).is_none());
        let mut p = 0;
        while p < turn1.len() {
            let next = effective_pf_target(p, turn1.len());
            cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn1, p, next - p, || {
                fake_cs((next / BLOCK) as u8)
            });
            p = next;
        }
        // Decode 100 tokens past prompt end (must NOT invalidate retained start points!).
        for d in 0..100 {
            let pos = turn1.len() + d;
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        // Should have retained EVERY starts at 2048, 4096, 6144, 8192 + PROMPT start at 8256 = 5 starts.
        assert_eq!(cache.retained_start_count(), 5);

        // Turn 2: extends Turn 1 by 140 tokens (8,406 total) -> must hit 8,256!
        let mut turn2 = turn1.clone();
        turn2.extend((0..140u32).map(|i| 60000 + i));
        let (matched, cs) = cache
            .match_and_bind(&mut pools, &mut tbl, &mut st, &turn2)
            .expect("Turn 2 must match Turn 1 prompt checkpoint");
        assert_eq!(matched, 8256);
        assert_eq!(cs, fake_cs((8256 / BLOCK) as u8));
        // The first window block restored with this checkpoint stays live up to the boundary.
        let oldest = BlockIndex::new(((matched - EXT) / BLOCK) as u32);
        let near_boundary = matched + BLOCK - 2;
        for (start, end) in [(matched, near_boundary), (near_boundary, near_boundary + 1)] {
            cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn2, start, end - start, || fake_cs(0));
            assert_eq!(tbl.get(BlockKind::Window, oldest).unwrap().is_some(), end == near_boundary);
            assert!(tbl.get(BlockKind::Full, oldest).unwrap().is_some());
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // Card 2: shares first 6,500 tokens (system+tools), diverges after -> must hit 6,144!
        let mut card2 = turn1[..6500].to_vec();
        card2.extend((0..1000u32).map(|i| 70000 + i));
        let (matched_c2, cs_c2) = cache
            .match_and_bind(&mut pools, &mut tbl, &mut st, &card2)
            .expect("Card 2 must match shared EVERY checkpoint");
        assert_eq!(matched_c2, 6144);
        assert_eq!(cs_c2, fake_cs((6144 / BLOCK) as u8));
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // Shutdown drains every ref back to 0.
        cache.shutdown(&mut pools);
        assert_eq!(cache.retained_start_count(), 0);
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 512);
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 256);
        for kind in KINDS {
            let pool = pools.of(kind);
            for i in 0..pool.len() {
                let s = Slot::new((i + 1) as u32).unwrap();
                assert_eq!(pool.record(s).unwrap().refs(), 0, "leaked ref in {kind:?} slot {}", s.get());
            }
        }
    }

    #[test]
    fn lru_eviction_and_pool_pressure_guard_never_panic() {
        // Tight pool: 80 full slots (5120 tokens), 48 window slots.
        let mut pools = BlockPools::with_capacities(80, 48, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut tbl = BlockTable::new(128).unwrap();
        let mut st = LaneBlockState::default();

        // Fill cache with 4 distinct 1024-token prompts (64 full slots + 64 window slots total -> forces LRU eviction!).
        for req in 0..4u32 {
            let toks: Vec<u32> = (0..1030u32).map(|i| req * 10000 + i).collect();
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks);
            let mut p = 0;
            while p < toks.len() {
                let next = effective_pf_target(p, toks.len());
                cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
                cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &toks, p, next - p, || fake_cs(req as u8));
                p = next;
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        assert!(cache.stats().start_points_evicted > 0, "tight pool must trigger LRU eviction");
        // Most recent prompt (req=3) must still be cached at 1024!
        let req3_ext: Vec<u32> = (0..1050u32).map(|i| 3 * 10000 + i).collect();
        assert_eq!(cache.peek_match_len(&pools, &req3_ext), 1024);

        // Pool-pressure admit guard: always admits when active_lanes == 0, defers when active lane fills pool.
        let big: Vec<u32> = (0..4000u32).map(|i| 90000 + i).collect();
        assert!(cache.can_admit(&pools, &[], 0, &big, 1024, 2048));
        // Requesting more window blocks in a single span than exist in the pool returns PoolExhausted without panicking.
        assert_eq!(
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 3840),
            Err(CacheError::PoolExhausted(BlockKind::Window))
        );
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // Pin 60 full slots across chunked steps (so expired window blocks prune cleanly while full slots fill).
        let active_toks: Vec<u32> = (0..3840u32).map(|i| 50000 + i).collect();
        let mut ap = 0;
        while ap < active_toks.len() {
            let chunk_t = 1024.min(active_toks.len() - ap);
            cache.ensure_span_blocks(&mut pools, &mut tbl, ap, chunk_t).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &active_toks, ap, chunk_t, || fake_cs(9));
            ap += chunk_t;
        }
        assert!(
            !cache.can_admit(
                &pools,
                &[InflightLaneReserve {
                    lane: 0,
                    namespace: 0,
                    toks: &active_toks,
                    block_hashes: None,
                    n_past: ap,
                    pf_end: ap,
                    cached: 0,
                    written: ap,
                    gen: 0,
                    max_gen: 1,
                    runnable: true
                }],
                1,
                &big,
                1024,
                2048
            ),
            "should defer when active lane consumes pool"
        );
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
    }

    #[test]
    fn concurrent_same_prefix_dedups_and_refreshes_expired_window() {
        let mut pools = BlockPools::with_capacities(256, 128, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut tbl0 = BlockTable::new(256).unwrap();
        let mut tbl1 = BlockTable::new(256).unwrap();
        let mut st0 = LaneBlockState::default();
        let mut st1 = LaneBlockState::default();

        // Lane 0 prefills 2100 tokens -> saves EVERY start at 2048 (window blocks 16..32, NOT 0..16!).
        let prompt0: Vec<u32> = (0..2100u32).collect();
        let mut p = 0;
        while p < prompt0.len() {
            let next = effective_pf_target(p, prompt0.len());
            cache.ensure_span_blocks(&mut pools, &mut tbl0, p, next - p).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl0, &mut st0, &prompt0, p, next - p, || fake_cs(1));
            p = next;
        }
        cache.release_lane(&mut pools, &mut tbl0, &mut st0);

        // Lane 1 shares blocks 0..10 (640 tokens) with prompt0, then diverges before 2048.
        // Its block 0..10 Full slots dedup against prompt0's live Full slots while Window slots
        // were expired from prompt0 -> must NOT destroy prompt0's 2048 start point!
        let mut prompt1 = prompt0[..640].to_vec();
        prompt1.extend((0..200u32).map(|i| 80000 + i));
        assert!(cache.match_and_bind(&mut pools, &mut tbl1, &mut st1, &prompt1).is_none());
        let mut p1 = 0;
        while p1 < prompt1.len() {
            let next = effective_pf_target(p1, prompt1.len());
            cache.ensure_span_blocks(&mut pools, &mut tbl1, p1, next - p1).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl1, &mut st1, &prompt1, p1, next - p1, || fake_cs(2));
            p1 = next;
        }
        cache.release_lane(&mut pools, &mut tbl1, &mut st1);
        assert!(cache.stats().shared_dedups >= 10, "blocks 0..10 full slots should dedup");

        // Verify prompt0's 2048 start point is STILL intact and matchable!
        let mut prompt0_ext = prompt0.clone();
        prompt0_ext.push(99999);
        assert_eq!(cache.peek_match_len(&pools, &prompt0_ext), 2048);

        cache.shutdown(&mut pools);
    }

    fn assert_zero_pool_leaks(pools: &BlockPools) {
        for kind in KINDS {
            let pool = pools.of(kind);
            for i in 0..pool.len() {
                let s = Slot::new((i + 1) as u32).unwrap();
                assert_eq!(pool.record(s).unwrap().refs(), 0, "leaked ref in {kind:?} slot {}", s.get());
            }
        }
    }

    #[test]
    fn singleflight_22_lanes_rebind_and_prefill_only_distinct_tails() {
        use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

        // 512 Full slots (32,768 tokens) is far below the 22 * 138 = 3,036 slots needed without dedup.
        let mut pools = BlockPools::with_capacities(512, 512, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let prefix: Vec<u32> = (0..8500u32).map(|i| (i * 31 + 7) % 50000).collect();

        struct SimLane {
            toks: Vec<u32>,
            tbl: BlockTable,
            blocks: LaneBlockState,
            n_past: usize,
            cached: usize,
            prefilled: usize,
            cs: Vec<u8>,
            active: bool,
        }

        let nlanes = 22usize;
        let chunk = 4096usize;
        let mut lanes: Vec<SimLane> = (0..nlanes)
            .map(|i| {
                let mut toks = prefix.clone();
                toks.extend((0..300u32).map(|j| 60000 + (i as u32) * 1000 + j));
                SimLane {
                    toks,
                    tbl: BlockTable::new(512).unwrap(),
                    blocks: LaneBlockState::default(),
                    n_past: 0,
                    cached: 0,
                    prefilled: 0,
                    cs: Vec::new(),
                    active: false,
                }
            })
            .collect();

        // Admit all 22 simultaneous requests at t=0 via in-flight shared prefix accounting.
        let mut planner = ServeStepPlanner::new(nlanes, 16);
        for i in 0..nlanes {
            let reserves: Vec<InflightLaneReserve<'_>> = lanes
                .iter()
                .enumerate()
                .filter(|(_, l)| l.active)
                .map(|(idx, l)| InflightLaneReserve {
                    lane: idx,
                    namespace: 0,
                    toks: &l.toks,
                    block_hashes: None,
                    n_past: l.n_past,
                    pf_end: l.toks.len(),
                    cached: l.cached,
                    written: l.blocks.written,
                    gen: 0,
                    max_gen: 128,
                    runnable: true,
                })
                .collect();
            assert!(
                cache.can_admit(&pools, &reserves, i, &lanes[i].toks, 128, chunk),
                "lane {i} should admit under singleflight shared prefix accounting"
            );
            let l = &mut lanes[i];
            assert!(cache.match_and_bind(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks).is_none());
            l.active = true;
            planner.on_admit(i);
        }

        let mut checkpoints_sealed = false;
        let mut leader_only_steps = 0usize;
        loop {
            if checkpoints_sealed {
                checkpoints_sealed = false;
                for l in &mut lanes {
                    if l.active && l.n_past == l.cached && l.blocks.written == l.n_past {
                        if let Some((matched_at, cs)) =
                            cache.rebind_if_deeper_match(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks, l.n_past)
                        {
                            l.cs = cs;
                            l.n_past = matched_at;
                            l.cached = matched_at;
                        }
                    }
                }
            }
            let cands: Vec<InflightPrefillLane<'_>> = lanes
                .iter()
                .enumerate()
                .filter(|(_, l)| l.active && l.n_past < l.toks.len())
                .map(|(i, l)| InflightPrefillLane {
                    lane: i,
                    namespace: 0,
                    toks: &l.toks,
                    block_hashes: None,
                    n_past: l.n_past,
                    pf_end: l.toks.len(),
                    runnable: true,
                    eligible_follower: l.n_past == l.cached && l.blocks.written == l.n_past,
                })
                .collect();
            if cands.is_empty() {
                break;
            }
            let mut deferred = vec![false; nlanes];
            for (idx, c) in cands.iter().enumerate() {
                if find_prefill_leader(&cands, idx).is_some() {
                    deferred[c.lane] = true;
                }
            }
            let inputs: Vec<ServeLaneInput> = lanes
                .iter()
                .enumerate()
                .map(|(i, l)| ServeLaneInput {
                    runnable: l.active && l.n_past < l.toks.len() && !deferred[i],
                    n_past: l.n_past,
                    pf_end: effective_pf_target(l.n_past, l.toks.len()),
                    has_pending_decode: false,
                })
                .collect();
            let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, chunk, BLOCK) else {
                panic!("expected prefill plan while lanes remain unfinished");
            };
            if lanes[0].n_past < 8192 {
                // Only lane 0 runs for [0..2048..4096..6144..8192), and followers accrue 0 wait_ticks.
                assert_eq!(spans.len(), 1);
                assert_eq!(spans[0].0, 0);
                for f in 1..nlanes {
                    assert_eq!(planner.wait_ticks(f), 0);
                }
                leader_only_steps += 1;
            }
            let before_starts = cache.stats().start_points_saved;
            for (i, p0, t) in spans {
                let l = &mut lanes[i];
                cache.ensure_span_blocks(&mut pools, &mut l.tbl, p0, t).unwrap();
                cache.finish_prefill_span(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks, p0, t, || {
                    fake_cs(((p0 + t) / BLOCK) as u8)
                });
                l.n_past = p0 + t;
                l.prefilled += t;
            }
            if cache.stats().start_points_saved > before_starts {
                checkpoints_sealed = true;
            }
            assert!(planner.complete_step().is_empty());
        }

        assert_eq!(leader_only_steps, 4, "lane 0 should run 4 leader chunks at 2048/4096/6144/8192");
        assert_eq!(lanes[0].cached, 0);
        assert_eq!(lanes[0].prefilled, 8800);
        for (i, lane) in lanes.iter().enumerate().take(nlanes).skip(1) {
            assert_eq!(lane.cached, 8192, "follower {i} should cache up to 8192");
            assert_eq!(lane.prefilled, 608, "follower {i} should prefill only [8192..8800)");
            assert_eq!(lane.cs, fake_cs((8192 / BLOCK) as u8));
        }
        assert!(cache.stats().singleflight_rebinds >= 21);
        assert_eq!(cache.stats().singleflight_saved_tokens, 21 * 8192);

        for l in &mut lanes {
            cache.release_lane(&mut pools, &mut l.tbl, &mut l.blocks);
        }
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 512);
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 512);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn singleflight_leader_cancellation_promotes_next_follower_without_leaks() {
        use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

        let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let prefix: Vec<u32> = (0..8500u32).map(|i| (i * 19 + 5) % 50000).collect();

        let nlanes = 4usize;
        let mut toks_list = Vec::with_capacity(nlanes);
        let mut tbls = Vec::with_capacity(nlanes);
        let mut blocks = Vec::with_capacity(nlanes);
        let mut n_past = vec![0usize; nlanes];
        let mut cached = vec![0usize; nlanes];
        let mut active = vec![true; nlanes];
        let mut planner = ServeStepPlanner::new(nlanes, 16);

        for i in 0..nlanes {
            let mut toks = prefix.clone();
            toks.extend((0..300u32).map(|j| 70000 + (i as u32) * 1000 + j));
            let mut tbl = BlockTable::new(512).unwrap();
            let mut st = LaneBlockState::default();
            assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks).is_none());
            toks_list.push(toks);
            tbls.push(tbl);
            blocks.push(st);
            planner.on_admit(i);
        }

        // Step 1: lane 0 leads [0..2048) and seals checkpoint 2048.
        let inputs: Vec<ServeLaneInput> = (0..nlanes)
            .map(|i| ServeLaneInput {
                runnable: i == 0,
                n_past: 0,
                pf_end: effective_pf_target(0, toks_list[i].len()),
                has_pending_decode: false,
            })
            .collect();
        let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, 4096, BLOCK) else {
            panic!("expected step 1 prefill");
        };
        assert_eq!(spans, vec![(0, 0, 2048)]);
        cache.ensure_span_blocks(&mut pools, &mut tbls[0], 0, 2048).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbls[0], &mut blocks[0], &toks_list[0], 0, 2048, || fake_cs(32));
        n_past[0] = 2048;
        assert!(planner.complete_step().is_empty());

        // Rebind followers 1..4 to 2048, then cancel lane 0 mid-prefill!
        for i in 1..nlanes {
            let (m, _) = cache
                .rebind_if_deeper_match(&mut pools, &mut tbls[i], &mut blocks[i], &toks_list[i], n_past[i])
                .expect("follower must rebind to 2048");
            assert_eq!(m, 2048);
            n_past[i] = m;
            cached[i] = m;
        }
        assert!(planner.request_cancel(0));
        cache.release_lane(&mut pools, &mut tbls[0], &mut blocks[0]);
        active[0] = false;

        // Next step: lane 1 must immediately promote to leader; lanes 2 and 3 must follow lane 1.
        let mut checkpoints_sealed = false;
        loop {
            if checkpoints_sealed {
                checkpoints_sealed = false;
                for i in 0..nlanes {
                    if active[i] && n_past[i] == cached[i] && blocks[i].written == n_past[i] {
                        if let Some((m, _)) = cache.rebind_if_deeper_match(
                            &mut pools,
                            &mut tbls[i],
                            &mut blocks[i],
                            &toks_list[i],
                            n_past[i],
                        ) {
                            n_past[i] = m;
                            cached[i] = m;
                        }
                    }
                }
            }
            let cands: Vec<InflightPrefillLane<'_>> = (0..nlanes)
                .filter(|&i| active[i] && n_past[i] < toks_list[i].len())
                .map(|i| InflightPrefillLane {
                    lane: i,
                    namespace: 0,
                    toks: &toks_list[i],
                    block_hashes: None,
                    n_past: n_past[i],
                    pf_end: toks_list[i].len(),
                    runnable: true,
                    eligible_follower: n_past[i] == cached[i] && blocks[i].written == n_past[i],
                })
                .collect();
            if cands.is_empty() {
                break;
            }
            let mut deferred = vec![false; nlanes];
            for (idx, c) in cands.iter().enumerate() {
                let leader = find_prefill_leader(&cands, idx);
                if c.lane == 1 {
                    assert_eq!(leader, None, "lane 1 must immediately become leader after lane 0 cancels");
                } else if n_past[c.lane] < 8192 {
                    assert_eq!(leader, Some(1), "lanes 2 and 3 must follow promoted lane 1");
                }
                if leader.is_some() {
                    deferred[c.lane] = true;
                }
            }
            let inputs: Vec<ServeLaneInput> = (0..nlanes)
                .map(|i| ServeLaneInput {
                    runnable: active[i] && n_past[i] < toks_list[i].len() && !deferred[i],
                    n_past: n_past[i],
                    pf_end: effective_pf_target(n_past[i], toks_list[i].len()),
                    has_pending_decode: false,
                })
                .collect();
            let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, 4096, BLOCK) else {
                panic!("expected prefill after leader promotion");
            };
            let before_starts = cache.stats().start_points_saved;
            for (i, p0, t) in spans {
                cache.ensure_span_blocks(&mut pools, &mut tbls[i], p0, t).unwrap();
                cache
                    .finish_prefill_span(&mut pools, &mut tbls[i], &mut blocks[i], &toks_list[i], p0, t, || fake_cs(1));
                n_past[i] = p0 + t;
            }
            if cache.stats().start_points_saved > before_starts {
                checkpoints_sealed = true;
            }
            assert!(planner.complete_step().is_empty());
        }

        assert_eq!(cached[1], 2048);
        assert_eq!(cached[2], 8192);
        assert_eq!(cached[3], 8192);

        for i in 1..nlanes {
            cache.release_lane(&mut pools, &mut tbls[i], &mut blocks[i]);
        }
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn singleflight_short_or_diverged_prompt_never_waits() {
        let leader_toks: Vec<u32> = (0..8500u32).map(|i| i + 1).collect();
        let short_toks: Vec<u32> = leader_toks[..1500].to_vec();
        let mut diverged_toks = leader_toks.clone();
        diverged_toks[100] ^= 0xffff;

        let cands = vec![
            InflightPrefillLane {
                lane: 0,
                namespace: 0,
                toks: &leader_toks,
                block_hashes: None,
                n_past: 0,
                pf_end: leader_toks.len(),
                runnable: true,
                eligible_follower: true,
            },
            InflightPrefillLane {
                lane: 1,
                namespace: 0,
                toks: &short_toks,
                block_hashes: None,
                n_past: 0,
                pf_end: short_toks.len(),
                runnable: true,
                eligible_follower: true,
            },
            InflightPrefillLane {
                lane: 2,
                namespace: 0,
                toks: &diverged_toks,
                block_hashes: None,
                n_past: 0,
                pf_end: diverged_toks.len(),
                runnable: true,
                eligible_follower: true,
            },
        ];

        assert_eq!(find_prefill_leader(&cands, 0), None);
        assert_eq!(find_prefill_leader(&cands, 1), None, "prompt < EARLY_EVERY_TOKENS must never wait");
        assert_eq!(find_prefill_leader(&cands, 2), None, "diverged prefix must never wait");

        assert_eq!(inflight_shared_checkpoint(&cands[1], &cands[..1]), 0);
        assert_eq!(inflight_shared_checkpoint(&cands[2], &cands[..1]), 0);
        let mut matching = leader_toks.clone();
        matching.extend(90000..90300);
        let longer = InflightPrefillLane { lane: 1, toks: &matching, pf_end: matching.len(), ..cands[0] };
        assert_eq!(
            inflight_shared_checkpoint(&longer, &cands[..1]),
            8192,
            "only the common periodic boundary is promised"
        );
        let equal = InflightPrefillLane { lane: 1, ..cands[0] };
        assert_eq!(inflight_shared_checkpoint(&equal, &cands[..1]), 8448);
    }

    #[test]
    fn simultaneous_burst_admission_guard_prevents_midflight_exhaustion() {
        // 130 Full slots = 8,320 tokens. Each request needs (2000 + 512).div_ceil(64) = 40 Full slots
        // Six independent requests arriving simultaneously would demand 240 Full
        // slots (> 130) if admitted together; reserved_inflight_full_slots must admit 3 and defer 3!
        let mut pools = BlockPools::with_capacities(130, 128, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        let chunk = 2048usize;
        let max_gen = 512usize;

        struct BurstLane {
            toks: Vec<u32>,
            tbl: BlockTable,
            blocks: LaneBlockState,
            n_past: usize,
            gen: usize,
            active: bool,
        }

        let mut requests: Vec<Vec<u32>> =
            (0..6u32).map(|r| (0..2000u32).map(|i| (r + 1) * 100_000 + i).collect()).collect();
        let mut lanes: Vec<BurstLane> = Vec::new();
        let mut queue: std::collections::VecDeque<Vec<u32>> = requests.drain(..).collect();

        // Wave 1: 6 requests arrive simultaneously at t=0.
        let mut admitted_wave1 = 0usize;
        while let Some(toks) = queue.front() {
            let reserves: Vec<InflightLaneReserve<'_>> = lanes
                .iter()
                .enumerate()
                .filter(|(_, l)| l.active)
                .map(|(idx, l)| InflightLaneReserve {
                    lane: idx,
                    namespace: 0,
                    toks: &l.toks,
                    block_hashes: None,
                    n_past: l.n_past,
                    pf_end: l.toks.len(),
                    cached: 0,
                    written: l.blocks.written,
                    gen: l.gen,
                    max_gen,
                    runnable: true,
                })
                .collect();
            if !cache.can_admit(&pools, &reserves, lanes.len(), toks, max_gen, chunk) {
                break;
            }
            let toks = queue.pop_front().unwrap();
            let mut tbl = BlockTable::new(128).unwrap();
            let mut blocks = LaneBlockState::default();
            assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut blocks, &toks).is_none());
            lanes.push(BurstLane { toks, tbl, blocks, n_past: 0, gen: 0, active: true });
            admitted_wave1 += 1;
        }
        assert_eq!(admitted_wave1, 3, "must admit only the 3 requests that fit inside 130 Full slots");
        assert_eq!(queue.len(), 3, "remaining 3 requests must stay queued, not admit and 500 later");
        assert_eq!(cache.stats().admit_deferred_pool_pressure, 1);

        // Run all admitted requests (prefill + full 512 decode tokens) and admit queued ones as slots free:
        // ZERO PoolExhausted errors across all 6 requests!
        loop {
            let mut progressed = false;
            for l in &mut lanes {
                if !l.active {
                    continue;
                }
                progressed = true;
                if l.n_past < l.toks.len() {
                    let next = effective_pf_target(l.n_past, l.toks.len());
                    cache
                        .ensure_span_blocks(&mut pools, &mut l.tbl, l.n_past, next - l.n_past)
                        .expect("admitted lane must never hit PoolExhausted during prefill");
                    cache.finish_prefill_span(
                        &mut pools,
                        &mut l.tbl,
                        &mut l.blocks,
                        &l.toks,
                        l.n_past,
                        next - l.n_past,
                        || fake_cs(1),
                    );
                    l.n_past = next;
                } else if l.gen < max_gen {
                    cache
                        .ensure_span_blocks(&mut pools, &mut l.tbl, l.n_past, 1)
                        .expect("admitted lane must never hit PoolExhausted during decode");
                    cache.finish_decode_span(&mut pools, &mut l.tbl, &mut l.blocks, l.n_past);
                    l.n_past += 1;
                    l.gen += 1;
                } else {
                    cache.release_lane(&mut pools, &mut l.tbl, &mut l.blocks);
                    l.active = false;
                }
            }
            while let Some(toks) = queue.front() {
                let reserves: Vec<InflightLaneReserve<'_>> = lanes
                    .iter()
                    .enumerate()
                    .filter(|(_, l)| l.active)
                    .map(|(idx, l)| InflightLaneReserve {
                        lane: idx,
                        namespace: 0,
                        toks: &l.toks,
                        block_hashes: None,
                        n_past: l.n_past,
                        pf_end: l.toks.len(),
                        cached: 0,
                        written: l.blocks.written,
                        gen: l.gen,
                        max_gen,
                        runnable: true,
                    })
                    .collect();
                if !cache.can_admit(&pools, &reserves, lanes.len(), toks, max_gen, chunk) {
                    break;
                }
                let toks = queue.pop_front().unwrap();
                let mut tbl = BlockTable::new(128).unwrap();
                let mut blocks = LaneBlockState::default();
                let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut blocks, &toks);
                lanes.push(BurstLane { toks, tbl, blocks, n_past: 0, gen: 0, active: true });
            }
            if !progressed && queue.is_empty() {
                break;
            }
        }
        assert_eq!(lanes.len(), 6);
        assert!(lanes.iter().all(|l| !l.active && l.gen == max_gen));
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn transactional_ensure_span_blocks_and_zero_500_deferral_drain() {
        use crate::scheduler::{LaneState, ServeLaneInput, ServeStepPlan, ServeStepPlanner};

        // 1. Transactional rollback on ensure_span_blocks: 3 Full slots available, request needs 4 blocks.
        let mut pools = BlockPools::with_capacities(3, 8, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut tbl = BlockTable::new(16).unwrap();
        assert_eq!(
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 256),
            Err(CacheError::PoolExhausted(BlockKind::Full))
        );
        for b in 0..4u32 {
            let bi = BlockIndex::new(b);
            assert_eq!(tbl.get(BlockKind::Full, bi).unwrap(), None, "block {b} Full must be rolled back");
            assert_eq!(tbl.get(BlockKind::Window, bi).unwrap(), None, "block {b} Window must be rolled back");
        }
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 3);
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 8);
        assert_zero_pool_leaks(&pools);

        // 2. End-to-end zero-500 deferral: lane 0 is decoding (holding 6 Full slots, 2 more to finish),
        // lane 1 is prefilling (needs 8 Full slots, only 4 free). Total pool = 10 Full slots.
        // Even when planner preempts to Prefill for lane 1 and lane 1 hits PoolExhausted,
        // lane 1 defers (0 HTTP 500s, 0 leaked slots), lane 0 finishes & frees its 6 slots,
        // and lane 1 completes cleanly!
        let mut pools = BlockPools::with_capacities(10, 16, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut planner = ServeStepPlanner::new(2, 2);

        let toks0: Vec<u32> = (0..384u32).collect(); // 6 Full blocks
        let toks1: Vec<u32> = (1000..1512u32).collect(); // 8 Full blocks
        let mut tbls = [BlockTable::new(32).unwrap(), BlockTable::new(32).unwrap()];
        let mut blocks = [LaneBlockState::default(), LaneBlockState::default()];
        let _ = cache.match_and_bind(&mut pools, &mut tbls[0], &mut blocks[0], &toks0);
        cache.ensure_span_blocks(&mut pools, &mut tbls[0], 0, 384).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbls[0], &mut blocks[0], &toks0, 0, 384, || fake_cs(1));
        let _ = cache.match_and_bind(&mut pools, &mut tbls[1], &mut blocks[1], &toks1);

        planner.on_admit(0);
        planner.on_admit(1);

        let mut n_past = [384usize, 0usize];
        let pf_end = [384usize, 512usize];
        let mut gen = [0usize, 0usize];
        let max_gen = [4usize, 1usize];
        let mut active = [true, true];
        let mut pool_deferred = [false, false];
        let mut prev_released = cache.stats().lanes_released;

        for _step in 0..32 {
            if cache.stats().lanes_released != prev_released {
                pool_deferred.fill(false);
                prev_released = cache.stats().lanes_released;
            }
            if !active[0] && !active[1] {
                break;
            }
            let inputs: Vec<ServeLaneInput> = (0..2)
                .map(|i| ServeLaneInput {
                    runnable: active[i] && !pool_deferred[i],
                    n_past: n_past[i],
                    pf_end: if n_past[i] < pf_end[i] { effective_pf_target(n_past[i], pf_end[i]) } else { pf_end[i] },
                    has_pending_decode: active[i] && n_past[i] >= pf_end[i],
                })
                .collect();
            let Some(plan) = planner.plan_and_begin_step(&inputs, 1024, BLOCK) else {
                panic!("deadlock: no runnable step while lanes remain active");
            };
            match plan {
                ServeStepPlan::Prefill(sp_list) => {
                    let mut live_sp = Vec::new();
                    for (i, p0, t) in sp_list {
                        match cache.ensure_span_blocks(&mut pools, &mut tbls[i], p0, t) {
                            Ok(()) => live_sp.push((i, p0, t)),
                            Err(CacheError::PoolExhausted(_)) => {
                                cache.record_step_deferred_pool_pressure();
                                pool_deferred[i] = true;
                            }
                        }
                    }
                    for (i, p0, t) in live_sp {
                        let toks = if i == 0 { &toks0 } else { &toks1 };
                        cache.finish_prefill_span(&mut pools, &mut tbls[i], &mut blocks[i], toks, p0, t, || fake_cs(2));
                        n_past[i] = p0 + t;
                    }
                }
                ServeStepPlan::Decode(need_dec) => {
                    for i in need_dec {
                        cache.ensure_span_blocks(&mut pools, &mut tbls[i], n_past[i], 1).unwrap();
                        cache.finish_decode_span(&mut pools, &mut tbls[i], &mut blocks[i], n_past[i]);
                        n_past[i] += 1;
                        gen[i] += 1;
                        if gen[i] >= max_gen[i] {
                            cache.release_lane(&mut pools, &mut tbls[i], &mut blocks[i]);
                            active[i] = false;
                            planner.on_finish(i);
                        }
                    }
                }
            }
            assert!(planner.complete_step().is_empty());
            for (i, &is_active) in active.iter().enumerate() {
                if is_active {
                    assert_eq!(planner.state(i), LaneState::Ready);
                }
            }
        }

        assert!(!active[0] && !active[1], "both lanes must complete without HTTP 500");
        assert!(cache.stats().step_deferred_pool_pressure >= 1);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    struct ScratchDir(std::path::PathBuf);
    impl ScratchDir {
        fn new(name: &str) -> Self {
            let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("target")
                .join("block-cache-spill-tests")
                .join(format!("{name}-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&p);
            std::fs::create_dir_all(&p).unwrap();
            Self(p)
        }
    }
    impl Drop for ScratchDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    // Populate a retained checkpoint at end, leaving its lane free.
    fn retain_test_prompt(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        tokens: &[u32],
        tag: u8,
    ) -> SealedId {
        let start = cache.match_and_bind(pools, tbl, state, tokens).map_or(0, |(p, _)| p);
        let end = tokens.len() - 1;
        cache.ensure_span_blocks(pools, tbl, start, end - start).unwrap();
        cache.finish_prefill_span(pools, tbl, state, tokens, start, end - start, || fake_cs(tag));
        let tip = *state.sealed.last().unwrap();
        cache.release_lane(pools, tbl, state);
        tip
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn long_spill_restore_keeps_source_and_accepts_early_fork() {
        let dir = ScratchDir::new("long-fork");
        let store = SpillStore::open(&dir.0, 100 * 1024 * 1024).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut pools = BlockPools::with_capacities(18, 18, 1).unwrap();
        let mut tbl = BlockTable::new(20).unwrap();
        let mut state = LaneBlockState::default();
        let end = WINDOW + BLOCK;
        let long: Vec<u32> = (0..=end as u32).collect();
        let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &long, 3);
        assert!(cache.evict_start(&mut pools, tip));
        // Two unrelated resident blocks leave only 16 free Full slots; the restore
        // needs 17. Writing these victims to the tight SSD must preserve the source.
        let unrelated: Vec<u32> = (0..=128).map(|i| 20_000 + i).collect();
        retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &unrelated, 4);
        assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &long), Some((end, fake_cs(3))));
        let root = state.sealed[0];
        let root_full = cache.tree.handle(root).unwrap().full();
        assert!(cache.tree.handle(root).unwrap().window().is_none());
        cache.release_lane(&mut pools, &mut tbl, &mut state);

        let mut fork = long[..BLOCK].to_vec();
        fork.push(99_000);
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &fork).is_none());
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, BLOCK).unwrap();
        let recomputed_window = tbl.get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut state, &fork, 0, BLOCK, || fake_cs(5));
        assert_eq!(state.sealed[0], root);
        assert_eq!(cache.tree.handle(root).unwrap(), BlockHandles::new(root_full, Some(recomputed_window)));
        assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(root_full));
        cache.ensure_span_blocks(&mut pools, &mut tbl, BLOCK, 1).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut state, &fork, BLOCK, 1, || fake_cs(6));
        cache.release_lane(&mut pools, &mut tbl, &mut state);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn spill_read_failure_releases_provisional_blocks_and_preserves_resident_match() {
        let dir = ScratchDir::new("stream-rollback");
        let store = SpillStore::open(&dir.0, 64 * 1024 * 1024).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
        let mut tbl = BlockTable::new(16).unwrap();
        let mut state = LaneBlockState::default();
        let long: Vec<u32> = (0..=6 * BLOCK as u32).collect();
        let short = &long[..BLOCK + 1];
        retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, short, 1);
        let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &long, 2);
        assert!(cache.evict_start(&mut pools, tip));

        let checkpoint = cache.spilled_starts.values().next().unwrap();
        let (_, _, last_file) = *checkpoint.entries.last().unwrap();
        std::fs::remove_file(cache.spill_store().unwrap().block_path(last_file)).unwrap();
        let before = cache.stats().slots_taken;
        assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &long), Some((BLOCK, fake_cs(1))));
        assert!(cache.stats().slots_taken > before, "earlier files used bounded provisional slots");
        assert_eq!(cache.stats().starts_restored, 0);
        assert_eq!(cache.retained_start_count(), 1);
        assert_eq!(cache.spilled_start_count(), 0);
        cache.release_lane(&mut pools, &mut tbl, &mut state);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn spill_store_eviction_restore_and_corrupt_fallback() {
        let dir = ScratchDir::new("e2e");
        let store = SpillStore::open_with_kvb(&dir.0, 256 * 1024 * 1024, 1).unwrap();
        // 24 Full slots, 16 Window slots at kvb=1 (1 MiB Full, 5 MiB Window).
        // Each 576-token prompt saves a PROMPT checkpoint at 512 (8 Full + 8 Window).
        // Three distinct prompts demand 24 Window slots (> 16), forcing LRU eviction + SSD spill of prompt 0!
        let mut pools = BlockPools::with_capacities(24, 16, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut tbl = BlockTable::new(32).unwrap();
        let mut st = LaneBlockState::default();

        let prompt0: Vec<u32> = (0..576u32).map(|i| 10_000 + i).collect();
        let prompt1: Vec<u32> = (0..576u32).map(|i| 20_000 + i).collect();
        let prompt2: Vec<u32> = (0..576u32).map(|i| 30_000 + i).collect();

        let run_prompt = |cache: &mut ServeBlockCache,
                          pools: &mut BlockPools,
                          tbl: &mut BlockTable,
                          st: &mut LaneBlockState,
                          toks: &[u32],
                          tag: u8| {
            assert!(cache.match_and_bind(pools, tbl, st, toks).is_none());
            let mut p = 0;
            while p < toks.len() {
                let next = effective_pf_target(p, toks.len());
                cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
                // Stamp recognizable sentinel pattern into each newly allocated slot before sealing.
                for b in (p / BLOCK)..=((next - 1) / BLOCK) {
                    let bi = BlockIndex::new(b as u32);
                    for kind in KINDS {
                        let e = tbl.get(kind, bi).unwrap().unwrap();
                        if !pools.of(kind).record(e.slot()).unwrap().sealed() {
                            let bytes = pools.of_mut(kind).slot_bytes_mut(e.slot()).unwrap();
                            bytes[0] = tag;
                            bytes[1] = b as u8;
                            bytes[bytes.len() - 1] = tag.wrapping_add(b as u8);
                        }
                    }
                }
                cache.finish_prefill_span(pools, tbl, st, toks, p, next - p, || fake_cs(tag));
                p = next;
            }
            cache.release_lane(pools, tbl, st);
        };

        run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt0, 0xA1);
        run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt1, 0xB2);
        run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt2, 0xC3);

        assert!(cache.stats().starts_spilled >= 1, "LRU eviction must spill prompt0 to SpillStore");
        assert!(cache.spilled_start_count() >= 1);
        assert!(cache.spill_store().unwrap().entry_count() > 0);
        // prompt0 is no longer in RAM: peek_match_len stays in-RAM only.
        let mut prompt0_ext = prompt0[..512].to_vec();
        prompt0_ext.extend(99_000..99_040);
        assert_eq!(cache.peek_match_len(&pools, &prompt0_ext), 0);

        // match_and_bind must restore prompt0 from SSD, verify SHA-256, and return exact cs + KV bytes!
        let (matched_at, cs) = cache
            .match_and_bind(&mut pools, &mut tbl, &mut st, &prompt0_ext)
            .expect("must restore spilled prompt0 checkpoint from SSD");
        assert_eq!(matched_at, 512);
        assert_eq!(cs, fake_cs(0xA1));
        assert_eq!(cache.stats().starts_restored, 1);
        for b in 0..8usize {
            let bi = BlockIndex::new(b as u32);
            for kind in KINDS {
                let e = tbl.get(kind, bi).unwrap().unwrap();
                let bytes = pools.of(kind).slot_bytes(e.slot()).unwrap();
                assert_eq!(bytes[0], 0xA1);
                assert_eq!(bytes[1], b as u8);
                assert_eq!(bytes[bytes.len() - 1], 0xA1u8.wrapping_add(b as u8));
            }
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // Corrupt-file fallback: evict prompt1 to SSD, corrupt one .blk file, verify clean cache miss!
        let prompt3: Vec<u32> = (0..576u32).map(|i| 40_000 + i).collect();
        run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt3, 0xD4);
        assert!(cache.spilled_start_count() >= 1);

        let mut corrupted_one = false;
        for entry in std::fs::read_dir(&dir.0).unwrap() {
            let path = entry.unwrap().path();
            if path.extension().and_then(|e| e.to_str()) == Some("blk") {
                let mut data = std::fs::read(&path).unwrap();
                let last = data.len() - 1;
                data[last] ^= 0xff;
                std::fs::write(&path, data).unwrap();
                corrupted_one = true;
                break;
            }
        }
        assert!(corrupted_one);

        let mut prompt1_ext = prompt1[..512].to_vec();
        prompt1_ext.extend(88_000..88_040);
        // Regardless of which spilled file was corrupted, trying prompt1_ext and prompt2_ext must
        // never panic, must fall back to None for the corrupted checkpoint, and must unlink the corrupt file!
        let m1 = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt1_ext);
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        let mut prompt2_ext = prompt2[..512].to_vec();
        prompt2_ext.extend(77_000..77_040);
        let m2 = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt2_ext);
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        assert!(m1.is_none() || m2.is_none(), "corrupted .blk must fall back to clean cache miss");
        assert!(cache.spill_store().unwrap().stats().corrupt_files_removed >= 1);

        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn maintain_spill_during_gpu_trims_excess_spilled_starts_without_touching_pools() {
        let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join(format!("block-cache-maint-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = SpillStore::open_with_kvb(&dir, 256 * 1024 * 1024, 1).unwrap();
        let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut tbl = BlockTable::new(16).unwrap();
        let mut st = LaneBlockState::default();

        for base in [1000u32, 2000u32, 3000u32] {
            let p: Vec<u32> = (0..576u32).map(|i| base + i).collect();
            assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p).is_none());
            let mut pos = 0;
            while pos < p.len() {
                let next = effective_pf_target(pos, p.len());
                cache.ensure_span_blocks(&mut pools, &mut tbl, pos, next - pos).unwrap();
                cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p, pos, next - pos, || {
                    fake_cs((base / 1000) as u8)
                });
                pos = next;
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        assert!(cache.spilled_start_count() >= 1);
        let used_slots = |p: &crate::blocks::BlockPool| {
            (1..=p.len()).filter(|&i| p.record(Slot::new(i as u32).unwrap()).unwrap().refs() > 0).count()
        };
        let used_before = used_slots(&pools.full);

        cache.max_spilled_starts = 0;
        let trimmed = cache.maintain_spill_during_gpu();
        assert!(trimmed >= 1);
        assert_eq!(cache.spilled_start_count(), 0);
        assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        assert_eq!(cache.stats().spill_maint_passes, 1);
        assert_eq!(used_slots(&pools.full), used_before, "RAM pool slots must not be mutated during GPU overlap");

        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn doomed_allocation_and_mid_span_rollback_preserve_cached_starts_without_spill() {
        let dir = ScratchDir::new("u105-bounded-evict");
        let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 1).unwrap();
        // 10 Full slots, 16 Window slots.
        let mut pools = BlockPools::with_capacities(10, 16, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut tbl_active = BlockTable::new(32).unwrap();
        let mut st_active = LaneBlockState::default();
        let mut tbl = BlockTable::new(32).unwrap();
        let mut st = LaneBlockState::default();

        // Populate 2 distinct cached start points of 3 blocks (192 tokens) each -> 6 evictable Full slots.
        let p_a: Vec<u32> = (0..=192u32).map(|i| 1_000 + i).collect();
        let p_b: Vec<u32> = (0..=192u32).map(|i| 2_000 + i).collect();
        retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p_a, 0x11);
        retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p_b, 0x22);
        assert_eq!(cache.retained_start_count(), 2);

        // Pin 2 Full slots on an active lane -> 2 free + 6 evictable = 8 reclaimable Full slots (K - 1 = 8).
        cache.ensure_span_blocks(&mut pools, &mut tbl_active, 0, 128).unwrap();
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 8);
        assert_eq!(cache.stats().start_points_evicted, 0);
        assert_eq!(cache.stats().starts_spilled, 0);

        // (a) Request needing K = 9 Full slots when free + evictable == 8 (K - 1) MUST fail with
        // PoolExhausted(Full) while evicting and spilling ZERO cached start points!
        let mut doomed_tbl = BlockTable::new(32).unwrap();
        assert_eq!(
            cache.ensure_span_blocks(&mut pools, &mut doomed_tbl, 0, 9 * BLOCK),
            Err(CacheError::PoolExhausted(BlockKind::Full))
        );
        assert_eq!(cache.retained_start_count(), 2, "doomed span must not empty cached start points");
        assert_eq!(cache.stats().start_points_evicted, 0, "zero start points evicted on doomed span");
        assert_eq!(cache.stats().starts_spilled, 0, "zero start points spilled on doomed span");
        assert_eq!(cache.spilled_start_count(), 0);
        assert_eq!(cache.peek_match_len(&pools, &p_a), 192);
        assert_eq!(cache.peek_match_len(&pools, &p_b), 192);

        // Also test single-slot take_zeroed_slot when remaining slots are 100% pinned by active lane:
        // pin the remaining 2 free slots, plus pin p_a and p_b on active tables so free + evictable == 0.
        let mut pin_a_tbl = BlockTable::new(32).unwrap();
        let mut pin_a_st = LaneBlockState::default();
        let mut pin_b_tbl = BlockTable::new(32).unwrap();
        let mut pin_b_st = LaneBlockState::default();
        assert_eq!(cache.match_and_bind(&mut pools, &mut pin_a_tbl, &mut pin_a_st, &p_a).unwrap().0, 192);
        assert_eq!(cache.match_and_bind(&mut pools, &mut pin_b_tbl, &mut pin_b_st, &p_b).unwrap().0, 192);
        cache.ensure_span_blocks(&mut pools, &mut tbl_active, 128, 128).unwrap();
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 0);
        assert_eq!(
            cache.take_zeroed_slot(&mut pools, BlockKind::Full),
            Err(CacheError::PoolExhausted(BlockKind::Full))
        );
        assert_eq!(cache.retained_start_count(), 2, "active-pinned starts must not be evicted on exhaustion");
        assert_eq!(cache.stats().start_points_evicted, 0);
        cache.release_lane(&mut pools, &mut pin_a_tbl, &mut pin_a_st);
        cache.release_lane(&mut pools, &mut pin_b_tbl, &mut pin_b_st);

        // Release 2 slots on tbl_active so 2 free + 6 evictable = 8 reclaimable Full slots again.
        cache.release_lane(&mut pools, &mut tbl_active, &mut st_active);
        cache.ensure_span_blocks(&mut pools, &mut tbl_active, 0, 128).unwrap();
        assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 8);

        // (b1) Satisfiable request needing 4 Full slots (2 free + 2 from oldest victim p_a) evicts ONLY p_a
        // and keeps newer p_b intact in RAM!
        // First test mid-span rollback via `try_ensure_span_blocks_with` aborting at block 2 (after 2 free
        // slots were taken, right before victim eviction): cache stays at 2 retained starts and 0 leaks!
        let mut rb_tbl = BlockTable::new(32).unwrap();
        assert_eq!(
            cache.try_ensure_span_blocks_with(&mut pools, &mut rb_tbl, 0, 4 * BLOCK, |blk, kind| {
                if blk == 2 && kind == BlockKind::Full {
                    Err(CacheError::PoolExhausted(BlockKind::Full))
                } else {
                    Ok(())
                }
            }),
            Err(CacheError::PoolExhausted(BlockKind::Full))
        );
        for b in 0..4u32 {
            assert_eq!(rb_tbl.get(BlockKind::Full, BlockIndex::new(b)).unwrap(), None);
            assert_eq!(rb_tbl.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), None);
        }
        assert_eq!(cache.retained_start_count(), 2, "rolled-back span must leave both cached starts intact");
        assert_eq!(cache.stats().start_points_evicted, 0);
        assert_eq!(cache.stats().starts_spilled, 0);

        // (b2) Now run the 4-block allocation to completion: only oldest victim p_a is evicted (1 eviction),
        // leaving p_b warm in RAM!
        cache.ensure_span_blocks(&mut pools, &mut rb_tbl, 0, 4 * BLOCK).unwrap();
        assert_eq!(cache.retained_start_count(), 1, "only the 1 needed LRU victim may be evicted");
        assert_eq!(cache.stats().start_points_evicted, 1);
        assert_eq!(cache.peek_match_len(&pools, &p_b), 192, "newer start p_b must remain warm in RAM");

        cache.release_lane(&mut pools, &mut rb_tbl, &mut st);
        cache.release_lane(&mut pools, &mut tbl_active, &mut st_active);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn failed_rebind_leaves_lane_prior_bindings_intact() {
        let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        // `tbl` has capacity for 2 blocks (128 tokens), while `tbl2` has capacity for 8 blocks (512 tokens).
        let mut tbl = BlockTable::new(2).unwrap();
        let mut st = LaneBlockState::default();

        let full_prompt: Vec<u32> = (0..=256u32).map(|i| 5000 + i).collect();
        let short_prompt = &full_prompt[..=128]; // checkpoint at 128 (`len - 1 == 128`)
        let _tip128 = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, short_prompt, 0x11);

        // Bind Lane 1 to the 128-token checkpoint first.
        let (matched, cs) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &full_prompt).unwrap();
        assert_eq!(matched, 128);
        assert_eq!(cs, fake_cs(0x11));
        let prior_b0_full = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
        let prior_b1_full = tbl.get(BlockKind::Full, BlockIndex::new(1)).unwrap().unwrap();
        let prior_sealed = st.sealed.clone();

        // Install a live deeper start point at 256 (4 blocks) on Lane 2 (`tbl2` capacity 8).
        let mut tbl2 = BlockTable::new(8).unwrap();
        let mut st2 = LaneBlockState::default();
        let tip256 = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &full_prompt, 0x33);

        // 1. Mid-staging failure: `tbl` (capacity 2) cannot stage block index 2 of the 256-token start!
        // `rebind_if_deeper_match` must roll back its staged entries and return `None` while keeping
        // Lane 1's existing 128-token bindings, `written == 128`, and refcounts 100% intact!
        assert_eq!(cache.rebind_if_deeper_match(&mut pools, &mut tbl, &mut st, &full_prompt, 128), None);
        assert_eq!(st.written, 128);
        assert_eq!(st.sealed, prior_sealed);
        assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(prior_b0_full));
        assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(1)).unwrap(), Some(prior_b1_full));

        // 2. Stale/corrupted deeper candidate in `starts` on a wide table (`tbl_wide` capacity 8):
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        let mut tbl_wide = BlockTable::new(8).unwrap();
        assert!(cache.evict_start(&mut pools, tip256));
        let (matched_w, _) = cache.match_and_bind(&mut pools, &mut tbl_wide, &mut st, &full_prompt).unwrap();
        assert_eq!(matched_w, 128);
        let tip256_stale = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &full_prompt, 0x44);
        // Simulate a stale entry in `starts` whose pool ref was dropped and generation advanced:
        {
            let bad = cache.starts.get_mut(&tip256_stale).unwrap().entries.last_mut().unwrap();
            pools.of_mut(bad.0).record_mut(bad.2.slot()).unwrap().drop_ref().unwrap();
            bad.2 = BlockEntry::new(bad.2.slot(), bad.2.generation() + 99, bad.2.offset(), bad.0, bad.2.kvb());
        }
        assert_eq!(cache.rebind_if_deeper_match(&mut pools, &mut tbl_wide, &mut st, &full_prompt, 128), None);
        assert_eq!(st.written, 128);
        assert_eq!(st.sealed, prior_sealed);
        assert_eq!(tbl_wide.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(prior_b0_full));
        assert_eq!(tbl_wide.get(BlockKind::Full, BlockIndex::new(1)).unwrap(), Some(prior_b1_full));

        cache.release_lane(&mut pools, &mut tbl_wide, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn spill_retained_start_owns_reused_disk_blocks_across_trim_and_same_tip_overwrite() {
        let dir = ScratchDir::new("reused-disk-ownership");
        let store = SpillStore::open_with_kvb(&dir.0, 256 * 1024 * 1024, 1).unwrap();
        let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        cache.max_spilled_starts = 1;
        let mut tbl = BlockTable::new(32).unwrap();
        let mut st = LaneBlockState::default();

        // Prompt A (checkpoint at 128 = 2 blocks) and Prompt B (shares block 0 with A, checkpoint at 192 = 3 blocks).
        let prompt_a: Vec<u32> = (0..=128u32).map(|i| 70_000 + i).collect();
        let mut prompt_b: Vec<u32> = prompt_a[..64].to_vec();
        prompt_b.extend((0..=128u32).map(|i| 80_000 + i));

        let tip_a = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt_a, 0x41);
        let tip_b = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt_b, 0x42);

        // Spill A first (`spilled_starts.len() == 1 == max_spilled_starts`).
        assert!(cache.evict_start(&mut pools, tip_a));
        assert_eq!(cache.spilled_start_count(), 1);

        // Now spill B: `max_spilled_starts == 1` trims A at the start of `spill_retained_start`,
        // while B reuses A's shared block-0 Full/Window `.blk` files from `entry_spill_keys`.
        // Because B claims ownership of reused keys from the start, trimming A must NOT delete block 0!
        assert!(cache.evict_start(&mut pools, tip_b));
        assert_eq!(cache.spilled_start_count(), 1);

        let (matched_b, cs_b) = cache
            .match_and_bind(&mut pools, &mut tbl, &mut st, &prompt_b)
            .expect("Prompt B must restore cleanly including shared reused block 0");
        assert_eq!(matched_b, 192);
        assert_eq!(cs_b, fake_cs(0x42));

        // Same-tip overwrite: keep `tbl` pinned to B's live blocks (0..3) while evicting the restored
        // start back to `spilled_starts`, then re-retain the same 192-token prefix on `tbl2` and spill it
        // again at the exact same `sp_tip` while `spilled_starts` ALREADY holds `sp_tip`!
        cache.max_spilled_starts = 4;
        let tip_b_restored = *st.sealed.last().unwrap();
        assert!(cache.evict_start(&mut pools, tip_b_restored));
        assert_eq!(cache.spilled_start_count(), 1);

        let mut tbl2 = BlockTable::new(32).unwrap();
        let mut st2 = LaneBlockState { prompt_len: prompt_b.len(), ..Default::default() };
        cache.ensure_span_blocks(&mut pools, &mut tbl2, 0, 192).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &prompt_b, 0, 192, || fake_cs(0x43));
        let tip_b_dup = *st2.sealed.last().unwrap();
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // Evicting `tip_b_dup` overwrites the existing `sp_tip` in `tip_to_spill` while reusing all 6 `.blk` files!
        assert!(cache.evict_start(&mut pools, tip_b_dup));
        assert_eq!(cache.spilled_start_count(), 1);
        let (matched_b3, cs_b3) = cache
            .match_and_bind(&mut pools, &mut tbl, &mut st, &prompt_b)
            .expect("same-tip re-spilled start must retain its reused disk blocks");
        assert_eq!(matched_b3, 192);
        assert_eq!(cs_b3, fake_cs(0x43));
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn spill_index_persists_across_reopen_and_async_restore_keeps_decoding_responsive() {
        let dir = ScratchDir::new("persist-and-async");
        {
            let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
            let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
            let mut cache = ServeBlockCache::with_spill(store);
            let mut tbl = BlockTable::new(32).unwrap();
            let mut st = LaneBlockState::default();

            let p0: Vec<u32> = (0..=512u32).map(|i| 10_000 + i).collect();
            let tip0 = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p0, 0x5A);
            assert!(cache.evict_start(&mut pools, tip0));
            assert_eq!(cache.spilled_start_count(), 1);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // Reopen SpillStore + ServeBlockCache from the same directory (simulating process restart).
        let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
        let mut pools = BlockPools::with_capacities(24, 24, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        assert_eq!(cache.spilled_start_count(), 1, "spilled start index must reload across restart");

        // Install a slow disk read barrier on this spill dir so lane 1 stays in `Restoring`
        // while unrelated Ready lane 0 executes 8 responsive decode steps in < 5 ms per step!
        let target_dir = dir.0.clone();
        let entered = Arc::new((Mutex::new(false), Condvar::new()));
        let release = Arc::new((Mutex::new(false), Condvar::new()));
        let entered_bg = entered.clone();
        let release_bg = release.clone();
        struct ReadHookGuard(Vec<Arc<(Mutex<bool>, Condvar)>>);
        impl Drop for ReadHookGuard {
            fn drop(&mut self) {
                crate::spill::set_test_spill_read_hook(None);
                for b in &self.0 {
                    *b.0.lock().unwrap() = true;
                    b.1.notify_all();
                }
            }
        }
        let hold = Arc::new((Mutex::new(false), Condvar::new()));
        let _hook_guard = ReadHookGuard(vec![release.clone(), hold.clone()]);
        crate::spill::set_test_spill_read_hook(Some(Arc::new(move |d, _key| {
            if d == target_dir {
                let mut e = entered_bg.0.lock().unwrap();
                if !*e {
                    *e = true;
                    entered_bg.1.notify_all();
                    drop(e);
                    let mut r = release_bg.0.lock().unwrap();
                    while !*r {
                        r = release_bg.1.wait(r).unwrap();
                    }
                }
            }
        })));

        let mut planner = crate::scheduler::ServeStepPlanner::new(3, 16);
        // Lane 0: Ready decoding lane at pos = 64.
        let mut tbl0 = BlockTable::new(32).unwrap();
        let mut st0 = LaneBlockState::default();
        let p_dec: Vec<u32> = (0..=64u32).map(|i| 90_000 + i).collect();
        retain_test_prompt(&mut cache, &mut pools, &mut tbl0, &mut st0, &p_dec, 0x33);
        let _ = cache.match_and_bind(&mut pools, &mut tbl0, &mut st0, &p_dec);
        planner.on_admit(0);

        // Lane 1: Cold SSD restore after restart (`begin_admit_bind` -> `Restoring`).
        let mut tbl1 = BlockTable::new(32).unwrap();
        let mut st1 = LaneBlockState::default();
        let mut p0_cont: Vec<u32> = (0..=512u32).map(|i| 10_000 + i).collect();
        p0_cont.extend(70_000..70_020);
        match cache.begin_admit_bind(&mut pools, 1, &mut tbl1, &mut st1, &p0_cont) {
            AdmitBindOutcome::Restoring { target_pos } => {
                assert_eq!(target_pos, 512);
                planner.admit_queued(1, crate::scheduler::LaneState::Queued);
                planner.start_restore(1);
            }
            other => panic!("expected Restoring from reloaded spill index, got {other:?}"),
        }

        // Wait until background restore worker is actively blocked inside disk read.
        {
            let mut e = entered.0.lock().unwrap();
            while !*e {
                let (next, timeout) = entered.1.wait_timeout(e, Duration::from_secs(5)).unwrap();
                assert!(!timeout.timed_out(), "background restore worker did not enter read");
                e = next;
            }
        }

        // Run 8 decode steps on Ready lane 0 while lane 1 is blocked in cold SSD read!
        let mut max_step_overhead = Duration::ZERO;
        for dec_pos in 64usize..72 {
            let t0 = Instant::now();
            let done = cache.poll_restores(&mut pools, |_| None);
            assert!(done.is_empty(), "restore is still held on barrier");
            let inputs = [
                crate::scheduler::ServeLaneInput {
                    runnable: true,
                    n_past: dec_pos,
                    pf_end: 64,
                    has_pending_decode: true,
                },
                crate::scheduler::ServeLaneInput {
                    runnable: true,
                    n_past: 0,
                    pf_end: p0_cont.len(),
                    has_pending_decode: false,
                },
                crate::scheduler::ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
            ];
            let plan = planner.plan_and_begin_step(&inputs, 2048, BLOCK).unwrap();
            assert_eq!(plan, crate::scheduler::ServeStepPlan::Decode(vec![0]));
            cache.ensure_span_blocks(&mut pools, &mut tbl0, dec_pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl0, &mut st0, dec_pos);
            assert!(planner.complete_step().is_empty());
            max_step_overhead = max_step_overhead.max(t0.elapsed());
        }
        assert!(
            max_step_overhead < Duration::from_millis(5),
            "scheduler decode step overhead {max_step_overhead:?} exceeded 5ms while cold SSD restore ran"
        );
        eprintln!(
            "[async-spill-progress] 8 unrelated decode steps completed while cold SSD restore held in disk read (max_step_overhead={max_step_overhead:?})"
        );

        // Release barrier and verify lane 1 completes restore cleanly (`Restoring -> Ready` at 512).
        {
            *release.0.lock().unwrap() = true;
            release.1.notify_all();
        }
        crate::spill::set_test_spill_read_hook(None);

        let deadline = Instant::now() + Duration::from_secs(5);
        let mut finished = None;
        while Instant::now() < deadline {
            let tbl1_ptr: *mut BlockTable = &mut tbl1;
            let st1_ptr: *mut LaneBlockState = &mut st1;
            let mut done = cache.poll_restores(&mut pools, |l| (l == 1).then_some((&(), tbl1_ptr, st1_ptr)));
            if let Some(c) = done.pop() {
                finished = Some(c);
                break;
            }
            cache.wait_restore_activity(Duration::from_millis(5));
        }
        let c = finished.expect("restore must finish after barrier release");
        assert!(!c.corrupt_fallback);
        assert_eq!(c.matched, Some((512, fake_cs(0x5A))));
        planner.finish_restore(1);
        assert_eq!(planner.state(1), crate::scheduler::LaneState::Ready);
        assert_eq!(cache.stats().starts_restored, 1);

        // Also verify mid-restore client disconnect cancels cleanly with zero leaked BlockPool slots!
        let p2: Vec<u32> = (0..=256u32).map(|i| 40_000 + i).collect();
        let mut tbl2 = BlockTable::new(32).unwrap();
        let mut st2 = LaneBlockState::default();
        let tip2 = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &p2, 0x77);
        assert!(cache.evict_start(&mut pools, tip2));

        let hold_bg = hold.clone();
        let dir2 = dir.0.clone();
        crate::spill::set_test_spill_read_hook(Some(Arc::new(move |d, _| {
            if d == dir2 {
                let mut h = hold_bg.0.lock().unwrap();
                while !*h {
                    h = hold_bg.1.wait(h).unwrap();
                }
            }
        })));
        let mut p2_cont = p2.clone();
        p2_cont.push(999);
        assert!(matches!(
            cache.begin_admit_bind(&mut pools, 2, &mut tbl2, &mut st2, &p2_cont),
            AdmitBindOutcome::Restoring { target_pos: 256 }
        ));
        planner.admit_queued(2, crate::scheduler::LaneState::Queued);
        planner.start_restore(2);
        // Disconnect mid-restore!
        assert!(planner.request_cancel(2));
        assert!(cache.cancel_restore(&mut pools, 2));
        *hold.0.lock().unwrap() = true;
        hold.1.notify_all();
        crate::spill::set_test_spill_read_hook(None);

        cache.release_lane(&mut pools, &mut tbl0, &mut st0);
        cache.release_lane(&mut pools, &mut tbl1, &mut st1);
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn retained_host_copy_budget_and_spill_deadline_bound_host_work() {
        let dir = ScratchDir::new("host-budget-and-deadline");
        let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
        let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut tbl = BlockTable::new(32).unwrap();
        let mut st = LaneBlockState::default();

        // Cap retained host copies so at most 1 checkpoint fits in host RAM (`cs` 4 KiB each, cap 6 KiB).
        cache.set_max_retained_host_bytes(6 * 1024);
        let p0: Vec<u32> = (0..=64u32).map(|i| 1000 + i).collect();
        let p1: Vec<u32> = (0..=64u32).map(|i| 2000 + i).collect();
        for (p, tag) in [(&p0, 0x10u8), (&p1, 0x20u8)] {
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, p);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, p, 0, 64, || vec![tag; 4096]);
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        assert_eq!(cache.retained_start_count(), 1, "host byte budget must evict older retained start");
        assert!(cache.retained_host_bytes() <= 6 * 1024);
        assert_eq!(cache.spilled_start_count(), 1, "evicted checkpoint spills within deadline");

        // Zero spill timeout simulates an expired write deadline without sleeping: must abort cleanly!
        cache.set_spill_write_timeout(Duration::ZERO);
        let p2: Vec<u32> = (0..=64u32).map(|i| 3000 + i).collect();
        let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p2);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p2, 0, 64, || vec![0x30; 4096]);
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        assert_eq!(cache.stats().spill_write_timeouts, 1);
        assert_eq!(cache.retained_start_count(), 1);

        cache.shutdown(&mut pools);
        assert_eq!(cache.retained_host_bytes(), 0);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn cache_namespace_isolates_ram_singleflight_and_ssd_restore() {
        let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join(format!("block-cache-ns-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = SpillStore::open_with_kvb(&dir, 128 * 1024 * 1024, 1).unwrap();
        let mut pools = BlockPools::with_capacities(6, 6, 1).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        let mut tbl_a = BlockTable::new(16).unwrap();
        let mut st_a = LaneBlockState::default();
        let mut tbl_b = BlockTable::new(16).unwrap();
        let mut st_b = LaneBlockState::default();

        let prompt: Vec<u32> = (0..2100u32).map(|i| i * 31 + 7).collect();
        let ext_prompt: Vec<u32> = (0..2200u32).map(|i| i * 31 + 7).collect();

        // Singleflight leader election must NOT coalesce across distinct namespaces.
        let cands = [
            InflightPrefillLane {
                lane: 0,
                namespace: 0xAAAA,
                toks: &prompt,
                block_hashes: None,
                n_past: 0,
                pf_end: prompt.len(),
                runnable: true,
                eligible_follower: true,
            },
            InflightPrefillLane {
                lane: 1,
                namespace: 0xBBBB,
                toks: &prompt,
                block_hashes: None,
                n_past: 0,
                pf_end: prompt.len(),
                runnable: true,
                eligible_follower: true,
            },
            InflightPrefillLane {
                lane: 2,
                namespace: 0xAAAA,
                toks: &prompt,
                block_hashes: None,
                n_past: 0,
                pf_end: prompt.len(),
                runnable: true,
                eligible_follower: true,
            },
        ];
        assert_eq!(find_prefill_leader(&cands, 1), None, "different namespace must never singleflight-wait");
        assert_eq!(find_prefill_leader(&cands, 2), Some(0), "same namespace shares leader");

        // Principal A (0xAAAA) prefills `prompt[..135]` (PROMPT checkpoint at 128).
        let short_p = prompt[..135].to_vec();
        let short_ext = ext_prompt[..195].to_vec();
        assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_p).is_none());
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &short_p, 0, 128, || fake_cs(0x41));
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 128, 7).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &short_p, 128, 7, || fake_cs(0x42));
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

        // Principal B (0xBBBB) sending the exact same extended prompt gets ZERO RAM warm hit.
        assert!(
            cache.match_and_bind_in_namespace(&mut pools, &mut tbl_b, &mut st_b, 0xBBBB, &short_ext).is_none(),
            "cross-principal RAM lookup must miss"
        );
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);

        // Same principal A (0xAAAA) gets full 128-token warm hit!
        let (hit_a, cs_a) = cache
            .match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_ext)
            .expect("same-principal warm hit");
        assert_eq!(hit_a, 128);
        assert_eq!(cs_a, fake_cs(0x41));
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

        // Spill Principal A's start point to SSD, then verify Principal B gets ZERO SSD restore hit
        // while Principal A restores 128 tokens cleanly from SSD.
        assert!(cache.evict_one_lru_start_inner(&mut pools, true, None));
        assert_eq!(cache.retained_start_count(), 0);
        assert_eq!(cache.spilled_start_count(), 1);

        assert!(
            cache.match_and_bind_in_namespace(&mut pools, &mut tbl_b, &mut st_b, 0xBBBB, &short_ext).is_none(),
            "cross-principal SSD lookup must miss without restoring"
        );
        assert_eq!(cache.stats().starts_restored, 0);
        assert_eq!(cache.spilled_start_count(), 1);
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);

        let (restored_a, restored_cs) = cache
            .match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_ext)
            .expect("same-principal SSD restore hit");
        assert_eq!(restored_a, 128);
        assert_eq!(restored_cs, fake_cs(0x41));
        assert_eq!(cache.stats().starts_restored, 1);
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn verify_span_tracking_and_rollback_preserve_ownership_across_block_and_window_boundaries() {
        let mut pools = BlockPools::with_capacities(32, 32, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let mut tbl = BlockTable::new(32).unwrap();
        let mut st = LaneBlockState::default();

        // Prefill 1022 tokens (just before WINDOW = 1024 and block 16 boundary).
        let prompt: Vec<u32> = (0..1022).map(|i| (i % 997) as u32 + 1).collect();
        let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 1022).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 1022, || fake_cs(1));
        assert_eq!(st.written, 1022);
        // Window block 0 must still be present at pos 1022.
        assert!(tbl.get(BlockKind::Window, BlockIndex::new(0)).unwrap().is_some());

        // Speculative verify span `[1022, 1026)` (k = 3) crosses both block 16 (pos 1024) and WINDOW = 1024!
        let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 1022, 4).unwrap();
        assert_eq!(alloc.len(), 2, "must track newly allocated Full + Window block 16");
        assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_some());
        assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_some());

        // Reject drafts at pos 1024..1026 (`n_keep = 2`, accepted_end = 1024):
        // Block 16 (start=1024 >= accepted_end=1024) MUST be released back to BlockPools,
        // block 15 stays unsealed with length 64, and Window block 0 is NOT prematurely pruned!
        cache.finish_verify_span(&mut pools, &mut tbl, &mut st, &alloc, 1022, 2);
        assert_eq!(st.written, 1024);
        assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_none());
        assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_none());
        let b15_full = tbl.get(BlockKind::Full, BlockIndex::new(15)).unwrap().unwrap();
        let rec15 = pools.full.record(b15_full.slot()).unwrap();
        assert!(!rec15.sealed(), "verify must never seal block 15");
        assert_eq!(rec15.length(), 64);

        // Full abort (`n_keep = 0`) on `[1024, 1028)` releases all newly allocated blocks and leaves written=1024.
        let alloc2 = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 1024, 4).unwrap();
        assert_eq!(alloc2.len(), 2);
        cache.finish_verify_span(&mut pools, &mut tbl, &mut st, &alloc2, 1024, 0);
        assert_eq!(st.written, 1024);
        assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_none());
        assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_none());

        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn spill_index_rejects_full_attn_budget_and_model_fingerprint_mismatches() {
        let dir = ScratchDir::new("spill-compat-header");
        let prompt: Vec<u32> = (0..=128u32).map(|i| 20_000 + i).collect();

        // 1. Spill one checkpoint under budget=Some(1024), model_fp=0x1111.
        {
            let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
            let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
            let mut cache = ServeBlockCache::with_spill_compat(store, Some(1024), 0x1111);
            let mut tbl = BlockTable::new(8).unwrap();
            let mut st = LaneBlockState::default();
            let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt, 9);
            assert!(cache.evict_start(&mut pools, tip));
            assert_eq!(cache.spilled_start_count(), 1);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // 2. Reopen with matching (Some(1024), 0x1111): checkpoint reloads cleanly.
        {
            let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
            let cache = ServeBlockCache::with_spill_compat(store, Some(1024), 0x1111);
            assert_eq!(cache.spilled_start_count(), 1);
            assert!(cache.spill_store().unwrap().entry_count() >= 1);
        }

        // 3. Reopen with different full_attn_budget (Some(2048)): rejects & sweeps stale blocks.
        {
            let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
            let cache = ServeBlockCache::with_spill_compat(store, Some(2048), 0x1111);
            assert_eq!(cache.spilled_start_count(), 0);
            assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        }

        // 4. Re-spill under (None, 0xAAAA), then reopen with different model fingerprint (None, 0xBBBB): rejects & sweeps.
        {
            let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
            let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
            let mut cache = ServeBlockCache::with_spill_compat(store, None, 0xAAAA);
            let mut tbl = BlockTable::new(8).unwrap();
            let mut st = LaneBlockState::default();
            let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt, 9);
            assert!(cache.evict_start(&mut pools, tip));
            assert_eq!(cache.spilled_start_count(), 1);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
        {
            let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
            let cache = ServeBlockCache::with_spill_compat(store, None, 0xBBBB);
            assert_eq!(cache.spilled_start_count(), 0);
            assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        }
    }

    #[test]
    fn kv4_serve_block_cache_keeps_exact_fp32_cs_and_binds_dc_digest_fingerprint() {
        use crate::blocks::{KvMode, KVB_KV4};
        use crate::spill::{Sha256, SpillError};

        const CS_FLOATS: usize = 958_464; // 3.66 MiB = 3,833,856 bytes
        const CS_F32_BYTES: usize = CS_FLOATS * 4;

        let mut raw_cs = Vec::with_capacity(CS_F32_BYTES);
        for i in 0..CS_FLOATS {
            let v = ((i as f32) * 0.001_37 - 400.0).sin() * 3.25;
            raw_cs.extend_from_slice(&v.to_le_bytes());
        }
        let prompt: Vec<u32> = (0..=64u32).map(|i| 50_000 + i).collect();

        let mut h_cal = Sha256::new();
        h_cal.update(b"inky-kv4-codec-v1\0");
        h_cal.update(&[1u8, 1u8, 1u8]);
        h_cal.update(&vec![0x5au8; 98_304]);
        let dc_digest = h_cal.finalize();
        let model_fp = 0x1234_5678_9abc_def0u64 ^ u64::from_le_bytes(dc_digest[0..8].try_into().unwrap());

        let dir = ScratchDir::new("kv4-cs-fp32-exact");
        {
            let mut pools = BlockPools::with_capacities_mode(4, 4, KvMode::Kv4).unwrap();
            let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
            let mut cache = ServeBlockCache::with_spill_compat(store, None, model_fp);

            let mut tbl = BlockTable::new(4).unwrap();
            let mut st = LaneBlockState { prompt_len: prompt.len(), ..Default::default() };
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 64, || raw_cs.clone());
            let tip = *st.sealed.last().unwrap();
            cache.release_lane(&mut pools, &mut tbl, &mut st);

            // Host RAM checkpoint retains exact 3,833,856-byte FP32 cs (zero rounding).
            assert!(cache.retained_host_bytes() >= CS_F32_BYTES as u64);
            let (matched_ram, cs_ram) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).unwrap();
            assert_eq!(matched_ram, 64);
            assert_eq!(cs_ram, raw_cs);
            cache.release_lane(&mut pools, &mut tbl, &mut st);

            // Evict to SSD SpillStore: persists exact 3.66 MiB FP32 cs + 528 KiB / 2,640 KiB KV4 blocks.
            assert!(cache.evict_start(&mut pools, tip));
            assert_eq!(cache.spilled_start_count(), 1);
            let ssd_used = cache.spill_store().unwrap().used_bytes();
            let expected_ssd = crate::blocks::KV4_FULL_STRIDE
                + crate::blocks::KV4_WINDOW_STRIDE
                + CS_F32_BYTES as u64
                + 3 * (crate::spill::SPILL_HEADER_LEN as u64);
            assert_eq!(ssd_used, expected_ssd);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // Reopen with a different K_DC_ROT digest fails closed at SpillStore open time.
        let mut wrong_digest = dc_digest;
        wrong_digest[0] ^= 0xff;
        assert!(matches!(
            SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, wrong_digest),
            Err(SpillError::ModeMismatch { expected, found }) if expected == KVB_KV4 && found == KVB_KV4
        ));

        // Reopen with the matching K_DC_ROT digest & model_fingerprint restores cs 100% bit-for-bit.
        {
            let mut pools = BlockPools::with_capacities_mode(4, 4, KvMode::Kv4).unwrap();
            let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
            let mut cache = ServeBlockCache::with_spill_compat(store, None, model_fp);
            assert_eq!(cache.spilled_start_count(), 1);
            let mut tbl = BlockTable::new(4).unwrap();
            let mut st = LaneBlockState::default();
            let (matched_ssd, cs_ssd) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).unwrap();
            assert_eq!(matched_ssd, 64);
            assert_eq!(cs_ssd, raw_cs);
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    #[test]
    fn sparse_topk_spill_compat_and_restore_sketch_recompute() {
        let dir = ScratchDir::new("sparse-topk-spill-compat");
        let prompt: Vec<u32> = (0..=64u32).map(|i| 30_000 + i).collect();

        // Default (`enable_sketches = false`) allocates 0 sketch bytes.
        let default_pools = BlockPools::with_capacities(2, 2, 1).unwrap();
        assert!(!default_pools.full.has_sketches());

        let spill_once = || {
            let mut pools = BlockPools::with_capacities_and_sketches(2, 2, 1, true).unwrap();
            let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
            let mut cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 4, 0xCCCC);
            let mut tbl = BlockTable::new(4).unwrap();
            let mut st = LaneBlockState::default();
            let start = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).map_or(0, |(p, _)| p);
            let end = prompt.len() - 1;
            cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
            let orig_slot = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();
            for (i, b) in pools.full.slot_bytes_mut(orig_slot).unwrap().iter_mut().enumerate() {
                *b = ((i.wrapping_mul(37).wrapping_add(13)) & 0x7f) as u8;
            }
            let mut expected_sketch = vec![0u8; crate::blocks::FULL_SKETCH_BYTES];
            crate::blocks::compute_full_slot_wht2_sketch_cpu(
                pools.full.slot_bytes(orig_slot).unwrap(),
                1,
                BLOCK,
                &mut expected_sketch,
            );
            assert!(expected_sketch.iter().any(|&b| b != 0), "expected sketch must be non-trivial");
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, start, end - start, || fake_cs(9));
            let tip = *st.sealed.last().unwrap();
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            assert!(cache.evict_start(&mut pools, tip));
            assert_eq!(cache.spilled_start_count(), 1);
            // Explicitly zero KV bytes and poison sketch bytes in every Full slot so `match_and_bind`
            // restore proves real recomputation from the SSD-spilled KV bytes.
            for idx in 1..=2u32 {
                let s = crate::blocks::Slot::new(idx).unwrap();
                pools.full.slot_bytes_mut(s).unwrap().fill(0);
                pools.full.slot_sketch_bytes_mut(s).unwrap().fill(0x5A);
            }

            // Sync restore (`match_and_bind`) restores Full slot and recomputes its exact 17,408 B sketch.
            let mut tbl2 = BlockTable::new(4).unwrap();
            let mut st2 = LaneBlockState::default();
            let matched = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &prompt);
            assert_eq!(matched.as_ref().map(|(at, _)| *at), Some(64));
            let entry = tbl2.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
            assert_eq!(pools.full.slot_sketch_valid_len(entry.slot()).unwrap(), BLOCK as u8);
            assert_eq!(pools.full.slot_sketch_bytes(entry.slot()).unwrap(), expected_sketch.as_slice());
            let restored_tip = *st2.sealed.last().unwrap();
            cache.release_lane(&mut pools, &mut tbl2, &mut st2);
            assert!(cache.evict_start(&mut pools, restored_tip));
            assert_eq!(cache.spilled_start_count(), 1);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        };

        spill_once();
        // Matching `(Some(128), anchors = 4)` reloads the spilled start cleanly.
        {
            let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
            let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 4, 0xCCCC);
            assert_eq!(cache.spilled_start_count(), 1);
        }
        // 1. Changing `anchors` (`4 -> 8`) rejects and sweeps spilled files.
        {
            let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
            let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 8, 0xCCCC);
            assert_eq!(cache.spilled_start_count(), 0);
            assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        }
        // 2. Changing `topk` (`Some(128) -> Some(64)`) rejects and sweeps spilled files.
        spill_once();
        {
            let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
            let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(64), 4, 0xCCCC);
            assert_eq!(cache.spilled_start_count(), 0);
            assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        }
        // 3. Transitioning `sparse -> dense` (`Some(128) -> None`) rejects and sweeps spilled files.
        spill_once();
        {
            let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
            let cache = ServeBlockCache::with_spill_compat_sparse(store, None, None, 4, 0xCCCC);
            assert_eq!(cache.spilled_start_count(), 0);
            assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
        }
    }

    #[test]
    fn kv4_and_sparse_topk_spill_restore_recomputes_wht2_sketch() {
        use crate::blocks::{KvMode, KVB_KV4};
        use crate::spill::Sha256;

        let dir = ScratchDir::new("kv4-sparse-topk-spill");
        let prompt: Vec<u32> = (0..=64u32).map(|i| 42_000 + i).collect();
        let mut h_cal = Sha256::new();
        h_cal.update(b"inky-kv4-codec-v1\0");
        h_cal.update(&[1u8, 1u8, 1u8]);
        h_cal.update(&vec![0x33u8; 98_304]);
        let dc_digest = h_cal.finalize();
        let model_fp = 0xCAFE_BABE_1234_5678u64 ^ u64::from_le_bytes(dc_digest[0..8].try_into().unwrap());

        let mut pools = BlockPools::with_capacities_mode_and_sketches(2, 2, KvMode::Kv4, true).unwrap();
        let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
        let mut cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(4), 2, model_fp);

        let mut tbl = BlockTable::new(4).unwrap();
        let mut st = LaneBlockState::default();
        let start = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).map_or(0, |(p, _)| p);
        let end = prompt.len() - 1;
        cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
        let orig_slot = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();
        {
            let bytes = pools.full.slot_bytes_mut(orig_slot).unwrap();
            let row_len = crate::blocks::KV4_ROW_BYTES as usize;
            for (row_idx, chunk) in bytes.chunks_exact_mut(row_len).enumerate() {
                for (j, b) in chunk[..64].iter_mut().enumerate() {
                    let lo = ((row_idx + j) % 16) as u8;
                    let hi = ((row_idx * 3 + j + 5) % 16) as u8;
                    *b = lo | (hi << 4);
                }
                let sc_bits = crate::blocks::f32_to_f16_bits(0.5 + ((row_idx % 7) as f32) * 0.125);
                chunk[64..66].copy_from_slice(&sc_bits.to_le_bytes());
            }
        }
        let mut expected_sketch = vec![0u8; crate::blocks::FULL_SKETCH_BYTES];
        crate::blocks::compute_full_slot_wht2_sketch_cpu(
            pools.full.slot_bytes(orig_slot).unwrap(),
            KVB_KV4,
            BLOCK,
            &mut expected_sketch,
        );
        assert!(expected_sketch.iter().any(|&b| b != 0));
        let raw_cs = fake_cs(77);
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, start, end - start, || raw_cs.clone());
        let tip = *st.sealed.last().unwrap();
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        assert!(cache.evict_start(&mut pools, tip));
        assert_eq!(cache.spilled_start_count(), 1);

        // Poison KV and sketch sidecars, then restore from SSD and verify exact KV4 sketch recomputation.
        for idx in 1..=2u32 {
            let s = crate::blocks::Slot::new(idx).unwrap();
            pools.full.slot_bytes_mut(s).unwrap().fill(0);
            pools.full.slot_sketch_bytes_mut(s).unwrap().fill(0xCC);
        }
        let mut tbl2 = BlockTable::new(4).unwrap();
        let mut st2 = LaneBlockState::default();
        let (matched, cs_out) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &prompt).unwrap();
        assert_eq!(matched, 64);
        assert_eq!(cs_out, raw_cs);
        let entry = tbl2.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
        assert_eq!(pools.full.slot_sketch_valid_len(entry.slot()).unwrap(), BLOCK as u8);
        assert_eq!(pools.full.slot_sketch_bytes(entry.slot()).unwrap(), expected_sketch.as_slice());
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    fn stamp_test_full_block_rows(slot_bytes: &mut [u8], blk_toks: &[u32], kvb: u32) {
        use crate::blocks::{key_row, kv4_key_row, Kv, KvMode};
        assert_eq!(blk_toks.len(), BLOCK);
        let mode = KvMode::from_kvb_tag(kvb).unwrap();
        let row_bytes = mode.row_bytes() as usize;
        for pass in 0..(FULL_PASSES as u32) {
            for (plane, kv) in [(0u32, Kv::Key), (1u32, Kv::Value)] {
                for head in 0..(NKV as u32) {
                    for (ib, &tok) in blk_toks.iter().enumerate() {
                        let off = if mode == KvMode::Kv4 {
                            kv4_key_row(0, BlockKind::Full, pass, kv, head, ib as u32).unwrap().0 as usize
                        } else {
                            key_row(0, BlockKind::Full, kvb, pass, kv, head, ib as u32).unwrap() as usize
                        };
                        for d in 0..row_bytes {
                            let v = tok
                                .wrapping_mul(131)
                                .wrapping_add(pass * 37)
                                .wrapping_add(plane * 19)
                                .wrapping_add(head * 7)
                                .wrapping_add(d as u32);
                            slot_bytes[off + d] = (v ^ (v >> 8) ^ (v >> 16)) as u8;
                        }
                    }
                }
            }
        }
    }

    fn assert_test_full_block_rows_match(slot_bytes: &[u8], blk_toks: &[u32], kvb: u32) {
        let mut expected = vec![0u8; slot_bytes.len()];
        stamp_test_full_block_rows(&mut expected, blk_toks, kvb);
        assert_eq!(slot_bytes, expected.as_slice(), "stitched Full block K/V rows diverged from token-exact reference");
    }

    #[test]
    fn rolling_stitch_hash_64_matches_full_recompute_and_default_kv_stitch_is_disabled() {
        let toks: Vec<u32> = (0..2600u32).map(|i| i.wrapping_mul(2654435761) % 65000).collect();
        let mut h = stitch_hash_64(&toks[0..BLOCK]);
        for i in 0..(toks.len() - BLOCK) {
            assert_eq!(h, stitch_hash_64(&toks[i..i + BLOCK]), "rolling hash mismatch at {i}");
            h = slide_stitch_hash_64(h, toks[i], toks[i + BLOCK]);
        }
        assert_eq!(h, stitch_hash_64(&toks[toks.len() - BLOCK..]));

        let mut pools = BlockPools::with_capacities(96, 64, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        assert!(!cache.kv_stitch_enabled(), "Decision 4 exactness requires --kv-stitch disabled by default");
        let mut tbl = BlockTable::new(96).unwrap();
        let mut st = LaneBlockState::default();
        let _ = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &toks[..2049], 5);

        let mut shifted = vec![77777u32; 83];
        shifted.extend_from_slice(&toks[..2048]);
        shifted.extend_from_slice(&[88888u32; 64]);
        assert!(
            cache.plan_stitches(&pools, 0, &shifted, 0).is_empty(),
            "plan_stitches must return empty when kv_stitch is disabled"
        );
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn kv_stitch_disabled_touches_zero_stitch_state_and_matches_baseline_identically() {
        let run_workload = |toggle_on_then_off: bool| -> (CacheStats, usize, u64) {
            let mut pools = BlockPools::with_capacities(96, 64, 1).unwrap();
            let mut cache = ServeBlockCache::new();
            if toggle_on_then_off {
                cache.set_kv_stitch(true);
                cache.set_kv_stitch(false);
            }
            assert!(!cache.kv_stitch_enabled());
            assert!(cache.stitch_index.is_empty());

            let shared_doc: Vec<u32> = (0..2048u32).map(|i| 15_000 + i).collect();
            let mut p1: Vec<u32> = (0..128u32).map(|i| 100 + i).collect();
            p1.extend_from_slice(&shared_doc);
            p1.push(99_999);

            let mut tbl = BlockTable::new(96).unwrap();
            let mut st = LaneBlockState::default();
            let sid = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p1, 0x77);
            assert!(cache.stitch_index.is_empty(), "kv_stitch=false must never populate stitch_index");
            assert!(
                cache.starts.get(&sid).unwrap().toks.is_empty(),
                "kv_stitch=false without spill_store must not retain token vectors in RAM"
            );

            // Exact prefix hit still works identically when kv_stitch=false.
            let mut p1_followup = p1[..2176].to_vec();
            p1_followup.extend_from_slice(&[55_555u32; 65]);
            let matched = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p1_followup);
            assert_eq!(matched.map(|m| m.0), Some(2176));
            cache.release_lane(&mut pools, &mut tbl, &mut st);

            // Shifted prompt gets zero stitch plans, and forged apply_stitch_plan returns SourceGone.
            let mut shifted: Vec<u32> = (0..147u32).map(|i| 800 + i).collect();
            shifted.extend_from_slice(&shared_doc);
            shifted.extend_from_slice(&[44_444u32; 129]);
            assert!(cache.plan_stitches(&pools, 0, &shifted, 0).is_empty());
            let forged = StitchSpanPlan {
                span_start: 0,
                stitch_start: 1024,
                heal_start: 1536,
                span_end: 3072,
                source: StitchSource::Retained { sid, src_start: 1152 },
            };
            assert_eq!(
                cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &shifted, &forged),
                StitchApplyOutcome::SourceGone
            );
            assert!(!st.stitched_approx);
            assert_eq!(cache.stats().stitch_hits, 0);
            assert_eq!(cache.stats().stitched_tokens_total, 0);

            let stats = cache.stats();
            let tree_len = cache.tree.entries().len();
            let host_bytes = cache.retained_host_bytes;
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
            (stats, tree_len, host_bytes)
        };

        let (stats_fresh, tree_fresh, host_fresh) = run_workload(false);
        let (stats_toggled, tree_toggled, host_toggled) = run_workload(true);
        assert_eq!(stats_fresh, stats_toggled);
        assert_eq!(tree_fresh, tree_toggled);
        assert_eq!(host_fresh, host_toggled);
    }

    #[test]
    fn kv_stitch_provenance_isolation_keeps_entry_tree_exact_and_prevents_chained_stitches() {
        let kvb = 1u32;
        let mut pools = BlockPools::with_capacities(256, 96, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);

        let file_span: Vec<u32> = (0..3200u32).map(|i| 10_000 + i).collect(); // 50 blocks
        let mut prompt_a: Vec<u32> = (0..128u32).map(|i| 1_000 + i).collect(); // 2 blocks
        prompt_a.extend_from_slice(&file_span);
        prompt_a.extend((0..257u32).map(|i| 40_000 + i)); // total 3585 -> exact PROMPT start saved at 3584 (56 blocks)

        let mut tbl_a = BlockTable::new(128).unwrap();
        let mut st_a = LaneBlockState { prompt_len: prompt_a.len(), ..Default::default() };
        for b in 0..56usize {
            let p0 = b * BLOCK;
            cache.ensure_span_blocks(&mut pools, &mut tbl_a, p0, BLOCK).unwrap();
            let fe = tbl_a.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
            stamp_test_full_block_rows(pools.full.slot_bytes_mut(fe.slot()).unwrap(), &prompt_a[p0..p0 + BLOCK], kvb);
            cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, p0, BLOCK, || fake_cs(0x11));
        }
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 3584, 1).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 3584, 1, || fake_cs(0x12));
        let a_slots: Vec<Slot> = (0..56u32)
            .map(|b| tbl_a.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap().slot())
            .collect();
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

        // 1. Aligned shift (+128 tokens, Δpos % 64 == 0): zero-copy shares physical Full slots!
        let mut prompt_b: Vec<u32> = (0..256u32).map(|i| 2_000 + i).collect(); // 4 blocks -> file_span at 256..3456
        prompt_b.extend_from_slice(&file_span);
        prompt_b.extend((0..129u32).map(|i| 50_000 + i));
        let plans_b = cache.plan_stitches(&pools, 0, &prompt_b, 0);
        assert_eq!(plans_b.len(), 1);
        assert_eq!(plans_b[0].span_start, 256);
        assert_eq!(plans_b[0].stitch_start, 1280);
        assert_eq!(plans_b[0].heal_start, 1920);
        assert_eq!(plans_b[0].span_end, 3456);

        let mut tbl_b = BlockTable::new(128).unwrap();
        let mut st_b = LaneBlockState { prompt_len: prompt_b.len(), ..Default::default() };
        cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 1280).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b, &prompt_b, 0, 1280, || fake_cs(0x21));
        let out_b = cache.apply_stitch_plan(&mut pools, &mut tbl_b, &mut st_b, &prompt_b, &plans_b[0]);
        assert_eq!(out_b, StitchApplyOutcome::Applied { stitched_tokens: 640, zero_copy_blocks: 10 });
        assert!(st_b.stitched_approx);
        assert_eq!(st_b.sealed.len(), 20, "post-stitch blocks must NEVER enter state.sealed / EntryTree");
        for k in 0..10usize {
            let slot_b = tbl_b.get(BlockKind::Full, BlockIndex::new((20 + k) as u32)).unwrap().unwrap().slot();
            assert_eq!(slot_b, a_slots[18 + k], "aligned stitch block {k} must zero-copy share source Full slot");
        }
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);
        assert!(!st_b.stitched_approx, "release_lane must reset stitched_approx");

        // 2. Unaligned shift (+19 tokens) + unique 2,817-token (>= MIN_STITCH_TOKENS) post-file tail:
        //    Verify stitched_approx prevents ANY post-stitch block or checkpoint from entering EntryTree / starts / stitch_index!
        let unique_post_stitch_tail: Vec<u32> = (0..2817u32).map(|i| 60_000 + i).collect();
        let mut prompt_c: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
        prompt_c.extend_from_slice(&file_span); // [147 .. 3347)
        prompt_c.extend_from_slice(&unique_post_stitch_tail); // total 6164 -> crosses EVERY at 2048/4096 and PROMPT at 6144!
        let plans_c = cache.plan_stitches(&pools, 0, &prompt_c, 0);
        assert_eq!(plans_c.len(), 1);
        assert_eq!(plans_c[0].span_start, 147);
        assert_eq!(plans_c[0].stitch_start, 1216);
        assert_eq!(plans_c[0].heal_start, 1792);
        assert_eq!(plans_c[0].span_end, 3347);

        let mut tbl_c = BlockTable::new(128).unwrap();
        let mut st_c = LaneBlockState { prompt_len: prompt_c.len(), ..Default::default() };
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 1216).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 0, 1216, || fake_cs(0x31));
        let starts_before = cache.stats().start_points_saved;
        let tree_before = cache.tree.entries().len();
        let stitch_buckets_before = cache.stitch_index.len();
        let cached_total_before = cache.stats().cached_tokens_total;

        let out_c = cache.apply_stitch_plan(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, &plans_c[0]);
        assert_eq!(out_c, StitchApplyOutcome::Applied { stitched_tokens: 576, zero_copy_blocks: 0 });
        assert!(st_c.stitched_approx);
        assert_eq!(st_c.written, 1792);
        assert_eq!(cache.stats().cached_tokens_total, cached_total_before, "stitches must not inflate cached_tokens_total");

        for b in 19..28usize {
            let fe = tbl_c.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
            assert_test_full_block_rows_match(
                pools.full.slot_bytes(fe.slot()).unwrap(),
                &prompt_c[b * BLOCK..(b + 1) * BLOCK],
                kvb,
            );
        }
        for b in 0..12u32 {
            assert!(tbl_c.get(BlockKind::Window, BlockIndex::new(b)).unwrap().is_none(), "expired win {b} pruned");
        }
        for b in 12..28u32 {
            assert!(tbl_c.get(BlockKind::Window, BlockIndex::new(b)).unwrap().is_some(), "healing win {b} present");
        }

        // Prefill the rest of prompt_c across EVERY (2048, 4096) and PROMPT (6144): ZERO EntryTree nodes, ZERO starts, ZERO stitch_index!
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 1792, 2048 - 1792).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 1792, 2048 - 1792, || fake_cs(0x32));
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 2048, 4096 - 2048).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 2048, 4096 - 2048, || fake_cs(0x33));
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 4096, 6144 - 4096).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 4096, 6144 - 4096, || fake_cs(0x34));
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 6144, 6164 - 6144).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 6144, 6164 - 6144, || fake_cs(0x35));

        assert_eq!(cache.stats().start_points_saved, starts_before, "stitched lane must save zero RetainedStarts");
        assert_eq!(cache.tree.entries().len(), tree_before, "stitched lane must insert zero post-stitch EntryTree nodes");
        assert_eq!(cache.stitch_index.len(), stitch_buckets_before, "stitched lane must never index approximate blocks");
        cache.release_lane(&mut pools, &mut tbl_c, &mut st_c);

        // 3. Subsequent exact non-stitching request with identical `prompt_c` prefix gets ZERO approximate cache match
        //    and dedups onto ZERO post-stitch blocks (`shared_dedups` only from pre-stitch blocks if any)!
        cache.set_kv_stitch(false);
        let mut tbl_exact = BlockTable::new(128).unwrap();
        let mut st_exact = LaneBlockState::default();
        assert_eq!(
            cache.match_and_bind(&mut pools, &mut tbl_exact, &mut st_exact, &prompt_c),
            None,
            "exact request must never match a checkpoint from a prior stitched lane"
        );
        let dedups_before = cache.stats().shared_dedups;
        cache.ensure_span_blocks(&mut pools, &mut tbl_exact, 0, 1408).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_exact, &mut st_exact, &prompt_c, 0, 1408, || fake_cs(0x55));
        assert_eq!(
            cache.stats().shared_dedups,
            dedups_before,
            "exact request must compute fresh blocks rather than deduping onto prior stitched blocks"
        );
        cache.release_lane(&mut pools, &mut tbl_exact, &mut st_exact);

        // 4. Re-enable kv_stitch and prove NoChainedStitch: `unique_post_stitch_tail` from `prompt_c` cannot be stitched!
        cache.set_kv_stitch(true);
        let mut chain_probe: Vec<u32> = (0..128u32).map(|i| 95_000 + i).collect();
        chain_probe.extend_from_slice(&unique_post_stitch_tail);
        chain_probe.extend((0..128u32).map(|i| 98_000 + i));
        assert!(
            cache.plan_stitches(&pools, 0, &chain_probe, 0).is_empty(),
            "stitches must never chain onto spans seen only in a stitched lane"
        );

        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn kv_stitch_plans_and_applies_multiple_spans_in_single_prompt() {
        let kvb = 1u32;
        let mut pools = BlockPools::with_capacities(320, 96, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);

        // Retain two independent exact donor files (`file_1` and `file_2`, 2,944 tokens = 46 blocks each).
        let file_1: Vec<u32> = (0..2944u32).map(|i| 110_000 + i).collect();
        let file_2: Vec<u32> = (0..2944u32).map(|i| 210_000 + i).collect();

        for (tag, file_toks) in [(0x11u8, &file_1), (0x22u8, &file_2)] {
            let mut donor: Vec<u32> = (0..128u32).map(|i| u32::from(tag) * 1000 + i).collect();
            donor.extend_from_slice(file_toks);
            donor.push(777_777); // total 3073 -> exact PROMPT checkpoint at 3072
            let mut tbl = BlockTable::new(128).unwrap();
            let mut st = LaneBlockState { prompt_len: donor.len(), ..Default::default() };
            for b in 0..48usize {
                let p0 = b * BLOCK;
                cache.ensure_span_blocks(&mut pools, &mut tbl, p0, BLOCK).unwrap();
                let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                stamp_test_full_block_rows(pools.full.slot_bytes_mut(fe.slot()).unwrap(), &donor[p0..p0 + BLOCK], kvb);
                cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &donor, p0, BLOCK, || fake_cs(tag));
            }
            cache.ensure_span_blocks(&mut pools, &mut tbl, 3072, 1).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &donor, 3072, 1, || fake_cs(tag));
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }

        // Combined prompt: 128-tok header (aligned!) + file_1 + 151-tok bridge (+23 mod 64 unaligned!) + file_2 + 128-tok question.
        let mut combined: Vec<u32> = (0..128u32).map(|i| 310_000 + i).collect();
        combined.extend_from_slice(&file_1); // [128 .. 3072)
        combined.extend((0..151u32).map(|i| 320_000 + i)); // [3072 .. 3223)
        combined.extend_from_slice(&file_2); // [3223 .. 6167)
        combined.extend((0..128u32).map(|i| 330_000 + i));

        let plans = cache.plan_stitches(&pools, 0, &combined, 0);
        assert_eq!(plans.len(), 2, "must plan 2 non-overlapping stitch spans in a single prompt");
        assert!(plans[0].span_end <= plans[1].stitch_start, "stitch spans must not overlap");
        for p in &plans {
            assert!(
                p.stitch_start - p.span_start >= LEFT_HEAL_TOKENS,
                "each span must reserve >= 1024 left-healing tokens"
            );
            assert!(
                p.span_end - p.heal_start >= MIN_HEAL_TOKENS,
                "each span must reserve >= 1536 right-healing tokens"
            );
        }

        let mut tbl = BlockTable::new(128).unwrap();
        let mut st = LaneBlockState { prompt_len: combined.len(), ..Default::default() };
        let mut cur = 0usize;
        for (idx, plan) in plans.iter().enumerate() {
            if cur < plan.stitch_start {
                cache.ensure_span_blocks(&mut pools, &mut tbl, cur, plan.stitch_start - cur).unwrap();
                cache.finish_prefill_span(
                    &mut pools,
                    &mut tbl,
                    &mut st,
                    &combined,
                    cur,
                    plan.stitch_start - cur,
                    || fake_cs(0x60 + idx as u8),
                );
            }
            let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &combined, plan);
            match (idx, out) {
                (0, StitchApplyOutcome::Applied { zero_copy_blocks, .. }) => assert!(zero_copy_blocks > 0),
                (1, StitchApplyOutcome::Applied { zero_copy_blocks: 0, .. }) => {}
                other => panic!("unexpected multi-span stitch outcome: {other:?}"),
            }
            for b in (plan.stitch_start / BLOCK)..(plan.heal_start / BLOCK) {
                let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                assert_test_full_block_rows_match(
                    pools.full.slot_bytes(fe.slot()).unwrap(),
                    &combined[b * BLOCK..(b + 1) * BLOCK],
                    kvb,
                );
            }
            cur = plan.heal_start;
        }
        cache.ensure_span_blocks(&mut pools, &mut tbl, cur, combined.len() - cur).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &combined, cur, combined.len() - cur, || fake_cs(0x77));
        assert_eq!(cache.stats().stitch_hits, 2);

        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn kv_stitch_enforces_strict_namespace_isolation_and_eviction_cleanup() {
        let mut pools = BlockPools::with_capacities(192, 64, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);

        let shared_file: Vec<u32> = (0..3072u32).map(|i| 30_000 + i).collect();
        let mut tenant_a_prompt: Vec<u32> = (0..128u32).map(|i| 500 + i).collect();
        tenant_a_prompt.extend_from_slice(&shared_file);
        tenant_a_prompt.extend((0..129u32).map(|i| 70_000 + i)); // 3329 tokens -> PROMPT start at 3328

        let mut tbl_a = BlockTable::new(96).unwrap();
        let mut st_a = LaneBlockState { namespace: 0xAAAA, prompt_len: tenant_a_prompt.len(), ..Default::default() };
        let _ = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_a, &mut st_a, 0xAAAA, &tenant_a_prompt);
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 3328).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &tenant_a_prompt, 0, 3328, || fake_cs(0xAA));
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 3328, 1).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &tenant_a_prompt, 3328, 1, || fake_cs(0xAB));
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

        // Shifted prompt (+19 tokens) with identical 3,072-token file body.
        let mut shifted_prompt: Vec<u32> = (0..147u32).map(|i| 9_000 + i).collect();
        shifted_prompt.extend_from_slice(&shared_file);
        shifted_prompt.extend((0..129u32).map(|i| 80_000 + i));

        // Tenant B (0xBBBB) and default namespace (0) MUST NEVER plan or apply Tenant A's spans!
        assert!(
            cache.plan_stitches(&pools, 0xBBBB, &shifted_prompt, 0).is_empty(),
            "Tenant B must never see Tenant A's stitch index entries"
        );
        assert!(
            cache.plan_stitches(&pools, 0, &shifted_prompt, 0).is_empty(),
            "Default namespace must never see Tenant A's stitch index entries"
        );

        let plans_a = cache.plan_stitches(&pools, 0xAAAA, &shifted_prompt, 0);
        assert_eq!(plans_a.len(), 1, "Same tenant 0xAAAA must match shifted file span");

        // Even if a forged StitchSpanPlan from Tenant A is handed to Tenant B's lane, apply_stitch_plan rejects it!
        let mut tbl_b = BlockTable::new(96).unwrap();
        let mut st_b = LaneBlockState { namespace: 0xBBBB, prompt_len: shifted_prompt.len(), ..Default::default() };
        cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, plans_a[0].stitch_start).unwrap();
        cache.finish_prefill_span(
            &mut pools,
            &mut tbl_b,
            &mut st_b,
            &shifted_prompt,
            0,
            plans_a[0].stitch_start,
            || fake_cs(0xBB),
        );
        assert_eq!(
            cache.apply_stitch_plan(&mut pools, &mut tbl_b, &mut st_b, &shifted_prompt, &plans_a[0]),
            StitchApplyOutcome::SourceGone,
            "cross-namespace stitch plan application must fail closed"
        );
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);

        // Evict Tenant A's RetainedStart and verify stitch_index drains to 0 entries and 0 leaks.
        cache.shutdown(&mut pools);
        assert!(cache.stitch_index.is_empty(), "evicting all starts must remove all stitch_index entries");
        assert!(cache.plan_stitches(&pools, 0xAAAA, &shifted_prompt, 0).is_empty());
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn ikv_catalog_async_staging_and_corrupt_page_quarantine_preserve_invariants() {
        use std::io::{Seek, SeekFrom, Write};
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;

        let dir = ScratchDir::new("ikv-block-cache");
        #[cfg(unix)]
        std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();

        let kvb = 1u32;
        let vocab = 262_144u32;
        let model_fp = 0xfeed_face_cafe_beefu64;
        let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"block-cache-test-hmac-key-32byte").unwrap();
        let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;

        // Build a 3,200-token (50-page) synthetic .ikv cartridge with deterministic per-token K/V rows.
        let cart_toks: Vec<u32> = (0..3200u32).map(|i| 120_000 + i).collect();
        let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(50);
        for p in 0..50usize {
            let mut page = vec![0u8; page_bytes];
            stamp_test_full_block_rows(&mut page, &cart_toks[p * BLOCK..(p + 1) * BLOCK], kvb);
            full_pages.push(page);
        }
        let ikv_path = dir.0.join("sample.ikv");
        let hdr = crate::ikv::write_ikv_cartridge_raw(
            &ikv_path,
            "src/sample.rs",
            kvb,
            vocab,
            model_fp,
            false,
            16,
            &cart_toks,
            &full_pages,
            Some(&hmac_key),
        )
        .unwrap();

        let cat = Arc::new(
            crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
        );
        assert_eq!(cat.len(), 1);

        let mut pools = BlockPools::with_capacities(192, 64, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_ikv_catalog(cat);
        assert_eq!(cache.stats().ikv_cartridges_loaded, 1);
        assert_eq!(cache.stats().ikv_quarantined, 0);

        // Prompt has an unaligned 83-token prefix (83 % 64 == 19) + 3,200-token file + 128-token question.
        let mut prompt: Vec<u32> = (0..83u32).map(|i| 4_000 + i).collect();
        prompt.extend_from_slice(&cart_toks);
        prompt.extend((0..128u32).map(|i| 90_000 + i));

        // Non-zero isolated namespace must NOT stitch from fleet .ikv catalog.
        assert!(cache.plan_stitches(&pools, 7, &prompt, 0).is_empty());

        // 1. Background non-blocking `start_stitch_plan` -> `Staging` -> `poll_ikv_stages`!
        let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].span_start, 83);
        assert_eq!(plans[0].stitch_start, 1152);
        assert_eq!(plans[0].heal_start, 1728);
        assert_eq!(plans[0].span_end, 3283);

        let mut tbl = BlockTable::new(96).unwrap();
        let mut st = LaneBlockState { namespace: 0, prompt_len: prompt.len(), ..Default::default() };
        let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 1152).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 1152, || fake_cs(1));
        assert_eq!(
            cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
            StitchStartOutcome::Staging
        );
        assert!(cache.has_pending_ikv_stage(0) && cache.has_inflight_restores());
        let done = loop {
            let tbl_ptr: *mut BlockTable = &mut tbl;
            let st_ptr: *mut LaneBlockState = &mut st;
            let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 0).then_some((&(), tbl_ptr, st_ptr)));
            if let Some(c) = batch.pop() {
                break c;
            }
            cache.wait_restore_activity(Duration::from_millis(50));
        };
        assert_eq!(done.stitched_tokens, Some(576));
        assert!(!done.corrupt_fallback);
        assert!(st.stitched_approx);
        assert_eq!(st.written, 1728);
        for b in 18..27usize {
            let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
            assert_test_full_block_rows_match(
                pools.full.slot_bytes(fe.slot()).unwrap(),
                &prompt[b * BLOCK..(b + 1) * BLOCK],
                kvb,
            );
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        // 2. Plant a 1-byte bit-flip inside page 20 on disk while mounted (inside read range pages 16..=25):
        //    background staging detects the SHA-256 mismatch, quarantines the cartridge (`ikv_quarantined == 1`),
        //    rolls back all reserved slots with zero leaks, AND subsequent `plan_stitches` never retries it!
        {
            let mut f = std::fs::OpenOptions::new().read(true).write(true).open(&ikv_path).unwrap();
            f.seek(SeekFrom::Start(hdr.full_pages_off + 20 * (page_bytes as u64) + 333)).unwrap();
            f.write_all(&[0xFF]).unwrap();
            f.sync_all().unwrap();
        }
        let mut tbl2 = BlockTable::new(96).unwrap();
        let mut st2 = LaneBlockState { namespace: 0, prompt_len: prompt.len(), ..Default::default() };
        let _ = cache.begin_admit_bind(&mut pools, 1, &mut tbl2, &mut st2, &prompt);
        cache.ensure_span_blocks(&mut pools, &mut tbl2, 0, 1152).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &prompt, 0, 1152, || fake_cs(2));
        assert_eq!(
            cache.start_stitch_plan(&mut pools, 1, &mut tbl2, &mut st2, &prompt, &plans[0]),
            StitchStartOutcome::Staging
        );
        let aborted = loop {
            let tbl_ptr: *mut BlockTable = &mut tbl2;
            let st_ptr: *mut LaneBlockState = &mut st2;
            let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 1).then_some((&(), tbl_ptr, st_ptr)));
            if let Some(c) = batch.pop() {
                break c;
            }
            cache.wait_restore_activity(Duration::from_millis(50));
        };
        assert!(aborted.corrupt_fallback && aborted.stitched_tokens.is_none());
        assert_eq!(cache.stats().corrupt_fallbacks, 1);
        assert_eq!(cache.stats().ikv_quarantined, 1, "corrupt runtime page must quarantine cartridge");
        assert_eq!(st2.written, 1152, "lane cursor must remain at stitch_start for clean fallback prefill");
        assert!(tbl2.get(BlockKind::Full, BlockIndex::new(18)).unwrap().is_none(), "staged slots must be rolled back");

        // Subsequent requests skip the quarantined cartridge immediately in `plan_stitches` and `apply_stitch_plan`!
        assert!(
            cache.plan_stitches(&pools, 0, &prompt, 0).is_empty(),
            "quarantined .ikv cartridge must never be planned again"
        );
        assert_eq!(
            cache.apply_stitch_plan(&mut pools, &mut tbl2, &mut st2, &prompt, &plans[0]),
            StitchApplyOutcome::SourceGone
        );

        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn kv_stitch_revisits_same_diagonal_past_single_token_edit_for_retained_and_ikv() {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;

        let kvb = 1u32;
        let vocab = 262_144u32;
        let model_fp = 0xabcd_ef01_2345_6789u64;
        let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"diag-edit-test-hmac-key-32-bytes").unwrap();
        let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;

        // Original 3,584-token (56-block) file:
        // [0..64) matching header + token [64] (will be edited in query!) + [65..3584) 3,519-token identical suffix!
        let orig_file: Vec<u32> = (0..3584u32).map(|i| 150_000 + i).collect();
        let mut edited_file = orig_file.clone();
        edited_file[64] = 999_999; // 1-token in-place edit -> suffix [65..3584) stays on the EXACT SAME diagonal!

        // Shifted query prompt (+19 unaligned header):
        let mut query_prompt: Vec<u32> = (0..83u32).map(|i| 7_000 + i).collect();
        query_prompt.extend_from_slice(&edited_file); // [83..147) matches [0..64), [147] edited, [148..3667) matches [65..3584)!
        query_prompt.extend((0..128u32).map(|i| 8_000 + i));

        // Case A: `RetainedStart` donor with `orig_file`!
        {
            let mut pools = BlockPools::with_capacities(224, 64, kvb).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_kv_stitch(true);

            let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 5_000 + i).collect();
            donor_prompt.extend_from_slice(&orig_file);
            donor_prompt.push(555_555); // total 3,713 -> exact PROMPT start saved at 3,712 (58 blocks)

            let mut tbl_d = BlockTable::new(96).unwrap();
            let mut st_d = LaneBlockState { prompt_len: donor_prompt.len(), ..Default::default() };
            for b in 0..58usize {
                let p0 = b * BLOCK;
                cache.ensure_span_blocks(&mut pools, &mut tbl_d, p0, BLOCK).unwrap();
                let fe = tbl_d.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                stamp_test_full_block_rows(
                    pools.full.slot_bytes_mut(fe.slot()).unwrap(),
                    &donor_prompt[p0..p0 + BLOCK],
                    kvb,
                );
                cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, p0, BLOCK, || fake_cs(0x44));
            }
            cache.ensure_span_blocks(&mut pools, &mut tbl_d, 3712, 1).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, 3712, 1, || fake_cs(0x45));
            cache.release_lane(&mut pools, &mut tbl_d, &mut st_d);

            let ret_plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
            assert_eq!(
                ret_plans.len(),
                1,
                "RetainedStart planner must revisit same diagonal past 1-token edit and stitch the 3,519-token suffix"
            );
            // Suffix starts at query_prompt[148] -> stitch_start = ceil((148+1024)/64)*64 = 1216; span_end = 3667 -> heal_start = ((3667-1536)/64)*64 = 2112!
            assert_eq!(ret_plans[0].span_start, 148);
            assert_eq!(ret_plans[0].stitch_start, 1216);
            assert_eq!(ret_plans[0].heal_start, 2112);
            assert_eq!(ret_plans[0].span_end, 3667);

            let mut tbl_q = BlockTable::new(96).unwrap();
            let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
            cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, 1216).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, 1216, || fake_cs(0x46));
            let out = cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &ret_plans[0]);
            assert_eq!(out, StitchApplyOutcome::Applied { stitched_tokens: 896, zero_copy_blocks: 0 });
            for b in 19..33usize {
                let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                assert_test_full_block_rows_match(
                    pools.full.slot_bytes(fe.slot()).unwrap(),
                    &query_prompt[b * BLOCK..(b + 1) * BLOCK],
                    kvb,
                );
            }
            cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // Case B: `MountedIkv` donor with `orig_file`!
        {
            let dir = ScratchDir::new("ikv-diag-edit");
            #[cfg(unix)]
            std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();

            let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(56);
            for p in 0..56usize {
                let mut page = vec![0u8; page_bytes];
                stamp_test_full_block_rows(&mut page, &orig_file[p * BLOCK..(p + 1) * BLOCK], kvb);
                full_pages.push(page);
            }
            let ikv_path = dir.0.join("orig.ikv");
            crate::ikv::write_ikv_cartridge_raw(
                &ikv_path,
                "src/orig.rs",
                kvb,
                vocab,
                model_fp,
                false,
                16,
                &orig_file,
                &full_pages,
                Some(&hmac_key),
            )
            .unwrap();
            let cat = Arc::new(
                crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
            );

            let mut pools = BlockPools::with_capacities(224, 64, kvb).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_kv_stitch(true);
            cache.set_ikv_catalog(cat);

            let ikv_plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
            assert_eq!(
                ikv_plans.len(),
                1,
                "MountedIkv planner must revisit same diagonal past 1-token edit and stitch the 3,519-token suffix"
            );
            assert_eq!(ikv_plans[0].span_start, 148);
            assert_eq!(ikv_plans[0].stitch_start, 1216);
            assert_eq!(ikv_plans[0].heal_start, 2112);
            assert_eq!(ikv_plans[0].span_end, 3667);

            let mut tbl_q = BlockTable::new(96).unwrap();
            let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
            cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, 1216).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, 1216, || fake_cs(0x47));
            let out = cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &ikv_plans[0]);
            assert_eq!(out, StitchApplyOutcome::Applied { stitched_tokens: 896, zero_copy_blocks: 0 });
            for b in 19..33usize {
                let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                assert_test_full_block_rows_match(
                    pools.full.slot_bytes(fe.slot()).unwrap(),
                    &query_prompt[b * BLOCK..(b + 1) * BLOCK],
                    kvb,
                );
            }
            cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    #[test]
    fn kv4_and_sparse_topk_stitch_recomputes_wht2_sketches_for_retained_and_ikv() {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;
        use crate::blocks::{KvMode, FULL_SKETCH_BYTES, KVB_KV4};

        let kvb = KVB_KV4;
        let vocab = 262_144u32;
        let kv4_digest_tag = 0x5152_5354_5556_5758u64;
        let model_fp = 0xabcd_ef01_2345_6789u64 ^ kv4_digest_tag;
        let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"kv4-sparse-stitch-hmac-key-32byt").unwrap();
        let page_bytes = KvMode::Kv4.stride_bytes(BlockKind::Full) as usize;

        let shared_file: Vec<u32> = (0..3200u32).map(|i| 160_000 + i).collect();
        let mut query_prompt: Vec<u32> = (0..83u32).map(|i| 7_500 + i).collect(); // +19 unaligned shift!
        query_prompt.extend_from_slice(&shared_file);
        query_prompt.extend((0..128u32).map(|i| 8_500 + i));

        // 1. Unaligned `RetainedStart` KV4 stitch with `has_sketches = true` recomputes exact 17,408B WHT-2bit sketches!
        {
            let mut pools = BlockPools::with_capacities_mode_and_sketches(160, 48, KvMode::Kv4, true).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_kv_stitch(true);

            let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 4_200 + i).collect();
            donor_prompt.extend_from_slice(&shared_file);
            donor_prompt.push(555_555);

            let mut tbl_d = BlockTable::new(96).unwrap();
            let mut st_d = LaneBlockState { prompt_len: donor_prompt.len(), ..Default::default() };
            let full_blks = (donor_prompt.len() - 1) / BLOCK;
            for b in 0..full_blks {
                let p0 = b * BLOCK;
                cache.ensure_span_blocks(&mut pools, &mut tbl_d, p0, BLOCK).unwrap();
                let fe = tbl_d.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                stamp_test_full_block_rows(
                    pools.full.slot_bytes_mut(fe.slot()).unwrap(),
                    &donor_prompt[p0..p0 + BLOCK],
                    kvb,
                );
                pools.full.on_slot_restored_from_spill(fe.slot());
                cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, p0, BLOCK, || fake_cs(b as u8));
            }
            cache.release_lane(&mut pools, &mut tbl_d, &mut st_d);

            let plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
            assert_eq!(plans.len(), 1);
            let mut tbl_q = BlockTable::new(96).unwrap();
            let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
            let p0_end = plans[0].stitch_start;
            cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, p0_end).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, p0_end, || fake_cs(1));
            assert!(matches!(
                cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &plans[0]),
                StitchApplyOutcome::Applied { zero_copy_blocks: 0, .. }
            ));

            let lo_b = plans[0].stitch_start / BLOCK;
            let hi_b = plans[0].heal_start / BLOCK;
            for b in lo_b..hi_b {
                let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
                assert_test_full_block_rows_match(
                    pools.full.slot_bytes(fe.slot()).unwrap(),
                    &query_prompt[b * BLOCK..(b + 1) * BLOCK],
                    kvb,
                );
                assert_eq!(pools.full.slot_sketch_valid_len(fe.slot()).unwrap(), BLOCK as u8);
                let mut exp_sk = vec![0u8; FULL_SKETCH_BYTES];
                crate::blocks::compute_full_slot_wht2_sketch_cpu(
                    pools.full.slot_bytes(fe.slot()).unwrap(),
                    kvb,
                    BLOCK,
                    &mut exp_sk,
                );
                assert_eq!(pools.full.slot_sketch_bytes(fe.slot()).unwrap(), exp_sk.as_slice());
            }
            cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // 2. `.ikv` `kvb=66` (`Kv4`) cartridge stitches + recomputes WHT-2bit sketches, while rejecting `kvb=1` or wrong digest!
        let dir = ScratchDir::new("kv4-sparse-ikv-stitch");
        #[cfg(unix)]
        std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
        let n_pages = shared_file.len().div_ceil(BLOCK);
        let mut pages = Vec::with_capacity(n_pages);
        for p in 0..n_pages {
            let mut page = vec![0u8; page_bytes];
            stamp_test_full_block_rows(&mut page, &shared_file[p * BLOCK..(p + 1) * BLOCK], kvb);
            pages.push(page);
        }
        let ikv_path = dir.0.join("shared_kv4.ikv");
        crate::ikv::write_ikv_cartridge_raw(
            &ikv_path,
            "shared_kv4.rs",
            kvb,
            vocab,
            model_fp,
            false,
            16,
            &shared_file,
            &pages,
            Some(&hmac_key),
        )
        .unwrap();

        // KV8 server (`kvb=1`) refuses KV4 `.ikv` (`kvb=66`), and wrong `kv4_digest` (`model_fp ^ 1`) fails closed!
        assert!(
            crate::ikv::IkvCatalog::load_dir(&dir.0, 1, vocab, model_fp, false, &hmac_key)
                .unwrap_err()
                .contains("rule kvb_match")
        );
        assert!(
            crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp ^ 1, false, &hmac_key)
                .unwrap_err()
                .contains("rule model_fingerprint")
        );

        let cat = std::sync::Arc::new(
            crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
        );
        let mut pools = BlockPools::with_capacities_mode_and_sketches(160, 48, KvMode::Kv4, true).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_ikv_catalog(cat);

        let plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
        assert_eq!(plans.len(), 1);
        let mut tbl_q = BlockTable::new(96).unwrap();
        let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
        let p0_end = plans[0].stitch_start;
        cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, p0_end).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, p0_end, || fake_cs(2));
        assert!(matches!(
            cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &plans[0]),
            StitchApplyOutcome::Applied { .. }
        ));
        let lo_b = plans[0].stitch_start / BLOCK;
        let hi_b = plans[0].heal_start / BLOCK;
        for b in lo_b..hi_b {
            let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
            assert_eq!(pools.full.slot_sketch_valid_len(fe.slot()).unwrap(), BLOCK as u8);
            let mut exp_sk = vec![0u8; FULL_SKETCH_BYTES];
            crate::blocks::compute_full_slot_wht2_sketch_cpu(
                pools.full.slot_bytes(fe.slot()).unwrap(),
                kvb,
                BLOCK,
                &mut exp_sk,
            );
            assert_eq!(pools.full.slot_sketch_bytes(fe.slot()).unwrap(), exp_sk.as_slice());
        }
        cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }
}

#[cfg(test)]
mod admission_tests;