inky-engine 3.0.3

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
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
//! 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`)
//! - Eviction of retained start points by demonstrated reuse per byte on pool and host pressure, under the
//!   card lease (never grows or panics; `INK_RETAIN_LRU=1` restores plain LRU)
//! - Pool-pressure admission guard keeping GPU memory bounded inside Metal working set

use crate::blockbook::PROMPT;
#[cfg(test)]
use crate::blockbook::EVERY;
use crate::blocks::{BlockEntry, BlockIndex, BlockKind, BlockPool, BlockPools, BlockTable, Slot, VerifyBlockFinalize, BLOCK, FULL_PASSES, NKV, WINDOW};
use crate::engine::EXT;
use crate::prefix::{BlockHandles, EntryTree, PrefixTree, SealedId};
use crate::spill::{
    read_block_from_dir, unlink_block_in_dir, RawDiskRead, RawDiskWrite, ReadOutcome, Sha256, SpillBlockKind,
    SpillBytes, SpillIo, SpillIoDone, SpillKey, SpillStore, SpillWriter,
};
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];

/// The checkpoint arithmetic, a child of the cache so the standalone cache trace builds carry it (`checkpoint.rs` beside
/// this file); serve and the trace gate reach it through these re-exports.
#[path = "checkpoint.rs"]
pub mod checkpoint;
pub use checkpoint::{
    effective_pf_target, finish_parts, is_every_checkpoint, span_checkpoints, start_reasons, step_pf_target, StateAt,
    EARLY_EVERY_LIMIT, EARLY_EVERY_TOKENS, LATE_EVERY_TOKENS,
};

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

#[cfg(test)]
thread_local! {
    /// Test seam: the decode reserve on this thread, so a scheduler test reaches the end of a lane's
    /// reservation in tens of steps instead of 4,096 (`None`: `MAX_ADMIT_DECODE_RESERVE`).
    pub(crate) static TEST_ADMIT_DECODE_RESERVE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}

fn admit_decode_reserve() -> usize {
    #[cfg(test)]
    if let Some(reserve) = TEST_ADMIT_DECODE_RESERVE.with(|r| r.get()) {
        return reserve;
    }
    MAX_ADMIT_DECODE_RESERVE
}

/// 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 cap on live approximate starts per auth scope: generous (32 lanes saving a few per turn for hundreds
/// of turns), and only there so one scope cannot crowd out the rest.
pub const DEFAULT_MAX_APPROX_STARTS_PER_SCOPE: usize = 2048;

/// 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). With the spill writer
/// thread it runs from the moment the checkpoint is queued, and bounds how long a spill can hold its blocks.
pub const DEFAULT_SPILL_WRITE_TIMEOUT: Duration = Duration::from_secs(30);

/// Default cap on the bytes of spill writes queued for the spill writer thread and not yet on disk. Those
/// blocks stay allocated until their write lands, so this is also the most pool memory spills can hold back at
/// once. A checkpoint that does not fit is dropped unspilled and counted, never waited for. Not measured: 2 GiB
/// is one 123K-token `--kv8` checkpoint, and about what the old synchronous spill could write inside its 30 s
/// deadline. `serve` lowers it to a sixteenth of the `Full` pool on a small pool.
pub const DEFAULT_SPILL_WRITE_QUEUE_BYTES: u64 = 2 << 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,
    /// Start points saved by approximate lanes into their namespace twin (`approx_namespace`).
    pub approx_starts_saved: u64,
    /// Admissions bound to an approximate start: a returning turn resumed from its own saved work.
    pub approx_start_matches: u64,
    /// Tokens those approximate starts covered (kept apart from the exact `cached_tokens_total`).
    pub approx_cached_tokens_total: u64,
    pub evictions_pool_pressure: u64,
    pub evictions_host_budget: u64,
    pub evictions_approx_scope_cap: u64,
    pub evictions_stale_invalid: u64,
    pub evictions_shutdown: u64,
    /// Earlier-turn approximate starts released when their conversation's next turn completed
    /// ([`ServeBlockCache::release_superseded_turn_starts`]): frees Window slots, loses no K/V.
    pub evictions_superseded: u64,
    /// Evictions whose victim the reuse-per-byte ranking chose where plain LRU would have kept it (the start
    /// LRU would have evicted first stayed resident): the proof the ranking decided an eviction. Zero under
    /// `INK_RETAIN_LRU=1`.
    pub evictions_ranked_over_lru: u64,
    /// The cache activity clock reuse credit ages on (`REUSE_EPOCH_TICKS` per epoch): binds and saves, never
    /// wall time. Its rate at width gives the creation grace's length in seconds.
    pub activity_ticks: u64,
    /// Released turns that left a start at their reply's last block boundary ([`TurnEndStart::Saved`]).
    pub turn_end_starts_saved: u64,
    /// Released turns that did not ([`TurnEndStart::NotSaved`]), by [`TurnEndMiss`] in `TurnEndMiss::ALL` order.
    pub turn_end_starts_not_saved: [u64; TurnEndMiss::ALL.len()],
    pub restores_failed: u64,
    pub spill_reads_hit: u64,
    pub spill_reads_miss: u64,
    pub spill_bytes_read: u64,
    pub spill_read_us_total: u64,
    /// Block and recurrent-state writes handed to the spill writer.
    pub spill_writes_queued: u64,
    /// Writes never handed over because the spill write queue was full; their start was dropped unspilled.
    pub spill_writes_dropped_queue_full: u64,
    /// Writes handed over and neither landed nor cancelled yet (a gauge), and their bytes.
    pub spill_writes_pending: u64,
    pub spill_write_bytes_pending: u64,
    /// Starts evicted for spilling that never reached disk, whatever the cause: queue full, disk budget,
    /// deadline, write error, shutdown, or nothing spillable. `starts_spilled` counts the ones that did.
    pub spill_starts_dropped: u64,
    /// Starts whose spill is queued or being written (a gauge).
    pub spill_starts_pending: u64,
    /// Spill disk operations that failed on the writer: a block write, an unlink, an index write.
    pub spill_io_errors: u64,
    /// Time the scheduler thread spent evicting start points: the sum, and the longest single eviction.
    pub evict_us_total: u64,
    pub evict_us_max: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EvictCause {
    PoolPressure,
    HostBudget,
    ApproxScopeCap,
    StaleInvalid,
    Shutdown,
    Superseded,
}

pub const MAX_OWNER_PRIOR_ENTRIES: usize = 8_192;

#[derive(Clone, Debug)]
struct OwnerPriorTurn {
    seq: u64,
    prompt_saved_pos: usize,
    prompt_len: usize,
    reply_saved_pos: usize,
    total_len: usize,
    prompt_tip_id: Option<SealedId>,
    reply_tip_id: Option<SealedId>,
    tip_id: Option<SealedId>,
    spilled_tip_id: Option<SealedId>,
    spilled_prompt_tip_id: Option<SealedId>,
    tail_toks: Vec<u32>,
    truncated_tail: bool,
    evicted: bool,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ObservedPrior {
    pub has_prior: bool,
    pub prompt_saved_pos: usize,
    pub prompt_len: usize,
    pub reply_saved_pos: usize,
    pub total_len: usize,
    pub prompt_tip_id: Option<SealedId>,
    pub reply_tip_id: Option<SealedId>,
    pub proven_common_len: usize,
    pub evicted: bool,
    pub any_saved_start_missing: bool,
    pub first_divergent_pos: Option<usize>,
}

/// Numbers-only point-in-time occupancy and cumulative eviction/spill/restore telemetry.
#[cfg(test)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheMemorySnapshot {
    pub window_slots_used: usize,
    pub window_slots_capacity: usize,
    pub window_slots_bytes_used: u64,
    pub window_slots_bytes_capacity: u64,
    pub full_slots_used: usize,
    pub full_slots_capacity: usize,
    pub full_slots_bytes_used: u64,
    pub full_slots_bytes_capacity: u64,
    pub retained_host_bytes: u64,
    pub retained_host_budget_bytes: u64,
    pub retained_starts: usize,
    pub approx_retained_starts: usize,
    pub spilled_starts: usize,
    pub evictions_pool_pressure: u64,
    pub evictions_host_budget: u64,
    pub evictions_approx_scope_cap: u64,
    pub evictions_stale_invalid: u64,
    pub evictions_shutdown: u64,
    pub evictions_superseded: u64,
    pub starts_spilled: u64,
    pub spill_writes_committed: u64,
    pub spill_bytes_written: u64,
    pub spill_write_us_total: u64,
    pub spill_write_timeouts: u64,
    pub spill_disk_used_bytes: u64,
    pub spill_disk_max_bytes: u64,
    pub spill_disk_gc_evictions: u64,
    pub spill_reads_hit: u64,
    pub spill_reads_miss: u64,
    pub spill_bytes_read: u64,
    pub spill_read_us_total: u64,
    pub starts_restored: u64,
    pub restores_failed: u64,
    pub restore_us_total: u64,
}

/// Numbers-only interval delta between two [`CacheMemorySnapshot`] captures.
#[cfg(test)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheMemoryInterval {
    pub window_slots_used: usize,
    pub window_slots_capacity: usize,
    pub window_slots_bytes_used: u64,
    pub window_slots_bytes_capacity: u64,
    pub full_slots_used: usize,
    pub full_slots_capacity: usize,
    pub full_slots_bytes_used: u64,
    pub full_slots_bytes_capacity: u64,
    pub retained_host_bytes: u64,
    pub retained_host_budget_bytes: u64,
    pub retained_starts: usize,
    pub approx_retained_starts: usize,
    pub spilled_starts: usize,
    pub evictions_pool_pressure: u64,
    pub evictions_host_budget: u64,
    pub evictions_approx_scope_cap: u64,
    pub evictions_stale_invalid: u64,
    pub evictions_shutdown: u64,
    pub evictions_superseded: u64,
    pub starts_spilled: u64,
    pub spill_writes_committed: u64,
    pub spill_bytes_written: u64,
    pub spill_write_us_total: u64,
    pub spill_write_timeouts: u64,
    pub spill_disk_used_bytes: u64,
    pub spill_disk_max_bytes: u64,
    pub spill_disk_gc_evictions: u64,
    pub spill_reads_hit: u64,
    pub spill_reads_miss: u64,
    pub spill_bytes_read: u64,
    pub spill_read_us_total: u64,
    pub starts_restored: u64,
    pub restores_failed: u64,
    pub restore_us_total: u64,
}

#[cfg(test)]
impl CacheMemorySnapshot {
    pub fn delta_since(&self, prev: &Self) -> CacheMemoryInterval {
        CacheMemoryInterval {
            window_slots_used: self.window_slots_used,
            window_slots_capacity: self.window_slots_capacity,
            window_slots_bytes_used: self.window_slots_bytes_used,
            window_slots_bytes_capacity: self.window_slots_bytes_capacity,
            full_slots_used: self.full_slots_used,
            full_slots_capacity: self.full_slots_capacity,
            full_slots_bytes_used: self.full_slots_bytes_used,
            full_slots_bytes_capacity: self.full_slots_bytes_capacity,
            retained_host_bytes: self.retained_host_bytes,
            retained_host_budget_bytes: self.retained_host_budget_bytes,
            retained_starts: self.retained_starts,
            approx_retained_starts: self.approx_retained_starts,
            spilled_starts: self.spilled_starts,
            evictions_pool_pressure: self.evictions_pool_pressure.saturating_sub(prev.evictions_pool_pressure),
            evictions_host_budget: self.evictions_host_budget.saturating_sub(prev.evictions_host_budget),
            evictions_approx_scope_cap: self.evictions_approx_scope_cap.saturating_sub(prev.evictions_approx_scope_cap),
            evictions_stale_invalid: self.evictions_stale_invalid.saturating_sub(prev.evictions_stale_invalid),
            evictions_shutdown: self.evictions_shutdown.saturating_sub(prev.evictions_shutdown),
            evictions_superseded: self.evictions_superseded.saturating_sub(prev.evictions_superseded),
            starts_spilled: self.starts_spilled.saturating_sub(prev.starts_spilled),
            spill_writes_committed: self.spill_writes_committed.saturating_sub(prev.spill_writes_committed),
            spill_bytes_written: self.spill_bytes_written.saturating_sub(prev.spill_bytes_written),
            spill_write_us_total: self.spill_write_us_total.saturating_sub(prev.spill_write_us_total),
            spill_write_timeouts: self.spill_write_timeouts.saturating_sub(prev.spill_write_timeouts),
            spill_disk_used_bytes: self.spill_disk_used_bytes,
            spill_disk_max_bytes: self.spill_disk_max_bytes,
            spill_disk_gc_evictions: self.spill_disk_gc_evictions.saturating_sub(prev.spill_disk_gc_evictions),
            spill_reads_hit: self.spill_reads_hit.saturating_sub(prev.spill_reads_hit),
            spill_reads_miss: self.spill_reads_miss.saturating_sub(prev.spill_reads_miss),
            spill_bytes_read: self.spill_bytes_read.saturating_sub(prev.spill_bytes_read),
            spill_read_us_total: self.spill_read_us_total.saturating_sub(prev.spill_read_us_total),
            starts_restored: self.starts_restored.saturating_sub(prev.starts_restored),
            restores_failed: self.restores_failed.saturating_sub(prev.restores_failed),
            restore_us_total: self.restore_us_total.saturating_sub(prev.restore_us_total),
        }
    }

    #[cfg(not(standalone_blocks))]
    pub fn to_json(self) -> serde_json::Value {
        serde_json::json!({
            "window_slots_used": self.window_slots_used,
            "window_slots_capacity": self.window_slots_capacity,
            "window_slots_bytes_used": self.window_slots_bytes_used,
            "window_slots_bytes_capacity": self.window_slots_bytes_capacity,
            "full_slots_used": self.full_slots_used,
            "full_slots_capacity": self.full_slots_capacity,
            "full_slots_bytes_used": self.full_slots_bytes_used,
            "full_slots_bytes_capacity": self.full_slots_bytes_capacity,
            "retained_host_bytes": self.retained_host_bytes,
            "retained_host_budget_bytes": self.retained_host_budget_bytes,
            "retained_starts": self.retained_starts,
            "approx_retained_starts": self.approx_retained_starts,
            "spilled_starts": self.spilled_starts,
            "evictions_pool_pressure": self.evictions_pool_pressure,
            "evictions_host_budget": self.evictions_host_budget,
            "evictions_approx_scope_cap": self.evictions_approx_scope_cap,
            "evictions_stale_invalid": self.evictions_stale_invalid,
            "evictions_shutdown": self.evictions_shutdown,
            "evictions_superseded": self.evictions_superseded,
            "starts_spilled": self.starts_spilled,
            "spill_writes_committed": self.spill_writes_committed,
            "spill_bytes_written": self.spill_bytes_written,
            "spill_write_us_total": self.spill_write_us_total,
            "spill_write_timeouts": self.spill_write_timeouts,
            "spill_disk_used_bytes": self.spill_disk_used_bytes,
            "spill_disk_max_bytes": self.spill_disk_max_bytes,
            "spill_disk_gc_evictions": self.spill_disk_gc_evictions,
            "spill_reads_hit": self.spill_reads_hit,
            "spill_reads_miss": self.spill_reads_miss,
            "spill_bytes_read": self.spill_bytes_read,
            "spill_read_us_total": self.spill_read_us_total,
            "starts_restored": self.starts_restored,
            "restores_failed": self.restores_failed,
            "restore_us_total": self.restore_us_total,
        })
    }
}

#[cfg(test)]
impl CacheMemoryInterval {
    #[cfg(not(standalone_blocks))]
    pub fn to_json(self) -> serde_json::Value {
        serde_json::json!({
            "window_slots_used": self.window_slots_used,
            "window_slots_capacity": self.window_slots_capacity,
            "window_slots_bytes_used": self.window_slots_bytes_used,
            "window_slots_bytes_capacity": self.window_slots_bytes_capacity,
            "full_slots_used": self.full_slots_used,
            "full_slots_capacity": self.full_slots_capacity,
            "full_slots_bytes_used": self.full_slots_bytes_used,
            "full_slots_bytes_capacity": self.full_slots_bytes_capacity,
            "retained_host_bytes": self.retained_host_bytes,
            "retained_host_budget_bytes": self.retained_host_budget_bytes,
            "retained_starts": self.retained_starts,
            "approx_retained_starts": self.approx_retained_starts,
            "spilled_starts": self.spilled_starts,
            "evictions_pool_pressure": self.evictions_pool_pressure,
            "evictions_host_budget": self.evictions_host_budget,
            "evictions_approx_scope_cap": self.evictions_approx_scope_cap,
            "evictions_stale_invalid": self.evictions_stale_invalid,
            "evictions_shutdown": self.evictions_shutdown,
            "evictions_superseded": self.evictions_superseded,
            "starts_spilled": self.starts_spilled,
            "spill_writes_committed": self.spill_writes_committed,
            "spill_bytes_written": self.spill_bytes_written,
            "spill_write_us_total": self.spill_write_us_total,
            "spill_write_timeouts": self.spill_write_timeouts,
            "spill_disk_used_bytes": self.spill_disk_used_bytes,
            "spill_disk_max_bytes": self.spill_disk_max_bytes,
            "spill_disk_gc_evictions": self.spill_disk_gc_evictions,
            "spill_reads_hit": self.spill_reads_hit,
            "spill_reads_miss": self.spill_reads_miss,
            "spill_bytes_read": self.spill_bytes_read,
            "spill_read_us_total": self.spill_read_us_total,
            "starts_restored": self.starts_restored,
            "restores_failed": self.restores_failed,
            "restore_us_total": self.restore_us_total,
        })
    }
}

/// 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,
    /// True when this approximate lane seals into its namespace's twin [`approx_namespace`] instead of
    /// sealing nothing: its blocks and start points live only in that twin, so they can serve only a
    /// later request whose tokens are an exact prefix match of this lane's (the same card's next turn),
    /// never an exact lookup, and never as a stitch donor. Set only by [`ServeBlockCache::enter_approx_path`]
    /// or by binding an approximate start, and only when [`ServeBlockCache::set_approx_retain`] is on.
    pub(crate) approx_path: bool,
    /// This lane's conversation twin namespace ([`approx_twin`]); 0 keeps it out of approximate reuse.
    pub owner: u64,
    /// True when the request sent a valid `X-Inky-Card-Id` with zero tools (`tools` absent or `[]`):
    /// isolated from `owner_prior` and `card_lease` (`owner == 0`) and classified as `*_side_call`.
    pub(crate) side_call: bool,
    pub(crate) save_owner_turn: u64,
    /// The lane's last completed decode block boundary and its `cs` there: saved as one approximate start
    /// when the turn ends ([`ServeBlockCache::release_lane`]), so the next turn resumes past this reply.
    pub(crate) turn_ckpt: Option<TurnCheckpoint>,
    /// Why the lane's last decode block boundary got no checkpoint, when it could not be held.
    pub(crate) turn_ckpt_miss: Option<TurnEndMiss>,
    pub(crate) bound_lane: Option<usize>,
    pub(crate) prompt_saved_pos: usize,
    pub(crate) prompt_saved_id: Option<SealedId>,
    /// The start this lane bound (bind, restore or rebind). With `prompt_saved_id` it is held, and so leased,
    /// while the lane is in flight, and its lease restarts at release ([`ServeBlockCache::release_lane`]).
    pub(crate) bound_start_id: Option<SealedId>,
    /// Starts this lane counts in [`ServeBlockCache`]'s `held_starts`; dropped at release and at the next bind.
    pub(crate) lease_holds: Vec<SealedId>,
    pub(crate) reply_saved_pos: usize,
    pub(crate) reply_saved_id: Option<SealedId>,
    pub(crate) tail_toks: Vec<u32>,
    pub(crate) observed_prior: ObservedPrior,
    /// True when this admission is an internal continuation after KV pool preemption (`Resumed::preemptions > 0`),
    /// so binding its own saved start does not inflate external turn-level `start_matches` / `cached_tokens_total`
    /// or `approx_start_matches` / `approx_cached_tokens_total`.
    pub internal_resume: bool,
    /// Reply tokens carried in `toks` past the request's own prompt on a preempted continuation (`Resumed::sent`),
    /// so `prompt_len` stays the request's own prompt length (`toks.len() - resume_reply_tokens`).
    pub resume_reply_tokens: usize,
}

impl LaneBlockState {
    #[inline]
    fn effective_prompt_len(&self, toks_len: usize) -> usize {
        toks_len.saturating_sub(self.resume_reply_tokens)
    }
}

/// A lane's pending turn-end start: a decode block boundary, the lane's `cs` there, and the Window blocks a
/// start there binds (`end / BLOCK - 16 .. end / BLOCK`).
///
/// Each Window entry holds one pool reference from the moment the checkpoint is taken until it is replaced or
/// the lane is released. The lane's own table cannot keep them: it drops block `end / BLOCK - 16` once it has
/// written position `end + 62` (`first_live_window_block_at(end + 63)` is one block later), which is one token
/// before the next boundary replaces this checkpoint. The table has just taken its newest block's slot back by
/// then, so the hold adds no slot to what a decoding lane occupies.
#[derive(Debug)]
pub(crate) struct TurnCheckpoint {
    end: usize,
    cs: Vec<u8>,
    window: Vec<(BlockIndex, BlockEntry)>,
}

/// What a released lane's turn-end start came to, for the request record (`reuse.turn_end_start`) and the
/// `turn_end_starts_*` counters. The aim is that no turn ends `NotSaved`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TurnEndStart {
    /// None was due: the reply completed no block past its prompt, or the lane keeps no approximate work
    /// (no conversation id, or `--exact`).
    #[default]
    NotDue,
    /// A start is held at the reply's last block boundary: the card's next turn prefills from there.
    Saved,
    /// The next turn prefills at least one whole block of this reply again.
    NotSaved(TurnEndMiss),
}

/// Why a turn-end start was not saved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnEndMiss {
    /// No `cs` was read at any block boundary of the reply.
    NoCheckpoint,
    /// A start was saved, but at an earlier boundary than the reply's last.
    Behind,
    /// The lane left its approximate path, or its sealed chain stops short of the checkpoint.
    OffPath,
    /// A block the start binds is in neither the lane's table nor the checkpoint's hold.
    BlockMissing,
    /// A block the start binds is no longer live and sealed.
    BlockNotLive,
}

impl TurnEndMiss {
    pub const ALL: [TurnEndMiss; 5] = [
        TurnEndMiss::NoCheckpoint,
        TurnEndMiss::Behind,
        TurnEndMiss::OffPath,
        TurnEndMiss::BlockMissing,
        TurnEndMiss::BlockNotLive,
    ];

    #[cfg(test)]
    pub fn name(self) -> &'static str {
        match self {
            TurnEndMiss::NoCheckpoint => "no_checkpoint",
            TurnEndMiss::Behind => "behind",
            TurnEndMiss::OffPath => "off_path",
            TurnEndMiss::BlockMissing => "block_missing",
            TurnEndMiss::BlockNotLive => "block_not_live",
        }
    }
}

impl TurnEndStart {
    /// The request record's `reuse.turn_end_start`: `saved`, `not_due`, or `not_saved:` and the reason.
    pub fn record_tag(self) -> &'static str {
        match self {
            TurnEndStart::NotDue => "not_due",
            TurnEndStart::Saved => "saved",
            TurnEndStart::NotSaved(TurnEndMiss::NoCheckpoint) => "not_saved:no_checkpoint",
            TurnEndStart::NotSaved(TurnEndMiss::Behind) => "not_saved:behind",
            TurnEndStart::NotSaved(TurnEndMiss::OffPath) => "not_saved:off_path",
            TurnEndStart::NotSaved(TurnEndMiss::BlockMissing) => "not_saved:block_missing",
            TurnEndStart::NotSaved(TurnEndMiss::BlockNotLive) => "not_saved:block_not_live",
        }
    }
}

/// The twin namespace an approximate lane (a stitched lane, or one resumed from an approximate start)
/// seals into. `EntryTree` keeps every chain inside one namespace (a parent must share its child's
/// namespace), so an exact lookup in `ns` can never walk into a block sealed here.
///
/// The lane's `owner` field holds this twin directly: [`approx_twin`] derives it from the server's secret
/// namespace salt, the auth namespace and the full conversation id, so it is unforgeable without the salt.
pub(crate) fn approx_namespace(ns: u64, owner: u64) -> u64 {
    debug_assert_ne!(owner, ns, "a twin namespace never equals its exact namespace");
    owner
}

/// The twin namespace for conversation `card_id` (the full, untruncated `X-Inky-Card-Id`; see
/// `crate::record::owner_card_id`) in auth namespace `ns`: SHA-256 over the same secret salt
/// `derive_cache_namespace` uses, a domain tag, `ns`, the id's length and the id. 0 (no approximate reuse)
/// when the request named no conversation. Never 0 and never `ns` otherwise.
///
/// The card id is not a boundary between users who share a key and namespace: anyone holding both can name
/// another's conversation. It binds saved work to a conversation within one auth scope, never across scopes.
pub fn approx_twin(salt: &str, ns: u64, card_id: Option<&str>) -> u64 {
    let Some(id) = card_id.filter(|s| !s.is_empty()) else { return 0 };
    let mut hasher = crate::spill::Sha256::new();
    hasher.update(b"inky-approx-twin-v1\0");
    hasher.update(&(salt.len() as u64).to_le_bytes());
    hasher.update(salt.as_bytes());
    hasher.update(b"\0approx\0");
    hasher.update(&ns.to_le_bytes());
    hasher.update(&(id.len() as u64).to_le_bytes());
    hasher.update(id.as_bytes());
    let digest = hasher.finalize();
    let mut twin = u64::from_le_bytes(digest[..8].try_into().unwrap()).max(1);
    if twin == ns {
        twin ^= 1;
    }
    twin.max(1)
}

/// One reuse epoch spans 64 cache activity ticks (binds and saves; idle wall time does not count). Buckets rotate
/// lazily, so aging needs neither a timer nor a sweep over unused checkpoints.
const REUSE_EPOCH_TICKS: u64 = 64;

/// A retained start's demonstrated reuse: prompt tokens its successful binds skipped. The current epoch counts in
/// full, the previous one half, older credit has expired (`specs/CacheScheduler.tla` `SavedTokens`).
#[derive(Default, Clone, Copy, Debug)]
struct RecentReuse {
    epoch: u64,
    current: u64,
    previous: u64,
}

impl RecentReuse {
    fn record(&mut self, tick: u64, skipped: usize) {
        let epoch = tick / REUSE_EPOCH_TICKS;
        if epoch != self.epoch {
            self.previous = if epoch - self.epoch == 1 { self.current } else { 0 };
            self.current = 0;
            self.epoch = epoch;
        }
        self.current = self.current.saturating_add(skipped as u64);
    }

    fn saved_tokens(&self, tick: u64) -> u64 {
        match (tick / REUSE_EPOCH_TICKS).saturating_sub(self.epoch) {
            0 => self.current.saturating_add(self.previous / 2),
            1 => self.current / 2,
            _ => 0,
        }
    }
}

/// A resident start's place in the eviction order; the smaller rank is reclaimed first. The card lease is the
/// outermost key in both orders, so a leased start is taken only when no unleased one serves
/// (`LeasedProtectedWhenUnleasedSuffices`, specs/CardStartLease.tla). Under it the ranked order is: idle before
/// live (pinned by a lane), stale before recent (credited, or new inside its creation grace), then fewer saved
/// tokens per byte, then LRU, deeper first, and the id. `INK_RETAIN_LRU=1` drops every key but lease, LRU and depth.
#[derive(Clone, Copy, Debug)]
struct EvictionRank {
    leased: bool,
    live: bool,
    recent: bool,
    saved_tokens: u64,
    bytes: u64,
    last_used_tick: u64,
    pos: usize,
    sid: SealedId,
}

impl EvictionRank {
    fn compare(&self, other: &Self, lru: bool) -> std::cmp::Ordering {
        if lru {
            return self.lru_cmp(other);
        }
        self.leased
            .cmp(&other.leased)
            .then_with(|| self.live.cmp(&other.live))
            .then_with(|| self.recent.cmp(&other.recent))
            // Saved tokens per byte, compared exactly by cross-multiplication.
            .then_with(|| {
                (u128::from(self.saved_tokens) * u128::from(other.bytes))
                    .cmp(&(u128::from(other.saved_tokens) * u128::from(self.bytes)))
            })
            .then_with(|| self.last_used_tick.cmp(&other.last_used_tick))
            .then_with(|| other.pos.cmp(&self.pos))
            .then_with(|| self.sid.cmp(&other.sid))
    }

    /// The order before reuse ranking: unleased first, oldest LRU tick, deeper leaf before shared root.
    fn lru_cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.leased
            .cmp(&other.leased)
            .then_with(|| self.last_used_tick.cmp(&other.last_used_tick))
            .then_with(|| other.pos.cmp(&self.pos))
            .then_with(|| self.sid.cmp(&other.sid))
    }
}

/// The start to evict among `cands` under the active order, and whether plain LRU would have kept it.
fn pick_ranked_victim(cands: &[EvictionRank], lru: bool) -> Option<(SealedId, bool)> {
    let chosen = cands.iter().min_by(|a, b| a.compare(b, lru))?;
    let over_lru = !lru && cands.iter().min_by(|a, b| a.lru_cmp(b)).is_some_and(|first| first.sid != chosen.sid);
    Some((chosen.sid, over_lru))
}

struct RetainedStart {
    namespace: u64,
    /// Saved by an approximate lane into its namespace's twin: never spilled, never a stitch donor.
    approx: bool,
    /// The auth namespace of the lane that saved it (for the per-scope cap on approximate starts).
    scope: u64,
    pos: usize,
    cs: Vec<u8>,
    reasons: u8,
    /// Pool bytes of the entry list's slots, shared slots charged in full (`checkpoint_slot_bytes`).
    slot_bytes: u64,
    entries: Vec<(BlockKind, BlockIndex, BlockEntry)>,
    toks: Vec<u32>,
    reuse: RecentReuse,
    /// The tick a lane computed and saved this start; `None` for one restored from disk. Only a computed start gets
    /// creation grace, and saving it again never renews it.
    created_tick: Option<u64>,
    last_used_tick: u64,
    last_owner: u64,
    owner_turn: u64,
    last_used_ms: 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,
}

/// What `spill-index.bin` is built from: the header fields and every spilled start as of one moment. The
/// starts are shared, not copied, so taking this costs the scheduler nothing per token; the writer builds
/// and hashes the image ([`SpillIndexSnapshot::into_bytes`]).
struct SpillIndexSnapshot {
    kvb: u32,
    next_spill_id: u64,
    tick: u64,
    full_attn_budget: u64,
    model_fingerprint: u64,
    records: Vec<(u64, Arc<SpilledStart>)>,
}

impl SpillIndexSnapshot {
    /// The crash-safe index image (pure-Rust binary format protected by `Sha256`, zero external crates).
    ///
    /// Never longer than `max_len`. `load_spill_index_on_open` reads at most `MAX_SPILL_INDEX_BYTES`, takes a
    /// longer file for a corrupt one and removes every spill block, so the least recently used starts are left
    /// out of the image until it fits. This run still restores them; the next open sweeps their blocks.
    fn into_bytes(mut self, max_len: usize) -> Vec<u8> {
        self.records.retain(|(_, sp)| sp.toks.len() == sp.pos && sp.pos > 0 && sp.pos.is_multiple_of(BLOCK));
        self.records.sort_by_key(|(id, sp)| (sp.last_used_tick, *id));
        let mut room = max_len.saturating_sub(SPILL_INDEX_PREFIX_LEN + 8 + 32);
        let mut first_kept = self.records.len();
        while first_kept > 0 {
            let sp = &self.records[first_kept - 1].1;
            let record_len = 46 + 4 * sp.toks.len() + 4 + 14 * sp.entries.len();
            if record_len > room {
                break;
            }
            room -= record_len;
            first_kept -= 1;
        }
        self.records.drain(..first_kept);

        let mut payload = Vec::new();
        for (id, sp) in &self.records {
            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 = self.records.len() 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(&self.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.full_attn_budget.to_le_bytes());
        header[44..52].copy_from_slice(&self.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();

        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);
        full
    }
}

/// Where an owner's prior-turn record pointed at a start that is now being spilled: once the spill lands, the
/// record points at the spilled start instead. `seq` names the record, which may be replaced meanwhile.
struct PriorFixup {
    owner: u64,
    seq: u64,
    tip: bool,
    prompt_tip: bool,
}

/// An evicted start whose spill is on its way to disk: the [`SpilledStart`] it becomes when every key it names
/// has landed, and what to undo if one does not.
struct PendingSpill {
    start: SpilledStart,
    prior_fixups: Vec<PriorFixup>,
    claimed_keys: Vec<SpillKey>,
    /// The spilled start a restore was reading when its need for slots evicted this one, and that start's
    /// keys: the commit must neither trim the one nor evict the others.
    shield: Option<(u64, Vec<SpillKey>)>,
    /// Keys not yet on disk: this spill's own writes, and writes an earlier spill queued for a shared block.
    waiting: usize,
    deadline_ms: u64,
}

/// One block or recurrent-state write handed to the spill writer and not yet landed.
struct PendingWrite {
    job: u64,
    bytes: u64,
    /// The pool slot the writer reads. One reference on it, the write pin, is held from the moment the write is
    /// queued until its result arrives or its job is cancelled before the writer took it, so the slot cannot be
    /// taken again while it is being read. `None` for recurrent state, whose bytes the job owns.
    pin: Option<(BlockKind, Slot)>,
    /// Spills that need this key. Empty: the write is in flight but every spill that wanted it has given up.
    waiters: Vec<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,
    /// The request's tokens, so a completed stage can move the lane onto its twin path (`enter_approx_path`).
    toks: Vec<u32>,
    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| crate::blocks::first_live_window_block_at(pos, EXT, 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,
    }
}

/// 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)
}

/// 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(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>,
    /// The queue of spill disk work and its thread, once anything has been queued.
    spill_writer: Option<SpillWriter>,
    /// True (the default): spill disk work runs on the calling thread, inside the eviction that asked for it,
    /// and has landed when that eviction returns. `serve` turns it off ([`ServeBlockCache::spill_in_background`]):
    /// evictions then only queue the work, and [`ServeBlockCache::poll_spill_writes`] collects what landed.
    spill_inline: bool,
    pending_spills: HashMap<u64, PendingSpill>,
    pending_writes: HashMap<SpillKey, PendingWrite>,
    spill_queue_bytes: u64,
    max_spill_queue_bytes: u64,
    spill_index_dirty: bool,
    spill_index_in_flight: bool,
    /// The longest index image `persist_spill_index` writes: `MAX_SPILL_INDEX_BYTES`, what a load will read.
    spill_index_max_bytes: usize,
    spilled_tree: PrefixTree<u64>,
    spilled_starts: HashMap<u64, Arc<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,
    card_lease: Duration,
    clock_origin: Instant,
    next_owner_turn: u64,
    latest_owner_turn: HashMap<u64, u64>,
    /// In-flight lanes holding each start (`LaneBlockState::lease_holds`); a held latest-turn PROMPT start is
    /// leased past `last_used_ms + card_lease`. Empty while `card_lease` is zero.
    held_starts: HashMap<SealedId, u32>,
    #[cfg(any(test, standalone_blocks))]
    test_clock_ms: Option<Arc<std::sync::atomic::AtomicU64>>,
    spill_write_timeout: Duration,
    spill_full_attn_budget: u64,
    spill_model_fingerprint: u64,
    kv_stitch: bool,
    /// Approximate lanes seal into their namespace twin so their own continuation can be resumed (`set_approx_retain`).
    approx_retain: bool,
    /// A prefill span may run through a start-point checkpoint ([`step_pf_target`]); off restores the split at every
    /// checkpoint (`INK_PREFILL_CKPT_SPLIT=1`, internal A/B switch).
    prefill_through: bool,
    /// Live approximate starts per auth scope, and the cap on them, so one tenant churning conversation ids
    /// cannot evict every other tenant's approximate work.
    approx_per_scope: HashMap<u64, usize>,
    max_approx_starts_per_scope: usize,
    /// `INK_RELEASE_SUPERSEDED_STARTS` (serve: on by default, `=0` off): a completed turn releases the approximate
    /// starts of its conversation's earlier turns ([`Self::release_superseded_turn_starts`]). Off in a bare cache.
    release_superseded_starts: bool,
    /// `INK_RETAIN_LRU=1` (dev opt-out, default off): evict retained starts by plain LRU under the lease, not by
    /// demonstrated reuse per byte ([`EvictionRank`]).
    retain_lru: bool,
    stitch_index: HashMap<(u64, u64), Vec<(SealedId, u32)>>,
    /// The zero-filled `Window` guard slots stitched lanes hold across their trailing window, as
    /// `(slot, generation)` ([`Self::finish_binding_stitched_lane`]). A guard is sealed and live like a
    /// block of K/V, but no lane computed it: it stands in for one lane's healing ramp only. So it is
    /// never a block's `Window` handle in `EntryTree`, never retained in `starts` or `spill_store`, and
    /// never bound in place of a block a lane computed. A released guard is dropped when the next one is
    /// taken or on shutdown; a generation is never reissued, so one that lingers until then matches nothing.
    stitch_guards: Vec<(Slot, 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,
    owner_prior: HashMap<u64, OwnerPriorTurn>,
    prior_checkpoint_owners: HashMap<SealedId, Vec<u64>>,
    next_owner_prior_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,
            spill_writer: None,
            spill_inline: true,
            pending_spills: HashMap::new(),
            pending_writes: HashMap::new(),
            spill_queue_bytes: 0,
            max_spill_queue_bytes: u64::MAX,
            spill_index_dirty: false,
            spill_index_in_flight: false,
            spill_index_max_bytes: MAX_SPILL_INDEX_BYTES,
            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,
            card_lease: Duration::ZERO,
            clock_origin: Instant::now(),
            next_owner_turn: 0,
            latest_owner_turn: HashMap::new(),
            held_starts: HashMap::new(),
            #[cfg(any(test, standalone_blocks))]
            test_clock_ms: None,
            spill_write_timeout: DEFAULT_SPILL_WRITE_TIMEOUT,
            spill_full_attn_budget: u64::MAX,
            spill_model_fingerprint: 0,
            kv_stitch: false,
            approx_retain: false,
            prefill_through: true,
            approx_per_scope: HashMap::new(),
            max_approx_starts_per_scope: DEFAULT_MAX_APPROX_STARTS_PER_SCOPE,
            release_superseded_starts: false,
            retain_lru: false,
            stitch_index: HashMap::new(),
            stitch_guards: Vec::new(),
            ikv_namespace: 0,
            ikv_catalog: None,
            ikv_stage_worker: None,
            pending_ikv_stages: HashMap::new(),
            next_ikv_stage_seq: 1,
            owner_prior: HashMap::new(),
            prior_checkpoint_owners: HashMap::new(),
            next_owner_prior_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
    }

    /// Let approximate lanes (stitched, or resumed from an approximate start) seal their blocks and start
    /// points into the twin [`approx_namespace`], so a returning turn of the same card resumes from its own
    /// saved work. Serve turns it on with `--kv-stitch` or `--ikv-dir` ([`crate::serve::approx_retain_for`]), both of
    /// which `--exact` refuses, so exact mode never has it. It also keeps a mounted file cartridge's prompt checkpoint
    /// in the conversation twin, so the same card's identical repeat binds it instead of stitching again (this was
    /// `INK_FILE_REUSE`, retired: serve mounts cartridges only with `--kv-stitch` and `--ikv-dir`, which turn this on, so
    /// it never added anything).
    pub fn set_approx_retain(&mut self, enabled: bool) {
        self.approx_retain = enabled;
    }

    /// Let a prefill span run through a start-point checkpoint (default on). Off is the earlier split at every
    /// checkpoint, kept for A/B timing and the token-parity tests (`INK_PREFILL_CKPT_SPLIT=1`).
    pub fn set_prefill_through(&mut self, enabled: bool) {
        self.prefill_through = enabled;
    }

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

    pub fn approx_retain_enabled(&self) -> bool {
        self.approx_retain
    }

    /// The longest whole-block prefix of `toks` already sealed for this request at ingress: in its exact namespace,
    /// or in its own conversation's twin when it names one. Token count only.
    pub fn ingress_common_prefix(&self, namespace: u64, owner: u64, toks: &[u32]) -> usize {
        let exact = self.tree.common_prefix_in_namespace(namespace, toks);
        if self.approx_retain && owner != 0 {
            exact.max(self.tree.common_prefix_in_namespace(approx_namespace(namespace, owner), toks))
        } else {
            exact
        }
    }

    pub fn max_retained_host_bytes(&self) -> u64 {
        self.max_retained_host_bytes
    }

    pub fn set_card_lease(&mut self, lease: Duration) {
        self.card_lease = lease;
    }

    pub fn card_lease(&self) -> Duration {
        self.card_lease
    }

    fn now_ms(&self) -> u64 {
        #[cfg(any(test, standalone_blocks))]
        if let Some(clk) = &self.test_clock_ms {
            return clk.load(Ordering::Relaxed);
        }
        self.clock_origin.elapsed().as_millis().min(u64::MAX as u128) as u64
    }

    /// The same clock in microseconds, for timing the scheduler's own work.
    fn now_us(&self) -> u64 {
        #[cfg(any(test, standalone_blocks))]
        if let Some(clk) = &self.test_clock_ms {
            return clk.load(Ordering::Relaxed).saturating_mul(1000);
        }
        self.clock_origin.elapsed().as_micros().min(u64::MAX as u128) as u64
    }

    fn alloc_owner_turn(&mut self) -> u64 {
        self.next_owner_turn = self.next_owner_turn.saturating_add(1);
        self.next_owner_turn
    }

    fn record_owner_turn(&mut self, owner: u64, turn: u64) {
        if owner == 0 || turn == 0 {
            return;
        }
        if self.latest_owner_turn.len() > self.starts.len().saturating_mul(2).saturating_add(64) {
            let live_owners: HashSet<u64> =
                self.starts.values().filter(|st| st.last_owner != 0).map(|st| st.last_owner).collect();
            self.latest_owner_turn.retain(|o, _| live_owners.contains(o));
        }
        let entry = self.latest_owner_turn.entry(owner).or_insert(0);
        if turn > *entry {
            *entry = turn;
        }
    }

    fn ensure_save_owner_turn(&mut self, state: &mut LaneBlockState) -> u64 {
        if self.card_lease.is_zero() || state.owner == 0 {
            state.save_owner_turn = 0;
            0
        } else {
            if state.save_owner_turn == 0 {
                let turn = self.alloc_owner_turn();
                state.save_owner_turn = turn;
                self.record_owner_turn(state.owner, turn);
            }
            state.save_owner_turn
        }
    }

    fn is_start_leased_at(&self, sid: SealedId, st: &RetainedStart, now_ms: u64, lease_ms: u64) -> bool {
        lease_ms > 0
            && (st.reasons & PROMPT) != 0
            && st.last_owner != 0
            && st.owner_turn != 0
            && self.latest_owner_turn.get(&st.last_owner) == Some(&st.owner_turn)
            && (now_ms < st.last_used_ms.saturating_add(lease_ms) || self.held_starts.contains_key(&sid))
    }

    /// Count `sid` as held by this in-flight lane (once per lane), so it stays leased until release.
    fn hold_start(&mut self, state: &mut LaneBlockState, sid: SealedId) {
        if self.card_lease.is_zero() || state.owner == 0 || state.lease_holds.contains(&sid) {
            return;
        }
        state.lease_holds.push(sid);
        *self.held_starts.entry(sid).or_insert(0) += 1;
    }

    /// Drop every hold this lane counts (release, or the next bind of a reused state).
    fn drop_lease_holds(&mut self, state: &mut LaneBlockState) {
        for sid in state.lease_holds.drain(..) {
            if let Some(n) = self.held_starts.get_mut(&sid) {
                *n -= 1;
                if *n == 0 {
                    self.held_starts.remove(&sid);
                }
            }
        }
    }

    /// At release: restart the lease of the starts this turn used (`[reply, prompt, bound]`), so the window
    /// counts from the end of the turn, or, for a cancelled card, drop its lease at once. Refreshes only a
    /// start that is still its owner's latest saved turn (never `save_owner_turn`: a short turn saves none).
    fn settle_lease_at_release(&mut self, state: &mut LaneBlockState, cancelled: bool) {
        self.drop_lease_holds(state);
        if self.card_lease.is_zero() || state.owner == 0 {
            return;
        }
        if cancelled {
            self.latest_owner_turn.remove(&state.owner);
            return;
        }
        let now_ms = self.now_ms();
        let latest = self.latest_owner_turn.get(&state.owner).copied();
        for sid in [state.reply_saved_id, state.prompt_saved_id, state.bound_start_id].into_iter().flatten() {
            if let Some(st) = self.starts.get_mut(&sid) {
                if st.last_owner == state.owner && st.owner_turn != 0 && latest == Some(st.owner_turn) {
                    st.last_used_ms = now_ms;
                }
            }
        }
    }

    /// INVARIANT (NoFalseExhaustion / LeasedProtectedWhenUnleasedSuffices / EveryOnlyNeverLeased /
    /// NoSavePreservesPriorTurnLease / PriorTurnImmediatelyUnleased, specs/CardStartLease.tla): returns
    /// the set of resident `PROMPT` / turn-end `SealedId`s belonging to each card's latest saved turn
    /// whose soft lease (`card_lease`) has not yet expired. Returns an empty `HashSet` in `O(1)` when
    /// `card_lease` is zero (default off). Never consulted by `reclaimable_slots`.
    fn leased_starts(&self) -> HashSet<SealedId> {
        let lease_ms = self.card_lease.as_millis().min(u64::MAX as u128) as u64;
        if lease_ms == 0 || self.starts.is_empty() {
            return HashSet::new();
        }
        let now_ms = self.now_ms();
        self.starts
            .iter()
            .filter(|(&sid, st)| self.is_start_leased_at(sid, st, now_ms, lease_ms))
            .map(|(&sid, _)| sid)
            .collect()
    }

    fn note_bound_chain_owner(
        &mut self,
        ids: &[SealedId],
        sid: SealedId,
        state: &mut LaneBlockState,
        prompt_len: usize,
        matched_at: usize,
    ) {
        self.note_bound_start_owner(sid, state, prompt_len, matched_at);
        if matched_at > prompt_len {
            if state.prompt_saved_pos == 0 {
                let prompt_ckpt = ((prompt_len.saturating_sub(1)) / BLOCK) * BLOCK;
                for cand_pos in [prompt_len, prompt_ckpt] {
                    if cand_pos > 0 && cand_pos.is_multiple_of(BLOCK) {
                        if let Some(&anc_id) = ids.get(cand_pos / BLOCK - 1) {
                            if self.starts.contains_key(&anc_id) {
                                state.prompt_saved_pos = cand_pos;
                                state.prompt_saved_id = Some(anc_id);
                                break;
                            }
                        }
                    }
                }
            }
            if matched_at.is_multiple_of(BLOCK) && matched_at > state.reply_saved_pos && self.starts.contains_key(&sid) {
                state.reply_saved_pos = matched_at;
                state.reply_saved_id = Some(sid);
            }
        }
    }

    fn note_bound_start_owner(&mut self, sid: SealedId, state: &mut LaneBlockState, prompt_len: usize, matched_at: usize) {
        let prompt_ckpt = ((prompt_len.saturating_sub(1)) / BLOCK) * BLOCK;
        if matched_at > 0
            && (matched_at == prompt_ckpt || matched_at == prompt_len)
            && matched_at >= state.prompt_saved_pos
            && self.starts.contains_key(&sid)
        {
            state.prompt_saved_pos = matched_at;
            state.prompt_saved_id = Some(sid);
        }
        if self.card_lease.is_zero() || state.owner == 0 {
            return;
        }
        if self.starts.contains_key(&sid) {
            state.bound_start_id = Some(sid);
            self.hold_start(state, sid);
        }
        let refresh = self.starts.get(&sid).is_some_and(|st| {
            st.last_owner == state.owner
                && (st.reasons & PROMPT) != 0
                && st.owner_turn != 0
                && self.latest_owner_turn.get(&state.owner) == Some(&st.owner_turn)
        });
        if refresh {
            let now_ms = self.now_ms();
            if let Some(st) = self.starts.get_mut(&sid) {
                st.last_used_ms = now_ms;
            }
        }
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn set_test_clock_ms(&mut self, now_ms: u64) {
        self.test_clock_ms = Some(Arc::new(std::sync::atomic::AtomicU64::new(now_ms)));
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn advance_test_clock_ms(&mut self, delta_ms: u64) {
        match &self.test_clock_ms {
            Some(clk) => {
                let _ = clk.fetch_add(delta_ms, Ordering::Relaxed);
            }
            None => {
                self.test_clock_ms = Some(Arc::new(std::sync::atomic::AtomicU64::new(delta_ms)));
            }
        }
    }

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

    /// Whether `e` is a stitch guard slot (`stitch_guards`): zeros no lane computed.
    fn is_stitch_guard(&self, e: BlockEntry) -> bool {
        e.kind() == BlockKind::Window && self.stitch_guards.contains(&(e.slot(), e.generation()))
    }

    /// Live, sealed, and computed by a lane (never a zero stitch guard).
    fn entry_is_valid_kv(&self, pools: &BlockPools, kind: BlockKind, e: BlockEntry) -> bool {
        !self.is_stitch_guard(e) && entry_is_live_sealed(pools, kind, e)
    }

    fn insert_and_pin_approx_block(
        &mut self,
        pools: &BlockPools,
        tbl: &BlockTable,
        ns: u64,
        parent: Option<SealedId>,
        b: usize,
        toks: &[u32],
    ) -> Option<SealedId> {
        let bi = BlockIndex::new(b as u32);
        let fe = tbl.get(BlockKind::Full, bi).ok().flatten()?;
        if !self.entry_is_valid_kv(pools, BlockKind::Full, fe) {
            return None;
        }
        // After a stitch the lane's `Window` entry for a stitched block is its zero guard. The block is
        // published with no `Window` handle then: a later lane that prefills the block installs its own.
        let we = tbl
            .get(BlockKind::Window, bi)
            .ok()
            .flatten()
            .filter(|&w| self.entry_is_valid_kv(pools, BlockKind::Window, w));
        let blk_toks = &toks[b * BLOCK..(b + 1) * BLOCK];
        let id = self.tree.insert_in_namespace(ns, parent, b * BLOCK, blk_toks, BlockHandles::new(fe, we)).ok()?;
        if let Some(canon) = self.tree.handle(id) {
            let full_stale = !self.entry_is_valid_kv(pools, BlockKind::Full, canon.full());
            let win_stale = canon
                .window()
                .is_some_and(|cw| !self.entry_is_valid_kv(pools, BlockKind::Window, cw));
            if full_stale || win_stale || (canon.window().is_none() && we.is_some()) {
                let best_f = if full_stale { fe } else { canon.full() };
                let best_w = if win_stale || canon.window().is_none() { we } else { canon.window() };
                let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
            }
        }
        if self.tree.pin(id).is_err() {
            self.tree.prune_unreferenced(id);
            return None;
        }
        Some(id)
    }

    /// Move an approximate lane's sealed chain into the twin [`approx_namespace`] and mark it
    /// `approx_path`, or extend an already-`approx_path` lane's twin chain across a subsequent
    /// stitched span (`state.sealed.len() .. written/BLOCK`), so its later full blocks and start
    /// points are retained there. On initial entry, inserts blocks `0..written/BLOCK` from the
    /// lane's own table, pins the twin chain, then unpins and prunes the lane's exact chain. On
    /// subsequent stitches on the same turn (`state.approx_path == true`), appends the newly
    /// stitched blocks onto the existing twin chain. A no-op unless `approx_retain` is on and the
    /// lane is approximate. Nothing exact is touched: the twin chain shares slots, and `EntryTree`
    /// keeps each chain inside its own namespace.
    pub fn enter_approx_path(
        &mut self,
        pools: &BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
    ) {
        if !self.approx_retain || state.owner == 0 || !state.stitched_approx {
            return;
        }
        let ns = approx_namespace(state.namespace, state.owner);
        debug_assert_ne!(ns, state.namespace, "a twin never equals its exact namespace");
        let n = (state.written / BLOCK).min(toks.len() / BLOCK);

        if state.approx_path {
            let start_blk = state.sealed.len();
            if start_blk == n {
                return;
            }
            if start_blk < n {
                let mut parent = state.sealed.last().copied();
                let mut added: Vec<SealedId> = Vec::with_capacity(n - start_blk);
                for b in start_blk..n {
                    let Some(id) = self.insert_and_pin_approx_block(pools, tbl, ns, parent, b, toks) else {
                        break;
                    };
                    added.push(id);
                    parent = Some(id);
                }
                if added.len() != n - start_blk {
                    for id in added.into_iter().rev() {
                        self.tree.unpin(id);
                        self.tree.prune_unreferenced(id);
                    }
                    let old_tip = state.sealed.last().copied();
                    for id in state.sealed.drain(..) {
                        self.tree.unpin(id);
                    }
                    if let Some(old_tip) = old_tip {
                        self.tree.prune_unreferenced(old_tip);
                    }
                    state.approx_path = false;
                    return;
                }
                state.sealed.extend(added);
                state.stitched_approx = true;
                state.approx_path = true;
                return;
            }
            // Defensive: `start_blk > n` cannot occur in normal forward flow; release the stale twin pins
            // cleanly and rebuild `0..n` from `tbl` below.
            let old_tip = state.sealed.last().copied();
            for id in state.sealed.drain(..) {
                self.tree.unpin(id);
            }
            if let Some(old_tip) = old_tip {
                self.tree.prune_unreferenced(old_tip);
            }
            state.approx_path = false;
        }

        let mut ids: Vec<SealedId> = Vec::with_capacity(n);
        let mut parent: Option<SealedId> = None;
        for b in 0..n {
            let Some(id) = self.insert_and_pin_approx_block(pools, tbl, ns, parent, b, toks) else {
                break;
            };
            ids.push(id);
            parent = Some(id);
        }
        if ids.len() != n {
            // A block the twin chain cannot hold: keep the lane as it was (approximate, sealing nothing).
            for id in ids.into_iter().rev() {
                self.tree.unpin(id);
                self.tree.prune_unreferenced(id);
            }
            return;
        }
        let old_tip = state.sealed.last().copied();
        for id in state.sealed.drain(..) {
            self.tree.unpin(id);
        }
        if let Some(old_tip) = old_tip {
            self.tree.prune_unreferenced(old_tip);
        }
        state.sealed = ids;
        state.stitched_approx = true;
        state.approx_path = true;
    }

    /// Bind the deepest live approximate start (in the twin of `state.namespace`) when it is strictly
    /// deeper than `exact_at`, the deepest exact start (in RAM or spilled). The lane becomes approximate
    /// and keeps sealing into the twin. `None` (state untouched) otherwise.
    fn bind_deeper_approx_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        exact_at: usize,
    ) -> Option<(usize, Vec<u8>)> {
        // INVARIANT (ApproxOwned, specs/ApproxStarts.tla): an approximate start serves only its own conversation in its own auth scope
        // (`approx_namespace(namespace, owner)`), only with `approx_retain` (never `--exact`), and only on an exact
        // token-prefix match; a request without a conversation id (`owner == 0`) gets exact starts only.
        if !self.approx_retain || state.owner == 0 || toks.len() <= 1 {
            return None;
        }
        let ns = approx_namespace(state.namespace, state.owner);
        let search = &toks[..toks.len() - 1];
        loop {
            let matched = self.tree.deepest_start_in_namespace(ns, search);
            if matched.at <= exact_at {
                return None;
            }
            let sid = matched.start?;
            let live = match self.starts.get(&sid) {
                Some(st) => {
                    st.approx
                        && st.namespace == ns
                        && st.pos == matched.at
                        && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
                }
                None => false,
            };
            if !live {
                // A start the tree names but the index cannot evict is a desync: give up on approximate reuse
                // for this request rather than spin on the scheduler thread.
                if !self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid) {
                    return None;
                }
                continue;
            }
            self.record_prefix_reuse(&matched.ids, 0);
            let prompt_len = state.effective_prompt_len(toks.len());
            self.note_bound_chain_owner(&matched.ids, sid, state, prompt_len, matched.at);
            let (cs, entries) = {
                let st = self.starts.get(&sid).expect("checked approximate 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 approximate start block");
            }
            for &id in &matched.ids {
                self.tree.pin(id).expect("pin matched approximate prefix block");
            }
            state.prompt_len = prompt_len;
            state.sealed = matched.ids;
            state.written = matched.at;
            state.stitched_approx = true;
            state.approx_path = true;
            if !state.internal_resume {
                self.stats.approx_start_matches += 1;
                self.stats.approx_cached_tokens_total += matched.at as u64;
            }
            return Some((matched.at, cs));
        }
    }

    #[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;
    }

    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()
    }

    /// From now on an eviction only queues its spill: the blocks are written by the spill writer thread, at
    /// most `max_queue_bytes` of them waiting at once, and [`ServeBlockCache::poll_spill_writes`] collects what
    /// landed. The scheduler never waits for the disk. Without this call (tests, the trace tools) a spill is
    /// written inside the eviction, as it always was.
    pub fn spill_in_background(&mut self, max_queue_bytes: u64) {
        let Some(store) = self.spill_store.as_ref() else {
            return;
        };
        let wake = self.shared_wake.clone();
        let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
        writer.start_thread(Arc::new(move || wake.notify()));
        self.spill_inline = false;
        self.max_spill_queue_bytes = max_queue_bytes;
    }

    /// Queue spills as [`ServeBlockCache::spill_in_background`] does, with no writer thread: the queued work
    /// runs only when the test calls [`ServeBlockCache::run_spill_writer_for_test`].
    #[cfg(test)]
    pub(crate) fn spill_by_hand_for_test(&mut self, max_queue_bytes: u64) {
        self.spill_inline = false;
        self.max_spill_queue_bytes = max_queue_bytes;
    }

    /// Run up to `max` queued spill jobs, as the writer thread would. Their results wait for the next
    /// [`ServeBlockCache::poll_spill_writes`].
    #[cfg(test)]
    pub(crate) fn run_spill_writer_for_test(&mut self, max: usize) -> usize {
        self.spill_writer.as_ref().map_or(0, |w| w.run_queued(max))
    }

    /// A fake slow disk: every block write advances the test clock by `ms_per_write`.
    #[cfg(test)]
    pub(crate) fn set_spill_write_cost_for_test(&mut self, ms_per_write: u64) {
        let clock = self.test_clock_ms.clone().expect("set_test_clock_ms first");
        let store = self.spill_store.as_ref().expect("a spill store");
        let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
        writer.set_block_hook(Some(Arc::new(move |_| {
            clock.fetch_add(ms_per_write, Ordering::Relaxed);
        })));
    }

    /// True while a spill write holds pool blocks that come back when it lands: a lane that found the pool
    /// exhausted can still be served, so it defers instead of failing.
    pub fn spill_writes_hold_blocks(&self) -> bool {
        self.pending_writes.values().any(|w| w.pin.is_some())
    }

    /// True while the spill writer owes a result: something for [`ServeBlockCache::poll_spill_writes`] to
    /// collect soon, even with every lane idle.
    pub fn has_pending_spill_io(&self) -> bool {
        !self.pending_writes.is_empty() || self.spill_index_in_flight || self.spill_index_dirty
    }

    fn push_spill_io(&mut self, job: SpillIo, urgent: bool) -> u64 {
        let store = self.spill_store.as_ref().expect("spill I/O requires an open store");
        let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
        writer.push(job, urgent)
    }

    /// Delete block `key`, which no spilled start names any more. Inline, the file is unlinked here; otherwise
    /// the index forgets it now and the spill writer unlinks it.
    fn drop_spill_block(&mut self, key: SpillKey) {
        let Some(store) = self.spill_store.as_mut() else {
            return;
        };
        if self.spill_inline {
            store.remove_block(key);
            return;
        }
        store.forget_block_owing_unlink(key);
        self.push_spill_io(SpillIo::Unlink { key }, true);
    }

    /// Unlink blocks the disk budget already dropped from the index (`reserve_write`, `evict_lru_to_fit_owing_unlinks`).
    fn unlink_owed_spill_blocks(&mut self, keys: Vec<SpillKey>) {
        for key in keys {
            if self.spill_inline {
                if let Some(store) = self.spill_store.as_ref() {
                    let _ = unlink_block_in_dir(store.dir(), key);
                }
            } else {
                self.push_spill_io(SpillIo::Unlink { key }, true);
            }
        }
    }

    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);
        }
    }

    /// Keys the disk budget must not evict: blocks a restore is reading, and blocks a pending spill reuses.
    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());
        }
        for pending in self.pending_spills.values() {
            out.extend(pending.claimed_keys.iter().copied());
        }
        out
    }

    fn spill_index_snapshot(&self) -> Option<SpillIndexSnapshot> {
        let store = self.spill_store.as_ref()?;
        Some(SpillIndexSnapshot {
            kvb: store.kvb(),
            next_spill_id: self.next_spill_id,
            tick: self.tick,
            full_attn_budget: self.spill_full_attn_budget,
            model_fingerprint: self.spill_model_fingerprint,
            records: self.spilled_starts.iter().map(|(&id, sp)| (id, sp.clone())).collect(),
        })
    }

    /// Persist `self.spilled_starts` crash-safely to `spill-index.bin`. Inline, it is written here. Otherwise it
    /// is only marked stale, and [`ServeBlockCache::poll_spill_writes`] hands the spill writer one image at a time.
    fn persist_spill_index(&mut self) {
        if !self.spill_inline {
            self.spill_index_dirty = self.spill_store.is_some();
            return;
        }
        let Some(snapshot) = self.spill_index_snapshot() else {
            return;
        };
        let image = snapshot.into_bytes(self.spill_index_max_bytes);
        if self.spill_store.as_ref().is_some_and(|store| store.write_index_bytes(&image).is_err()) {
            self.stats.spill_io_errors += 1;
        }
    }

    fn flush_spill_index(&mut self) {
        if !self.spill_index_dirty || self.spill_index_in_flight {
            return;
        }
        let Some(snapshot) = self.spill_index_snapshot() else {
            return;
        };
        self.spill_index_dirty = false;
        self.spill_index_in_flight = true;
        let max_len = self.spill_index_max_bytes;
        self.push_spill_io(SpillIo::Index { build: Box::new(move || snapshot.into_bytes(max_len)) }, true);
    }

    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, Arc::new(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, starts_dropped) = self.settle_spill_budget(0, &protected);
        evicted += gc_evicted;
        if index_dirty || starts_dropped {
            self.persist_spill_index();
        }
        self.stats.spill_maint_passes += 1;
        self.stats.spill_maint_evictions += evicted as u64;
        evicted
    }

    /// Landed bytes that only spills still in flight own, `except` aside. They are on disk but are not yet part
    /// of the budget: each such spill settles it when it commits, or unlinks its blocks when it fails.
    fn in_flight_spill_bytes(&self, except: u64) -> u64 {
        let Some(store) = self.spill_store.as_ref() else {
            return 0;
        };
        let mut seen: HashSet<SpillKey> = HashSet::new();
        let mut total = 0u64;
        for (&id, pending) in &self.pending_spills {
            if id == except {
                continue;
            }
            for &sk in &pending.claimed_keys {
                let in_flight_only = self
                    .spill_key_owners
                    .get(&sk)
                    .is_some_and(|owners| owners.iter().all(|o| *o != except && self.pending_spills.contains_key(o)));
                if in_flight_only && seen.insert(sk) {
                    total = total.saturating_add(store.entry_bytes(sk).unwrap_or(0));
                }
            }
        }
        total
    }

    /// Bring the bytes on disk back under `--max-spill-bytes` (not counting what spills still in flight have
    /// landed): evict LRU blocks outside `protected`, and the spilled starts that owned them. No index write.
    /// Returns `(blocks evicted, whether a spilled start went with them)`.
    fn settle_spill_budget(&mut self, except: u64, protected: &HashSet<SpillKey>) -> (usize, bool) {
        let in_flight = self.in_flight_spill_bytes(except);
        let inline = self.spill_inline;
        let Some(store) = self.spill_store.as_mut() else {
            return (0, false);
        };
        if store.used_bytes() <= store.max_bytes().saturating_add(in_flight) {
            return (0, false);
        }
        let mut owed_unlinks = Vec::new();
        let gc_evicted = store.settle_budget(in_flight, protected, (!inline).then_some(&mut owed_unlinks));
        self.unlink_owed_spill_blocks(owed_unlinks);
        let starts_dropped = self.drop_starts_of_gc_evicted(&gc_evicted);
        (gc_evicted.len(), starts_dropped)
    }

    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 {
        let mut s = self.stats;
        s.activity_ticks = self.tick;
        if let Some(st) = &self.spill_store {
            let ds = st.stats();
            s.spill_reads_hit = ds.reads_hit;
            s.spill_reads_miss = ds.reads_miss;
            s.spill_bytes_read = ds.bytes_read;
            s.spill_read_us_total = ds.read_us_total;
        }
        s.spill_writes_pending = self.pending_writes.len() as u64;
        s.spill_write_bytes_pending = self.spill_queue_bytes;
        s.spill_starts_pending = self.pending_spills.len() as u64;
        s
    }

    #[cfg(test)]
    pub fn memory_snapshot(&self, pools: &BlockPools) -> CacheMemorySnapshot {
        let (win_used, win_cap) = self.pool_occupancy(pools, BlockKind::Window);
        let (full_used, full_cap) = self.pool_occupancy(pools, BlockKind::Full);
        let win_stride = pools.window.stride_bytes();
        let full_stride = pools.full.stride_bytes();
        let approx_retained_starts: usize = self.approx_per_scope.values().copied().sum();
        let cs = self.stats();
        let (
            spill_writes_committed,
            spill_bytes_written,
            spill_write_us_total,
            spill_disk_used_bytes,
            spill_disk_max_bytes,
            spill_disk_gc_evictions,
        ) = match &self.spill_store {
            Some(store) => {
                let ds = store.stats();
                (
                    ds.writes_committed,
                    ds.bytes_written,
                    ds.write_us_total,
                    store.used_bytes(),
                    store.max_bytes(),
                    ds.disk_gc_evictions,
                )
            }
            None => (0, 0, 0, 0, 0, 0),
        };
        CacheMemorySnapshot {
            window_slots_used: win_used,
            window_slots_capacity: win_cap,
            window_slots_bytes_used: (win_used as u64).saturating_mul(win_stride),
            window_slots_bytes_capacity: (win_cap as u64).saturating_mul(win_stride),
            full_slots_used: full_used,
            full_slots_capacity: full_cap,
            full_slots_bytes_used: (full_used as u64).saturating_mul(full_stride),
            full_slots_bytes_capacity: (full_cap as u64).saturating_mul(full_stride),
            retained_host_bytes: self.retained_host_bytes,
            retained_host_budget_bytes: self.max_retained_host_bytes,
            retained_starts: self.starts.len(),
            approx_retained_starts,
            spilled_starts: self.spilled_starts.len(),
            evictions_pool_pressure: cs.evictions_pool_pressure,
            evictions_host_budget: cs.evictions_host_budget,
            evictions_approx_scope_cap: cs.evictions_approx_scope_cap,
            evictions_stale_invalid: cs.evictions_stale_invalid,
            evictions_shutdown: cs.evictions_shutdown,
            evictions_superseded: cs.evictions_superseded,
            starts_spilled: cs.starts_spilled,
            spill_writes_committed,
            spill_bytes_written,
            spill_write_us_total,
            spill_write_timeouts: cs.spill_write_timeouts,
            spill_disk_used_bytes,
            spill_disk_max_bytes,
            spill_disk_gc_evictions,
            spill_reads_hit: cs.spill_reads_hit,
            spill_reads_miss: cs.spill_reads_miss,
            spill_bytes_read: cs.spill_bytes_read,
            spill_read_us_total: cs.spill_read_us_total,
            starts_restored: cs.starts_restored,
            restores_failed: cs.restores_failed,
            restore_us_total: cs.restore_us_total,
        }
    }

    fn register_prior_checkpoint_ids(&mut self, owner: u64, prior: &OwnerPriorTurn) {
        let mut registered: [Option<SealedId>; 3] = [None; 3];
        let mut n = 0usize;
        for id in [prior.prompt_tip_id, prior.reply_tip_id, prior.tip_id].into_iter().flatten() {
            if registered[..n].contains(&Some(id)) {
                continue;
            }
            registered[n] = Some(id);
            n += 1;
            let owners = self.prior_checkpoint_owners.entry(id).or_default();
            if !owners.contains(&owner) {
                owners.push(owner);
            }
        }
    }

    fn unregister_prior_checkpoint_ids(&mut self, owner: u64, prior: &OwnerPriorTurn) {
        for id in [prior.prompt_tip_id, prior.reply_tip_id, prior.tip_id].into_iter().flatten() {
            let empty = if let Some(owners) = self.prior_checkpoint_owners.get_mut(&id) {
                owners.retain(|&o| o != owner);
                owners.is_empty()
            } else {
                false
            };
            if empty {
                self.prior_checkpoint_owners.remove(&id);
            }
        }
    }

    pub fn observe_prior(&self, owner: u64, toks: &[u32]) -> ObservedPrior {
        if owner == 0 {
            return ObservedPrior::default();
        }
        let Some(p) = self.owner_prior.get(&owner) else {
            return ObservedPrior::default();
        };
        let prompt_missing =
            p.prompt_saved_pos > 0 && p.prompt_tip_id.is_none_or(|id| !self.starts.contains_key(&id));
        let reply_missing =
            p.reply_saved_pos > 0 && p.reply_tip_id.is_none_or(|id| !self.starts.contains_key(&id));
        let any_saved_start_missing = p.evicted || prompt_missing || reply_missing;
        let _ = p.truncated_tail;

        let check_tail = |chain_len: usize| -> (Option<usize>, usize) {
            for (i, &expected) in p.tail_toks.iter().enumerate() {
                let idx = chain_len + i;
                if toks.get(idx).copied() != Some(expected) {
                    return (Some(idx), idx);
                }
            }
            (None, chain_len + p.tail_toks.len())
        };

        let (first_divergent_pos, proven_common_len) = match p.tip_id {
            Some(tip) => match self
                .tree
                .first_divergence_along_chain(tip, toks)
                .or_else(|| p.spilled_tip_id.and_then(|stip| self.spilled_tree.first_divergence_along_chain(stip, toks)))
            {
                Some(Err(diff_idx)) => (Some(diff_idx), diff_idx),
                Some(Ok(chain_len)) => check_tail(chain_len),
                None => match p
                    .prompt_tip_id
                    .and_then(|ptip| self.tree.first_divergence_along_chain(ptip, toks))
                    .or_else(|| {
                        p.spilled_prompt_tip_id
                            .and_then(|sptip| self.spilled_tree.first_divergence_along_chain(sptip, toks))
                    }) {
                    Some(Err(diff_idx)) => (Some(diff_idx), diff_idx),
                    Some(Ok(chain_len)) => (None, chain_len),
                    None => (None, 0),
                },
            },
            None => {
                if !p.evicted && !p.tail_toks.is_empty() {
                    check_tail(0)
                } else {
                    (None, 0)
                }
            }
        };

        ObservedPrior {
            has_prior: true,
            prompt_saved_pos: p.prompt_saved_pos,
            prompt_len: p.prompt_len,
            reply_saved_pos: p.reply_saved_pos,
            total_len: p.total_len,
            prompt_tip_id: p.prompt_tip_id,
            reply_tip_id: p.reply_tip_id,
            proven_common_len,
            evicted: p.evicted,
            any_saved_start_missing,
            first_divergent_pos,
        }
    }

    pub fn classify_observed_reuse(
        owner: u64,
        restore_at: usize,
        restore_failed: bool,
        obs: ObservedPrior,
        sealed: &[SealedId],
    ) -> (&'static str, Option<usize>) {
        let _ = (obs.total_len, obs.evicted);
        if restore_at > 0 {
            if owner != 0 && obs.has_prior {
                let matched_prompt_ckpt = obs.prompt_saved_pos >= BLOCK
                    && obs.prompt_saved_pos <= restore_at
                    && obs
                        .prompt_tip_id
                        .is_some_and(|id| sealed.get(obs.prompt_saved_pos / BLOCK - 1) == Some(&id));
                let matched_reply_ckpt = obs.reply_saved_pos >= BLOCK
                    && obs.reply_saved_pos <= restore_at
                    && obs
                        .reply_tip_id
                        .is_some_and(|id| sealed.get(obs.reply_saved_pos / BLOCK - 1) == Some(&id));
                let reply_continuous = obs.reply_saved_pos > 0
                    && restore_at >= obs.reply_saved_pos
                    && (matched_reply_ckpt || obs.proven_common_len >= obs.reply_saved_pos)
                    && obs.first_divergent_pos.is_none_or(|d| d >= restore_at);
                let prompt_continuous = obs.prompt_saved_pos > 0
                    && (matched_prompt_ckpt || obs.proven_common_len >= obs.prompt_saved_pos);

                if reply_continuous {
                    ("hit_reply_end", obs.first_divergent_pos)
                } else if prompt_continuous
                    && restore_at == obs.prompt_saved_pos
                    && obs.first_divergent_pos.is_some_and(|d| d >= obs.prompt_len)
                {
                    ("hit_prompt_end_diverged", obs.first_divergent_pos)
                } else if obs.first_divergent_pos.is_some() {
                    ("hit_prefix_diverged", obs.first_divergent_pos)
                } else if prompt_continuous
                    && restore_at >= obs.prompt_saved_pos
                    && obs.first_divergent_pos.is_none()
                {
                    ("hit_prompt_end", None)
                } else {
                    ("hit_shared_prefix", None)
                }
            } else {
                ("hit_shared_prefix", None)
            }
        } else if restore_failed {
            ("miss_restore_failed", obs.first_divergent_pos)
        } else if owner == 0 || !obs.has_prior {
            ("miss_no_prior_turn", None)
        } else if obs.first_divergent_pos.is_some() {
            ("miss_diverged", obs.first_divergent_pos)
        } else if obs.any_saved_start_missing {
            ("miss_evicted", None)
        } else {
            ("miss_prior_unsealed", None)
        }
    }

    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;
        }
    }

    /// `(slots referenced or retired, all slots)` of `kind`'s pool, retained start points included: an O(slots)
    /// walk, for the operator metrics only.
    pub fn pool_occupancy(&self, pools: &BlockPools, kind: BlockKind) -> (usize, usize) {
        let pool = pools.of(kind);
        let (_, free) = pool.count_usable_and_avail(&[]);
        (pool.len().saturating_sub(free), pool.len())
    }

    /// 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.approx && st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(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.approx && st.namespace == namespace
                        && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
                }
                None => false,
            };
            if all_live {
                break;
            }
            self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
            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.record_prefix_reuse(&pinned_ids, n_past);
        let prompt_len = state.effective_prompt_len(toks.len());
        self.note_bound_chain_owner(&pinned_ids, sid, state, prompt_len, matched.at);
        Self::drop_turn_checkpoint(pools, state);
        state.turn_ckpt_miss = None;
        *tbl = staged;
        state.prompt_len = prompt_len;
        state.sealed = pinned_ids;
        state.written = matched.at;
        state.stitched_approx = false;
        state.approx_path = false;
        if !state.internal_resume {
            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 = state.effective_prompt_len(toks.len());
        state.written = 0;
        state.stitched_approx = false;
        state.approx_path = false;
        state.save_owner_turn = 0;
        state.prompt_saved_pos = 0;
        state.prompt_saved_id = None;
        state.bound_start_id = None;
        Self::drop_turn_checkpoint(pools, state);
        state.turn_ckpt_miss = None;
        self.drop_lease_holds(state);
        state.reply_saved_pos = 0;
        state.reply_saved_id = None;
        state.tail_toks.clear();
        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.approx && st.namespace == namespace
                            && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
                    }
                    None => false,
                };
                if !all_live {
                    self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
                    in_ram = self.tree.deepest_start_in_namespace(namespace, search);
                }
            } else {
                in_ram.at = 0;
            }
        }
        // `restored_tip`: a disk restore landed; `restored`: the start it newly published (none when another lane had
        // already made that start resident, which is ordinary resident reuse).
        let mut restored_tip = None;
        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_tip = self.try_restore_spilled_start(pools, namespace, toks, spill_id, &in_ram);
                }
            }
        }
        let restored = restored_tip.and_then(|(tip, published)| published.then_some(tip));
        let matched =
            if restored_tip.is_some() { self.tree.deepest_start_in_namespace(namespace, search) } else { in_ram };
        if let Some(bound) = self.bind_deeper_approx_start(pools, tbl, state, toks, matched.at) {
            return Some(bound);
        }
        self.bind_matched_resident_start(pools, tbl, state, toks.len(), matched, restored)
    }

    fn bind_resident_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        restored: Option<SealedId>,
    ) -> 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]);
        let prompt_len = state.effective_prompt_len(toks.len());
        self.bind_matched_resident_start(pools, tbl, state, prompt_len, matched, restored)
    }

    fn bind_matched_resident_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        prompt_len: usize,
        matched: crate::prefix::StartMatch<BlockHandles>,
        restored: Option<SealedId>,
    ) -> 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.approx && st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e));
        if !all_live {
            self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
            return None;
        }
        // Touch the matched start and its ancestors along the hot prefix. A start this bind just restored from disk
        // has not shown resident reuse, so it is only touched; a shallower resident fallback earns its credit.
        if Some(sid) == restored {
            self.tick += 1;
            let now = self.tick;
            for &anc in &matched.ids {
                if let Some(st) = self.starts.get_mut(&anc) {
                    st.last_used_tick = now;
                }
            }
        } else {
            self.record_prefix_reuse(&matched.ids, 0);
        }
        self.note_bound_chain_owner(&matched.ids, sid, state, prompt_len, matched.at);
        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;
        state.approx_path = false;
        if !state.internal_resume {
            self.stats.start_matches += 1;
            self.stats.cached_tokens_total += matched.at as u64;
        }
        Some((matched.at, cs))
    }

    /// Touch and credit the starts on a successful bind's matched path (`ids`, the bound start and its ancestors in
    /// its namespace). Each earns the prompt tokens it let the lane skip beyond the `n_past` it had already computed
    /// (0 for an empty lane; a deeper rebind passes its written length). A probe, a save or a disk restore earns none.
    fn record_prefix_reuse(&mut self, ids: &[SealedId], n_past: usize) {
        self.tick += 1;
        let now = self.tick;
        for id in ids {
            if let Some(st) = self.starts.get_mut(id) {
                st.last_used_tick = now;
                st.reuse.record(now, st.pos.saturating_sub(n_past));
            }
        }
    }

    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) {
                    self.drop_spill_block(sk);
                }
            }
        }
        true
    }

    /// Forget blocks the disk budget evicted, and drop every spilled start that owned one. No index write.
    /// Returns whether a spilled start was dropped. A pending spill's blocks are protected, so none is here.
    fn drop_starts_of_gc_evicted(&mut self, evicted: &[SpillKey]) -> bool {
        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 {
                    debug_assert!(!self.pending_spills.contains_key(&oid), "disk GC evicted a pending spill's block");
                    if self.remove_spilled_start_inner(oid, true) {
                        dirty = true;
                    }
                }
            }
        }
        dirty
    }

    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 forget_spill_key_mapping(&mut self, sk: SpillKey) {
        if let Some(entry_key) = self.spill_key_to_entry.remove(&sk) {
            self.entry_spill_keys.remove(&entry_key);
        }
    }

    /// End a queued write that will never be read: drop its write pin and give back its reserved disk bytes.
    /// Only for a write whose job the spill writer provably never took (`SpillWriter::cancel` removed it, or
    /// `SpillWriter::stop` emptied the queue and joined the thread). A write the writer holds keeps its pin
    /// until its result arrives: dropping it sooner lets the slot be taken again while it is being read.
    fn release_pending_write(&mut self, pools: &mut BlockPools, sk: SpillKey) {
        let Some(write) = self.pending_writes.remove(&sk) else {
            return;
        };
        self.spill_queue_bytes = self.spill_queue_bytes.saturating_sub(write.bytes);
        if let Some((kind, slot)) = write.pin {
            pools.of_mut(kind).record_mut(slot).unwrap().drop_ref().expect("drop a cancelled spill write pin");
        }
        if let Some(store) = self.spill_store.as_mut() {
            store.release_write_reservation(sk);
        }
    }

    /// Give up `spill_id`'s claims. A block no other spill claims goes: unlinked if it is on disk, taken back
    /// out of the spill writer's queue and unpinned if it still waits there. A block the writer already holds
    /// is left to land, and `on_spill_block_written` unlinks it then unless a later spill has claimed it.
    fn abort_spill_claims(&mut self, pools: &mut BlockPools, spill_id: u64, claimed: &[SpillKey]) {
        for &sk in claimed {
            let mut cancel_job = None;
            if let Some(write) = self.pending_writes.get_mut(&sk) {
                write.waiters.retain(|&id| id != spill_id);
                if write.waiters.is_empty() {
                    cancel_job = Some(write.job);
                }
            }
            let unowned = if let Some(owners) = self.spill_key_owners.get_mut(&sk) {
                owners.retain(|&id| id != spill_id);
                owners.is_empty()
            } else {
                false
            };
            if unowned {
                self.spill_key_owners.remove(&sk);
            }
            if let Some(job) = cancel_job {
                if self.spill_writer.as_ref().is_some_and(|writer| writer.cancel(job)) {
                    self.release_pending_write(pools, sk);
                    if unowned {
                        self.forget_spill_key_mapping(sk);
                    }
                }
                continue;
            }
            if unowned && !self.pending_writes.contains_key(&sk) {
                self.forget_spill_key_mapping(sk);
                if !self.in_flight_restore_keys.contains_key(&sk) {
                    self.drop_spill_block(sk);
                }
            }
        }
    }

    /// The spilled start a trim to `max_spilled_starts` would drop next: the least recently used, never one a
    /// restore is reading (`shield`, or any in flight).
    fn oldest_trimmable_spilled_start(&self, shield: Option<u64>) -> Option<u64> {
        self.spilled_starts
            .iter()
            .filter(|(id, _)| Some(**id) != shield && !self.in_flight_restore_spills.contains(id))
            .min_by_key(|(_, sp)| (sp.last_used_tick, std::cmp::Reverse(sp.pos)))
            .map(|(&id, _)| id)
    }

    /// Whether one more spilled start fits `max_spilled_starts`, trimming the oldest if it has to.
    fn spilled_start_slot_available(&self, shield: Option<u64>) -> bool {
        let over = (self.spilled_starts.len() + 1).saturating_sub(self.max_spilled_starts);
        over == 0
            || self
                .spilled_starts
                .keys()
                .filter(|id| Some(**id) != shield && !self.in_flight_restore_spills.contains(id))
                .count()
                >= over
    }

    /// Start spilling the evicted start `st`. Nothing in the cold tier changes here and no file is touched: the
    /// blocks already on disk, or on their way there for an earlier spill, are claimed; the rest are checked
    /// against the spill write queue and the disk budget, pinned, and handed to the spill writer. The spill
    /// commits in `commit_pending_spill` once every one has landed, and only there does an older spilled start
    /// give way to it. `Some(spill_id)`: the spill is pending and has taken `st.cs` and `st.toks`. `None`: `st`
    /// is not spilled and the cold tier is exactly as it was.
    ///
    /// The rule that a spill which does not land leaves the cold tier as it found it follows the fix to
    /// `HotRamLruCache::alloc_for_logical` in Hellblazer/phlegethon commit 2541674 (GPL-3.0-or-later), which
    /// applies it to a different structure; no code is shared.
    fn queue_spill(
        &mut self,
        pools: &mut BlockPools,
        st: &mut RetainedStart,
        restore: Option<&RestoreSource>,
    ) -> Option<u64> {
        if self.spill_store.is_none()
            || st.approx
            || self.max_spilled_starts == 0
            || st.pos == 0
            || !st.pos.is_multiple_of(BLOCK)
            || st.toks.len() != st.pos
            || st.entries.is_empty()
        {
            return None;
        }
        if self.spill_write_timeout.is_zero() {
            self.stats.spill_write_timeouts += 1;
            return None;
        }
        for &(kind, _, e) in &st.entries {
            if !self.entry_is_valid_kv(pools, kind, e) || pools.of(kind).slot_raw_region(e.slot()).is_none() {
                return None;
            }
        }
        let shield_spill = restore.map(|source| source.spill_id);
        if !self.spilled_start_slot_available(shield_spill) {
            return None;
        }

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

        // Claim every block already on disk, or on its way there for an earlier spill, so no trim or disk GC
        // before this spill commits can delete a `.blk` file it reuses.
        let mut protected = self.protected_spill_keys(restore);
        let mut claimed_keys: Vec<SpillKey> = Vec::with_capacity(st.entries.len() + 1);
        let mut have: 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) {
                let on_disk = self.spill_store.as_ref().is_some_and(|store| store.contains(sk));
                if on_disk || self.pending_writes.contains_key(&sk) {
                    protected.insert(sk);
                    have.insert(sk);
                    self.claim_spill_key(spill_id, sk, &mut claimed_keys);
                }
            }
        }

        // What is left to write.
        struct NewWrite {
            kind: BlockKind,
            slot: Slot,
            generation: u32,
            entry_key: (u8, u32, u32),
            key: SpillKey,
            bytes: u64,
        }
        let mut new_writes: Vec<NewWrite> = Vec::new();
        let mut spilled_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::with_capacity(st.entries.len());
        let mut total_bytes = SpillStore::block_file_bytes(0, st.cs.len()).ok();
        for &(kind, bi, e) in &st.entries {
            let entry_key = (kind_idx(kind) as u8, e.slot().get(), e.generation());
            if let Some(&key) = self.entry_spill_keys.get(&entry_key).filter(|k| have.contains(k)) {
                spilled_entries.push((kind, bi, key));
                continue;
            }
            let key = self.alloc_spill_key(kind);
            spilled_entries.push((kind, bi, key));
            let bytes = SpillStore::block_file_bytes(pools.of(kind).stride_bytes() as usize, 0).ok();
            total_bytes = total_bytes.zip(bytes).map(|(total, bytes)| total.saturating_add(bytes));
            new_writes.push(NewWrite {
                kind,
                slot: e.slot(),
                generation: e.generation(),
                entry_key,
                key,
                bytes: bytes.unwrap_or(0),
            });
        }
        let Some(total_bytes) = total_bytes else {
            self.abort_spill_claims(pools, spill_id, &claimed_keys);
            return None;
        };

        // The spill write queue is bounded: a spill that does not fit is dropped, never waited for.
        if self.spill_queue_bytes.saturating_add(total_bytes) > self.max_spill_queue_bytes {
            self.stats.spill_writes_dropped_queue_full += new_writes.len() as u64 + 1;
            self.abort_spill_claims(pools, spill_id, &claimed_keys);
            return None;
        }
        // The disk budget, before anything is written or evicted: the whole spill must fit once LRU disk GC
        // has done all it may. The GC itself waits for the commit.
        let fits = self.spill_store.as_ref().is_some_and(|store| {
            let after = store.bytes_after_full_gc(&protected).saturating_add(store.reserved_bytes());
            after.saturating_add(total_bytes) <= store.max_bytes()
        });
        if !fits {
            if let Some(store) = self.spill_store.as_mut() {
                store.note_over_budget_drop();
            }
            self.abort_spill_claims(pools, spill_id, &claimed_keys);
            return None;
        }

        let timeout_ms = self.spill_write_timeout.as_millis().min(u128::from(u64::MAX)) as u64;
        let deadline_ms = self.now_ms().saturating_add(timeout_ms);
        let mut waiting = 0usize;
        for sk in &claimed_keys {
            if let Some(write) = self.pending_writes.get_mut(sk) {
                write.waiters.push(spill_id);
                waiting += 1;
            }
        }
        for w in new_writes {
            let pool = pools.of_mut(w.kind);
            let (ptr, len) = pool.slot_raw_region(w.slot).expect("a spilled block has bytes");
            // Held by this start alone, the block is free the moment its write lands: write it first.
            let urgent = pool.record(w.slot).is_ok_and(|rec| rec.refs() == 1);
            // The write pin. `release_pending_write` and `on_spill_block_written` are the only places it is dropped.
            pool.record_mut(w.slot).unwrap().add_ref().expect("pin a block for its spill write");
            if let Some(old_key) = self.entry_spill_keys.insert(w.entry_key, w.key) {
                self.spill_key_to_entry.remove(&old_key);
            }
            self.spill_key_to_entry.insert(w.key, w.entry_key);
            self.claim_spill_key(spill_id, w.key, &mut claimed_keys);
            if let Some(store) = self.spill_store.as_mut() {
                store.reserve_write(w.key, w.bytes);
            }
            let job = self.push_spill_io(
                SpillIo::Block {
                    key: w.key,
                    generation: u64::from(w.generation),
                    kv: SpillBytes::Pinned { ptr: ptr as *const u8, len },
                    state: None,
                    refuse_existing: true,
                },
                urgent,
            );
            self.pending_writes
                .insert(w.key, PendingWrite { job, bytes: w.bytes, pin: Some((w.kind, w.slot)), waiters: vec![spill_id] });
            self.spill_queue_bytes = self.spill_queue_bytes.saturating_add(w.bytes);
            self.stats.spill_writes_queued += 1;
            waiting += 1;
        }

        let cs_key = self.alloc_spill_key(BlockKind::Full);
        let cs = std::mem::take(&mut st.cs);
        let cs_bytes = SpillStore::block_file_bytes(0, cs.len()).unwrap_or(0);
        self.claim_spill_key(spill_id, cs_key, &mut claimed_keys);
        if let Some(store) = self.spill_store.as_mut() {
            store.reserve_write(cs_key, cs_bytes);
        }
        let job = self.push_spill_io(
            SpillIo::Block {
                key: cs_key,
                generation: 1,
                kv: SpillBytes::Owned(Vec::new()),
                state: Some(cs),
                refuse_existing: true,
            },
            true,
        );
        self.pending_writes.insert(cs_key, PendingWrite { job, bytes: cs_bytes, pin: None, waiters: vec![spill_id] });
        self.spill_queue_bytes = self.spill_queue_bytes.saturating_add(cs_bytes);
        self.stats.spill_writes_queued += 1;
        waiting += 1;

        self.pending_spills.insert(
            spill_id,
            PendingSpill {
                start: SpilledStart {
                    namespace: st.namespace,
                    pos: st.pos,
                    reasons: st.reasons,
                    cs_key,
                    entries: spilled_entries,
                    toks: std::mem::take(&mut st.toks),
                    last_used_tick: st.last_used_tick,
                },
                prior_fixups: Vec::new(),
                claimed_keys,
                shield: restore.map(|source| (source.spill_id, source.keys.iter().copied().collect())),
                waiting,
                deadline_ms,
            },
        );
        Some(spill_id)
    }

    /// The spill writer finished block `key`. Its write pin is dropped here, now that the writer is done with
    /// the slot, and every spill waiting for the block moves on: to its commit when this was its last, to its
    /// end when the write failed.
    fn on_spill_block_written(&mut self, pools: &mut BlockPools, key: SpillKey, raw: RawDiskWrite) {
        let Some(write) = self.pending_writes.remove(&key) else {
            let landed = self.spill_store.as_mut().is_some_and(|store| store.apply_raw_write(key, raw).is_ok());
            if !landed {
                self.stats.spill_io_errors += 1;
            } else if !self.spill_key_owners.contains_key(&key) {
                self.forget_spill_key_mapping(key);
                if !self.in_flight_restore_keys.contains_key(&key) {
                    self.drop_spill_block(key);
                }
            }
            return;
        };
        self.spill_queue_bytes = self.spill_queue_bytes.saturating_sub(write.bytes);
        if let Some((kind, slot)) = write.pin {
            pools.of_mut(kind).record_mut(slot).unwrap().drop_ref().expect("drop a landed spill write pin");
        }
        let landed = self.spill_store.as_mut().is_some_and(|store| store.apply_raw_write(key, raw).is_ok());
        if !landed {
            // Nothing of ours is at this key's path (a failed write removes its own temporary file), so the key
            // is forgotten outright: dropping its spills below must not unlink whatever is there.
            self.stats.spill_io_errors += 1;
            self.spill_key_owners.remove(&key);
            self.forget_spill_key_mapping(key);
            for spill_id in write.waiters {
                self.fail_pending_spill(pools, spill_id);
            }
            return;
        }
        if !self.spill_key_owners.contains_key(&key) {
            // Every spill that wanted this block gave up while it was being written.
            self.forget_spill_key_mapping(key);
            if !self.in_flight_restore_keys.contains_key(&key) {
                self.drop_spill_block(key);
            }
            return;
        }
        for spill_id in write.waiters {
            let last = self.pending_spills.get_mut(&spill_id).is_some_and(|pending| {
                pending.waiting = pending.waiting.saturating_sub(1);
                pending.waiting == 0
            });
            if last {
                self.commit_pending_spill(pools, spill_id);
            }
        }
    }

    /// Every key `spill_id` names is on disk: make it a spilled start. Only now does anything older give way to
    /// it: the oldest spilled starts are trimmed to `max_spilled_starts`, LRU disk GC settles
    /// `--max-spill-bytes`, and the index is persisted, once. A spill that cannot be kept after all is dropped
    /// first, with the cold tier left as it was.
    fn commit_pending_spill(&mut self, pools: &mut BlockPools, spill_id: u64) {
        let Some(pending) = self.pending_spills.get(&spill_id) else {
            return;
        };
        let shield_spill = pending.shield.as_ref().map(|(id, _)| *id);
        // Still pending, so its own blocks are among the protected ones.
        let mut protected = self.protected_spill_keys(None);
        if let Some((_, keys)) = &pending.shield {
            protected.extend(keys.iter().copied());
        }
        let in_flight = self.in_flight_spill_bytes(spill_id);
        let (all_present, fits) = self.spill_store.as_ref().map_or((false, false), |store| {
            let start = &pending.start;
            let all_present = store.contains(start.cs_key) && start.entries.iter().all(|&(_, _, sk)| store.contains(sk));
            (all_present, store.bytes_after_full_gc(&protected) <= store.max_bytes().saturating_add(in_flight))
        });
        if !all_present || !fits || !self.spilled_start_slot_available(shield_spill) {
            if all_present && !fits {
                if let Some(store) = self.spill_store.as_mut() {
                    store.note_over_budget_drop();
                }
            }
            self.fail_pending_spill(pools, spill_id);
            return;
        }
        let pending = self.pending_spills.remove(&spill_id).expect("checked above");
        let st = pending.start;

        // The start's blocks are as recent as the start: a block reused from an earlier spill would otherwise
        // keep its first write's LRU stamp, and disk GC would take it, and every start that shares it, first.
        if let Some(store) = self.spill_store.as_mut() {
            for &(_, _, sk) in &st.entries {
                store.touch(sk);
            }
            store.touch(st.cs_key);
        }
        while self.spilled_starts.len() >= self.max_spilled_starts {
            let Some(oldest) = self.oldest_trimmable_spilled_start(shield_spill) else {
                break;
            };
            self.remove_spilled_start_inner(oldest, true);
        }
        self.settle_spill_budget(spill_id, &protected);

        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");
        let spilled_tip = 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);
            }
            p.expect("non-empty spilled blocks")
        } else {
            tip
        };
        let _ = self.spilled_tree.set_handle(spilled_tip, spill_id);
        self.spilled_tree.retain_start(spilled_tip).expect("retain spilled start");
        self.spilled_tips.insert(spill_id, spilled_tip);
        self.spilled_starts.insert(spill_id, Arc::new(st));
        self.stats.starts_spilled += 1;

        for fixup in pending.prior_fixups {
            if let Some(prior) = self.owner_prior.get_mut(&fixup.owner) {
                if prior.seq == fixup.seq {
                    if fixup.tip {
                        prior.spilled_tip_id = Some(spilled_tip);
                    }
                    if fixup.prompt_tip {
                        prior.spilled_prompt_tip_id = Some(spilled_tip);
                    }
                }
            }
        }
        self.persist_spill_index();
    }

    /// `spill_id` will not reach disk (a failed write, its deadline, no room after all, shutdown): give up its
    /// claims, count it, and settle the owners' prior-turn records as an unspilled eviction would have.
    fn fail_pending_spill(&mut self, pools: &mut BlockPools, spill_id: u64) {
        let Some(pending) = self.pending_spills.remove(&spill_id) else {
            return;
        };
        self.abort_spill_claims(pools, spill_id, &pending.claimed_keys);
        self.stats.spill_starts_dropped += 1;
        for fixup in pending.prior_fixups {
            if let Some(prior) = self.owner_prior.get_mut(&fixup.owner) {
                if prior.seq == fixup.seq
                    && prior.tip_id.is_some_and(|id| !self.tree.contains_node(id))
                    && prior.spilled_tip_id.is_none_or(|stip| !self.spilled_tree.contains_node(stip))
                {
                    prior.tail_toks.clear();
                }
            }
        }
    }

    fn collect_spill_results(&mut self, pools: &mut BlockPools) -> usize {
        let mut collected = 0usize;
        while let Some(done) = self.spill_writer.as_ref().and_then(|writer| writer.try_recv()) {
            collected += 1;
            match done {
                SpillIoDone::Block { key, raw } => self.on_spill_block_written(pools, key, raw),
                SpillIoDone::Unlink { result, .. } => {
                    if result.is_err() {
                        self.stats.spill_io_errors += 1;
                    }
                }
                SpillIoDone::Index { result } => {
                    self.spill_index_in_flight = false;
                    if result.is_err() {
                        self.stats.spill_io_errors += 1;
                    }
                }
            }
        }
        collected
    }

    /// Collect what the spill writer has finished since the last call: landed blocks give their pool slots
    /// back, spills whose last block landed commit, spills past their deadline are dropped, and a stale index
    /// is handed to the writer. Never waits for the writer. Returns the number of results collected.
    pub fn poll_spill_writes(&mut self, pools: &mut BlockPools) -> usize {
        if self.spill_writer.is_none() {
            return 0;
        }
        let collected = self.collect_spill_results(pools);
        if !self.pending_spills.is_empty() {
            let now_ms = self.now_ms();
            let mut expired: Vec<u64> =
                self.pending_spills.iter().filter(|(_, p)| now_ms >= p.deadline_ms).map(|(&id, _)| id).collect();
            expired.sort_unstable();
            for spill_id in expired {
                self.stats.spill_write_timeouts += 1;
                self.fail_pending_spill(pools, spill_id);
            }
        }
        self.flush_spill_index();
        collected
    }

    /// Inline spill: run what the eviction just queued on this thread and collect it, so the spill has landed
    /// (or failed) before the eviction returns.
    fn finish_spill_io_inline(&mut self, pools: &mut BlockPools) {
        if !self.spill_inline {
            return;
        }
        while self.spill_writer.as_ref().is_some_and(|writer| writer.run_queued(usize::MAX) > 0) {
            self.collect_spill_results(pools);
        }
    }

    /// Stop the spill writer for good. Queued writes are dropped unread and the one the writer holds is waited
    /// for, so that no write pin outlives this call; what has landed is committed, every other pending spill is
    /// counted as dropped, and the index is written. From here on spill disk work is inline.
    fn stop_spill_writer(&mut self, pools: &mut BlockPools) {
        let Some(writer) = self.spill_writer.as_mut() else {
            return;
        };
        let dropped = writer.stop();
        self.spill_inline = true;
        self.collect_spill_results(pools);
        self.spill_writer = None;
        for job in dropped {
            match job {
                SpillIo::Block { key, .. } => {
                    self.spill_key_owners.remove(&key);
                    self.forget_spill_key_mapping(key);
                    self.release_pending_write(pools, key);
                }
                SpillIo::Unlink { key } => {
                    if let Some(store) = self.spill_store.as_ref() {
                        if unlink_block_in_dir(store.dir(), key).is_err() {
                            self.stats.spill_io_errors += 1;
                        }
                    }
                }
                SpillIo::Index { .. } => {
                    self.spill_index_in_flight = false;
                    self.spill_index_dirty = self.spill_store.is_some();
                }
            }
        }
        let unread: Vec<SpillKey> = self.pending_writes.keys().copied().collect();
        for sk in unread {
            self.spill_key_owners.remove(&sk);
            self.forget_spill_key_mapping(sk);
            self.release_pending_write(pools, sk);
        }
        let mut pending: Vec<u64> = self.pending_spills.keys().copied().collect();
        pending.sort_unstable();
        for spill_id in pending {
            self.fail_pending_spill(pools, spill_id);
        }
        if self.spill_index_dirty || self.spill_index_in_flight {
            self.spill_index_dirty = false;
            self.spill_index_in_flight = false;
            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, bool)> {
        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.stats.restores_failed += 1;
                    self.remove_spilled_start(spill_id, true);
                    return None;
                }
            },
            ReadOutcome::Miss(_) => {
                self.stats.corrupt_fallbacks += 1;
                self.stats.restores_failed += 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);
            self.stats.restores_failed += 1;
            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, bool) {
        // 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 && self.entry_is_valid_kv(pools, BlockKind::Window, cw) => Some(cw),
                (Some(we), _) => Some(we),
                (None, Some(cw)) if self.entry_is_valid_kv(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;
        let published = !self.starts.contains_key(&tip);
        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,
                approx: false,
                scope: namespace,
                pos,
                cs,
                reasons,
                slot_bytes: Self::checkpoint_slot_bytes(pools, &final_entries),
                entries: final_entries,
                toks: prefix_toks.to_vec(),
                reuse: RecentReuse::default(),
                created_tick: None,
                last_used_tick: now,
                last_owner: 0,
                owner_turn: 0,
                last_used_ms: 0,
            };
            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, published)
    }

    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 = state.effective_prompt_len(toks.len());
        state.written = 0;
        state.stitched_approx = false;
        state.approx_path = false;
        state.bound_lane = Some(lane);
        state.save_owner_turn = 0;
        state.prompt_saved_pos = 0;
        state.prompt_saved_id = None;
        state.bound_start_id = None;
        Self::drop_turn_checkpoint(pools, state);
        state.turn_ckpt_miss = None;
        self.drop_lease_holds(state);
        state.reply_saved_pos = 0;
        state.reply_saved_id = None;
        state.tail_toks.clear();
        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.approx && st.namespace == namespace
                            && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
                    }
                    None => false,
                };
                if !all_live {
                    self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
                    in_ram = self.tree.deepest_start_in_namespace(namespace, search);
                }
            } else {
                in_ram.at = 0;
            }
        }

        // A returning turn of an approximate (stitched) lane resumes from its own saved work in the twin
        // namespace when that is deeper than every exact start, in RAM or spilled.
        let spilled_at = if self.spill_store.is_some() && !self.spilled_starts.is_empty() {
            self.spilled_tree.deepest_start_in_namespace(namespace, search).at
        } else {
            0
        };
        if let Some(bound) = self.bind_deeper_approx_start(pools, tbl, state, toks, in_ram.at.max(spilled_at)) {
            return AdmitBindOutcome::Immediate(Some(bound));
        }

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

        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, None));
        }
        let Some(&spill_id) = on_disk.blocks.last() else {
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
        };
        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, None));
        }
        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, None));
        };
        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, 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 AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
        }

        // 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);
                self.stats.restores_failed += 1;
                return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
            }
        };

        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 victim in victims {
            self.evict_ranked_victim(pools, victim, Some(&source), EvictCause::PoolPressure);
        }
        if self.evict_past_pending_spills(pools, need_win, need_full, in_ram.start, Some(&source)).is_err() {
            Self::release_restore_refs(pools, held_reused);
            self.unpin_inflight_restore_keys(spill_id, &protected_vec);
            self.stats.restores_failed += 1;
            return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
        }

        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);
                self.stats.restores_failed += 1;
                return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
            };
            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, None));
        }

        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 {
                match msg.payload {
                    RestoreMsgPayload::RecurrentState { key, raw }
                    | RestoreMsgPayload::Block { key, raw, .. }
                    | RestoreMsgPayload::Aborted { key, raw } => {
                        if let Some(store) = self.spill_store.as_mut() {
                            let _ = store.apply_raw_read(key, raw);
                        }
                    }
                    RestoreMsgPayload::Done { .. } => {}
                }
                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 (tip, published) = 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, published.then_some(tip))
                        } 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.stats.restores_failed += 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, None)
                        } 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.stats.restores_failed += 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, None)
                    } 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");
        }
    }

    /// 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
    }

    /// Pool bytes of a checkpoint's referenced slots, each charged at its own pool's stride (shared slots in full).
    fn checkpoint_slot_bytes(pools: &BlockPools, entries: &[(BlockKind, BlockIndex, BlockEntry)]) -> u64 {
        entries.iter().map(|(kind, _, _)| pools.of(*kind).stride_bytes()).fold(0u64, u64::saturating_add)
    }

    /// The start's rank under pool pressure: its cost is its host bytes plus the pool bytes of every slot it
    /// references (`select_eviction_victims` separately simulates what an eviction actually frees).
    fn eviction_rank(&self, sid: SealedId, st: &RetainedStart, leased: bool) -> EvictionRank {
        let mut rank = self.host_eviction_rank(sid, st, leased);
        rank.bytes = rank.bytes.saturating_add(st.slot_bytes);
        rank
    }

    /// The start's rank under host-budget pressure, which frees host bytes only.
    fn host_eviction_rank(&self, sid: SealedId, st: &RetainedStart, leased: bool) -> EvictionRank {
        let saved_tokens = st.reuse.saved_tokens(self.tick);
        EvictionRank {
            leased,
            live: self.tree.pin_count(sid) != 0,
            // A new, uncredited start gets one epoch to serve its first return; saving it again never renews that.
            recent: saved_tokens != 0
                || st.created_tick.is_some_and(|created| self.tick.saturating_sub(created) < REUSE_EPOCH_TICKS),
            saved_tokens,
            // Never zero, so cross-multiplied densities stay a strict weak order (a start always holds entries;
            // this only guards the sort against a degenerate record).
            bytes: st.host_bytes().max(1),
            last_used_tick: st.last_used_tick,
            pos: st.pos,
            sid,
        }
    }

    /// Evict a victim the ranking chose, counting it in `evictions_ranked_over_lru` when plain LRU would have kept it.
    fn evict_ranked_victim(
        &mut self,
        pools: &mut BlockPools,
        (sid, over_lru): (SealedId, bool),
        restore: Option<&RestoreSource>,
        cause: EvictCause,
    ) -> bool {
        let evicted = self.evict_start_inner(pools, sid, cause != EvictCause::ApproxScopeCap, restore, cause);
        if evicted && over_lru {
            self.stats.evictions_ranked_over_lru += 1;
        }
        evicted
    }

    /// Upfront check + minimal ranked 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 [`EvictionRank`]-ordered starts 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. Each victim carries whether plain LRU would have kept it:
    ///   it is not among the first as many starts, in LRU order, that could free a slot.
    fn select_eviction_victims(
        &self,
        pools: &BlockPools,
        need_win: usize,
        need_full: usize,
        protected_start: Option<SealedId>,
    ) -> Result<Vec<(SealedId, bool)>, CacheError> {
        // Free slots first: a span they already cover needs no victim, and each count stops once it has
        // enough. Only a kind that is short pays for the whole-pool reclaimable count (free slots are
        // reclaimable, so a kind that is not short cannot be exhausted).
        let mut sim_free = [pools.window.count_free_up_to(need_win), pools.full.count_free_up_to(need_full)];
        if sim_free[0] >= need_win && sim_free[1] >= need_full {
            return Ok(Vec::new());
        }
        if sim_free[0] < need_win && need_win > self.reclaimable_slots(pools, BlockKind::Window, protected_start) {
            return Err(CacheError::PoolExhausted(BlockKind::Window));
        }
        if sim_free[1] < need_full && need_full > self.reclaimable_slots(pools, BlockKind::Full, protected_start) {
            return Err(CacheError::PoolExhausted(BlockKind::Full));
        }

        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 leased = self.leased_starts();
        let lru = self.retain_lru;
        let mut cands: Vec<EvictionRank> = self
            .starts
            .iter()
            .filter(|(&sid, _)| Some(sid) != protected_start)
            .map(|(&sid, st)| self.eviction_rank(sid, st, leased.contains(&sid)))
            .collect();
        cands.sort_unstable_by(|a, b| a.compare(b, lru));

        let can_free_any = |sid: SealedId| {
            self.starts[&sid].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)
            })
        };
        let mut dropped: [HashMap<u32, u32>; 2] = [HashMap::new(), HashMap::new()];
        let mut victims = Vec::new();
        for cand in &cands {
            let sid = cand.sid;
            let st = &self.starts[&sid];
            if !can_free_any(sid) {
                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));
        }
        if lru {
            return Ok(victims.into_iter().map(|sid| (sid, false)).collect());
        }
        cands.sort_unstable_by(EvictionRank::lru_cmp);
        let lru_first: HashSet<SealedId> =
            cands.iter().map(|c| c.sid).filter(|&sid| can_free_any(sid)).take(victims.len()).collect();
        Ok(victims.into_iter().map(|sid| (sid, !lru_first.contains(&sid))).collect())
    }

    /// 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 {
        self.span_shortfall(pools, tbl, p0, t) == Some([0, 0])
    }

    /// How many slots `ensure_span_blocks(pools, tbl, p0, t)` lacks, `[Window, Full]`, after every free and
    /// evictable slot: `Some([0, 0])` exactly when the span can be satisfied now, `None` when the span lies
    /// outside the lane's table. Non-mutating.
    pub fn span_shortfall(&self, pools: &BlockPools, tbl: &BlockTable, p0: usize, t: usize) -> Option<[usize; 2]> {
        if t == 0 {
            return Some([0, 0]);
        }
        let lo_blk = p0 / BLOCK;
        let hi_blk = (p0 + t - 1) / BLOCK;
        let mut need = [0usize; 2];
        for b in lo_blk..=hi_blk {
            let bi = BlockIndex::new(b as u32);
            for kind in KINDS {
                if tbl.get(kind, bi).ok()?.is_none() {
                    need[kind_idx(kind)] += 1;
                }
            }
        }
        for kind in KINDS {
            let n = &mut need[kind_idx(kind)];
            if *n > 0 {
                *n = n.saturating_sub(self.reclaimable_slots(pools, kind, None));
            }
        }
        Some(need)
    }

    /// Slots only this lane keeps from other lanes, `[Window, Full]`: its table entries that no other lane and
    /// no restore references (retained start points may: they stay evictable). Releasing the lane makes exactly
    /// these free or evictable, and their rows are the work a later resume has to compute again.
    pub fn lane_exclusive_slots(&self, pools: &BlockPools, tbl: &BlockTable) -> [usize; 2] {
        let mut exclusive = [0usize; 2];
        for (_, e) in tbl.entries() {
            let ki = kind_idx(e.kind());
            let Ok(rec) = pools.of(e.kind()).record(e.slot()) else { continue };
            let held_by_starts = self.start_slot_refs[ki].get(e.slot().pool_index().get() as usize).copied().unwrap_or(0);
            if rec.generation() == e.generation() && rec.refs() == held_by_starts + 1 {
                exclusive[ki] += 1;
            }
        }
        exclusive
    }

    /// Index of `kind` in the `[Window, Full]` pairs [`Self::span_shortfall`] and [`Self::lane_exclusive_slots`] return.
    pub fn kind_slot(kind: BlockKind) -> usize {
        kind_idx(kind)
    }

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

    #[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>,
        cause: EvictCause,
    ) -> bool {
        let began_us = self.now_us();
        let Some(mut st) = self.starts.remove(&sid) else {
            return false;
        };
        self.unindex_retained_start_for_stitch(sid, st.namespace, &st.toks);
        if st.approx {
            if let Some(n) = self.approx_per_scope.get_mut(&st.scope) {
                *n = n.saturating_sub(1);
                if *n == 0 {
                    self.approx_per_scope.remove(&st.scope);
                }
            }
        }
        self.retained_host_bytes = self.retained_host_bytes.saturating_sub(st.host_bytes());
        // A spill is only queued here: the blocks it has to write are pinned for the spill writer before this
        // start's own references to them are dropped below, so none of them is free while it is being read.
        // An evicted start that asked for a spill ends in exactly one of `starts_spilled` and
        // `spill_starts_dropped`.
        let queued_spill = if allow_spill && self.spill_store.is_some() && !st.approx {
            let queued = self.queue_spill(pools, &mut st, restore);
            if queued.is_none() {
                self.stats.spill_starts_dropped += 1;
            }
            queued
        } else {
            None
        };
        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);
        // An owner's prior-turn record that named this start points at the spilled start once the spill has
        // landed (`commit_pending_spill`); if it never lands, `fail_pending_spill` settles the record instead.
        let mut prior_fixups: Vec<PriorFixup> = Vec::new();
        if let Some(owners) = self.prior_checkpoint_owners.get(&sid).cloned() {
            for owner in owners {
                if let Some(p) = self.owner_prior.get_mut(&owner) {
                    let (tip, prompt_tip) = (p.tip_id == Some(sid), p.prompt_tip_id == Some(sid));
                    if queued_spill.is_some() && (tip || prompt_tip) {
                        prior_fixups.push(PriorFixup { owner, seq: p.seq, tip, prompt_tip });
                    }
                    if p.prompt_tip_id == Some(sid) || p.reply_tip_id == Some(sid) {
                        p.evicted = true;
                    }
                    if !(queued_spill.is_some() && tip)
                        && p.tip_id.is_some_and(|id| !self.tree.contains_node(id))
                        && p.spilled_tip_id.is_none_or(|stip| !self.spilled_tree.contains_node(stip))
                    {
                        p.tail_toks.clear();
                    }
                }
            }
            if !self.tree.contains_node(sid) {
                self.prior_checkpoint_owners.remove(&sid);
            }
        }
        if let Some(pending) = queued_spill.and_then(|spill_id| self.pending_spills.get_mut(&spill_id)) {
            pending.prior_fixups = prior_fixups;
        }
        self.stats.start_points_evicted += 1;
        match cause {
            EvictCause::PoolPressure => self.stats.evictions_pool_pressure += 1,
            EvictCause::HostBudget => self.stats.evictions_host_budget += 1,
            EvictCause::ApproxScopeCap => self.stats.evictions_approx_scope_cap += 1,
            EvictCause::StaleInvalid => self.stats.evictions_stale_invalid += 1,
            EvictCause::Shutdown => self.stats.evictions_shutdown += 1,
            EvictCause::Superseded => self.stats.evictions_superseded += 1,
        }
        self.finish_spill_io_inline(pools);
        let took_us = self.now_us().saturating_sub(began_us);
        self.stats.evict_us_total = self.stats.evict_us_total.saturating_add(took_us);
        self.stats.evict_us_max = self.stats.evict_us_max.max(took_us);
        true
    }

    /// Free `need_win` and `need_full` slots when the victims already evicted did not. A victim whose spill is
    /// on its way to disk keeps the blocks being written until they land, so the pool is that much smaller for
    /// a moment: evict further LRU starts until the slots are free, or until nothing more can be evicted
    /// (`PoolExhausted`: the caller defers, and the slots come back as the writes land). With no spill write
    /// pending the earlier eviction freed what `select_eviction_victims` said it would, and this does nothing.
    fn evict_past_pending_spills(
        &mut self,
        pools: &mut BlockPools,
        need_win: usize,
        need_full: usize,
        protected_start: Option<SealedId>,
        restore: Option<&RestoreSource>,
    ) -> Result<(), CacheError> {
        while !self.pending_writes.is_empty() {
            let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
            if victims.is_empty() {
                break;
            }
            for victim in victims {
                self.evict_ranked_victim(pools, victim, restore, EvictCause::PoolPressure);
            }
        }
        Ok(())
    }

    /// Evict the LRU starts that free `need_win` and `need_full` slots (`select_eviction_victims`, then
    /// `evict_past_pending_spills`).
    fn evict_for_slots(
        &mut self,
        pools: &mut BlockPools,
        need_win: usize,
        need_full: usize,
        protected_start: Option<SealedId>,
    ) -> Result<(), CacheError> {
        let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
        for victim in victims {
            self.evict_ranked_victim(pools, victim, None, EvictCause::PoolPressure);
        }
        self.evict_past_pending_spills(pools, need_win, need_full, protected_start, None)
    }

    /// Evict `scope`'s least recently used approximate starts (never `protect`) while it holds more than
    /// `max_approx_starts_per_scope`. Scans only when the cap is exceeded.
    fn enforce_approx_scope_cap(&mut self, pools: &mut BlockPools, scope: u64, protect: Option<SealedId>) {
        while self.approx_per_scope.get(&scope).copied().unwrap_or(0) > self.max_approx_starts_per_scope {
            let leased = self.leased_starts();
            let cands: Vec<EvictionRank> = self
                .starts
                .iter()
                .filter(|(sid, st)| st.approx && st.scope == scope && Some(**sid) != protect)
                .map(|(&sid, st)| self.eviction_rank(sid, st, leased.contains(&sid)))
                .collect();
            let Some(victim) = pick_ranked_victim(&cands, self.retain_lru) else { break };
            if !self.evict_ranked_victim(pools, victim, None, EvictCause::ApproxScopeCap) {
                break;
            }
        }
    }

    #[cfg(any(test, standalone_blocks))]
    pub fn set_max_approx_starts_per_scope(&mut self, cap: usize) {
        self.max_approx_starts_per_scope = cap.max(1);
    }

    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 Some(victim) = self.host_trim_victim(protect_sid) else {
                break;
            };
            self.evict_ranked_victim(pools, victim, None, EvictCause::HostBudget);
        }
    }

    /// The start a host-budget trim evicts next (never `protect_sid` while the budget is above zero), ranked by
    /// [`Self::host_eviction_rank`], and whether plain LRU would have kept it.
    fn host_trim_victim(&self, protect_sid: Option<SealedId>) -> Option<(SealedId, bool)> {
        let leased = self.leased_starts();
        let cands: Vec<EvictionRank> = self
            .starts
            .iter()
            .filter(|(&sid, _)| !(protect_sid == Some(sid) && self.max_retained_host_bytes > 0))
            .map(|(&sid, st)| self.host_eviction_rank(sid, st, leased.contains(&sid)))
            .collect();
        pick_ranked_victim(&cands, self.retain_lru)
    }

    #[cfg(test)]
    fn evict_one_lru_start_inner(
        &mut self,
        pools: &mut BlockPools,
        allow_spill: bool,
        restore: Option<&RestoreSource>,
    ) -> bool {
        self.evict_one_lru_start_with_cause(pools, allow_spill, restore, EvictCause::PoolPressure)
    }

    fn evict_one_lru_start_with_cause(
        &mut self,
        pools: &mut BlockPools,
        allow_spill: bool,
        restore: Option<&RestoreSource>,
        cause: EvictCause,
    ) -> bool {
        let leased = self.leased_starts();
        // Evict Tier-0 unleased before Tier-1 leased, oldest LRU tick first; on a tie, deeper leaf before shared root.
        let victim = self
            .starts
            .iter()
            .filter(|(&sid, _)| !restore.is_some_and(|source| source.resident_start == Some(sid)))
            .min_by_key(|(sid, st)| (leased.contains(sid), st.last_used_tick, std::cmp::Reverse(st.pos)))
            .map(|(&sid, _)| sid);
        let Some(sid) = victim else {
            return false;
        };
        self.evict_start_inner(pools, sid, allow_spill, restore, cause)
    }

    /// 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 protected_start = restore.and_then(|r| r.resident_start);
        let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
        for victim in victims {
            self.evict_ranked_victim(pools, victim, restore, EvictCause::PoolPressure);
        }
        self.evict_past_pending_spills(pools, need_win, need_full, protected_start, 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 victim in victims {
                self.evict_ranked_victim(pools, victim, None, EvictCause::PoolPressure);
            }
            let still_win = deferred_after_eviction.iter().filter(|(kind, _)| *kind == BlockKind::Window).count();
            let still_full = deferred_after_eviction.len() - still_win;
            if let Err(err) = self.evict_past_pending_spills(pools, still_win, still_full, None, None) {
                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(err);
            }
            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;
        // An exact lane seals into its namespace; an approximate lane seals only on its `approx_path`,
        // into the twin `approx_namespace`, never into the exact chain.
        let sealing = !state.stitched_approx || state.approx_path;
        let seal_ns = if state.approx_path { approx_namespace(state.namespace, state.owner) } else { state.namespace };
        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 sealing && (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(seal_ns, 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;
                    }
                    // Never a stitch guard: the lane keeps the block it just computed, and the handle
                    // update below replaces the guard in the tree.
                    if let Some(canon_w) =
                        canon_w.filter(|&w| w != win_e && self.entry_is_valid_kv(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 on exact prefill lanes, and on approximate lanes only on their
        // `approx_path`, in the twin `approx_namespace`: exact `EntryTree` chains and exact `starts` stay 100% exact,
        // an approximate start is never a stitch donor (stitches never chain onto stitches), and it can serve only a
        // later request whose tokens exactly match its prefix. A stitched lane off the path still seals nothing.
        if sealing && end > 0 && end.is_multiple_of(BLOCK) && state.sealed.len() == end / BLOCK {
            let reasons = start_reasons(end, state.prompt_len, state.approx_path);
            if reasons != 0 {
                let tip = *state.sealed.last().unwrap();
                self.tick += 1;
                let now = self.tick;
                let lease_ms = self.card_lease.as_millis().min(u64::MAX as u128) as u64;
                let (save_turn, now_ms) = if lease_ms > 0 && state.owner != 0 && (reasons & PROMPT) != 0 {
                    (self.ensure_save_owner_turn(state), self.now_ms())
                } else {
                    (0, 0)
                };
                let can_claim_existing = save_turn != 0
                    && self
                        .starts
                        .get(&tip)
                        .is_some_and(|st| {
                            st.last_owner == state.owner || !self.is_start_leased_at(tip, st, now_ms, lease_ms)
                        });
                // Approximate starts are never spilled or stitch donors, so they never need their tokens.
                let keep_toks = (self.spill_store.is_some() || self.kv_stitch) && !state.approx_path;
                let mut check_host_budget = false;
                if let Some(existing) = self.starts.get_mut(&tip) {
                    existing.reasons |= reasons;
                    existing.last_used_tick = now;
                    if can_claim_existing {
                        existing.last_owner = state.owner;
                        existing.owner_turn = save_turn;
                        existing.last_used_ms = now_ms;
                    }
                    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);
                        if !existing.approx {
                            self.index_retained_start_for_stitch(tip);
                        }
                        check_host_budget = true;
                    }
                } else {
                    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));
                    }
                    if entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e)) {
                        let cs = read_cs();
                        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: seal_ns,
                            approx: state.approx_path,
                            scope: state.namespace,
                            pos: end,
                            cs,
                            reasons,
                            slot_bytes: Self::checkpoint_slot_bytes(pools, &entries),
                            entries,
                            toks: if keep_toks { toks[..end].to_vec() } else { Vec::new() },
                            reuse: RecentReuse::default(),
                            created_tick: Some(now),
                            last_used_tick: now,
                            last_owner: if save_turn != 0 { state.owner } else { 0 },
                            owner_turn: save_turn,
                            last_used_ms: now_ms,
                        };
                        self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
                        self.starts.insert(tip, st);
                        if state.approx_path {
                            // Never a stitch donor: stitches never chain onto stitches.
                            self.stats.approx_starts_saved += 1;
                            *self.approx_per_scope.entry(state.namespace).or_insert(0) += 1;
                            self.enforce_approx_scope_cap(pools, state.namespace, Some(tip));
                        } else {
                            self.index_retained_start_for_stitch(tip);
                            self.stats.start_points_saved += 1;
                        }
                        check_host_budget = true;
                    }
                }
                if (reasons & PROMPT) != 0 && end >= state.prompt_saved_pos && self.starts.contains_key(&tip) {
                    state.prompt_saved_pos = end;
                    state.prompt_saved_id = Some(tip);
                    self.hold_start(state, tip);
                }
                if check_host_budget {
                    self.enforce_retained_host_budget(pools, Some(tip));
                }
            }
        }
        if state.owner != 0 && end <= toks.len() {
            let sealed_end = state.sealed.len() * BLOCK;
            state.tail_toks.clear();
            if end >= sealed_end && end - sealed_end < BLOCK {
                state.tail_toks.extend_from_slice(&toks[sealed_end..end]);
            }
        }
        self.prune_expired_window(pools, tbl, p0, end);
    }

    /// Finish a prefill span that may have run through start-point checkpoints `ckpts` (in order, strictly inside the
    /// span, from [`span_checkpoints`]) as the spans the checkpoints used to split it into: each part ending at a
    /// checkpoint with the conv state the engine kept there (`read_kept(m)`, `m` rows into the span), and the last with
    /// the lane's state at the end (`read_cs`). The blocks, seals, start points and window pruning are exactly those the
    /// split steps made. Without a checkpoint it is [`Self::finish_prefill_span`].
    #[allow(clippy::too_many_arguments)]
    pub fn finish_prefill_span_through<F, G>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        p0: usize,
        t: usize,
        ckpts: &[usize],
        read_kept: G,
        read_cs: F,
    ) where
        F: FnOnce() -> Vec<u8>,
        G: Fn(usize) -> Vec<u8>,
    {
        let mut read_cs = Some(read_cs);
        for (lo, hi, at) in finish_parts(p0, t, ckpts) {
            match at {
                StateAt::Kept(m) => self.finish_prefill_span(pools, tbl, state, toks, lo, hi - lo, || read_kept(m)),
                StateAt::End => self.finish_prefill_span(pools, tbl, state, toks, lo, hi - lo, read_cs.take().unwrap()),
            }
        }
    }

    /// 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);
    }

    /// After a decode or verify step wrote up to position `pos`: seal every reply block completed since the
    /// lane's last sealed block into its twin [`approx_namespace`] chain, and, when `pos + 1` is a block boundary,
    /// keep the lane's `cs` there as its turn-end start. `toks` is the lane's committed history (prompt then
    /// generated tokens, `toks[p]` the token whose K/V `p` holds). Catching up from `state.sealed.len()` makes a
    /// DSpark verify step, which can cross a boundary without landing on it, seal what it completed too.
    /// An exact lane enters the twin first: decode-written K/V is not prefill-exact, so it never enters the
    /// exact chain, and the lane is approximate from here on. A no-op without `approx_retain` or an owner.
    pub fn seal_decode_block<F>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        pos: usize,
        read_cs: F,
    ) where
        F: FnOnce() -> Vec<u8>,
    {
        self.seal_verify_step(pools, tbl, state, toks, pos, None, read_cs);
    }

    /// Whether `state`'s lane keeps a turn-end start: the caller of [`Self::seal_verify_step`] reads a crossed
    /// boundary's `cs` (a 3.8 MB copy) only for a lane that does.
    pub fn keeps_turn_end_start(&self, state: &LaneBlockState) -> bool {
        self.approx_retain && state.owner != 0
    }

    /// [`Self::seal_decode_block`] for a DSpark verify step that kept positions up to `pos`. A step can cross a
    /// block boundary without ending on it, and the lane's `cs` is then already past the boundary: `crossed` is
    /// that boundary and the `cs` the step had there (`Engine::verify_cs_after`), and the turn-end checkpoint is
    /// taken at it. Without it a crossed boundary gets no checkpoint, and a reply that ends before a step lands
    /// on a later one leaves its start behind its last block.
    #[allow(clippy::too_many_arguments)]
    pub fn seal_verify_step<F>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
        toks: &[u32],
        pos: usize,
        crossed: Option<(usize, Vec<u8>)>,
        read_cs: F,
    ) where
        F: FnOnce() -> Vec<u8>,
    {
        let end = pos + 1;
        if !self.keeps_turn_end_start(state) || toks.len() < end {
            return;
        }
        debug_assert_ne!(approx_namespace(state.namespace, state.owner), state.namespace);
        // Seal the records of every completed block from the lane's sealed frontier to `end`.
        let mut done = state.sealed.len();
        let mut entries: Vec<(BlockEntry, BlockEntry)> = Vec::new();
        while (done + 1) * BLOCK <= end {
            let bi = BlockIndex::new(done as u32);
            let (Some(fe), Some(we)) =
                (tbl.get(BlockKind::Full, bi).ok().flatten(), tbl.get(BlockKind::Window, bi).ok().flatten())
            else {
                break;
            };
            let full = [(BlockKind::Full, fe), (BlockKind::Window, we)]
                .iter()
                .all(|&(kind, e)| pools.of(kind).record(e.slot()).is_ok_and(|r| r.length() == BLOCK as u32));
            if !full {
                break;
            }
            for (kind, e) in [(BlockKind::Full, fe), (BlockKind::Window, we)] {
                pools.of_mut(kind).record_mut(e.slot()).unwrap().seal();
            }
            entries.push((fe, we));
            done += 1;
        }
        if !state.approx_path {
            if entries.is_empty() {
                return;
            }
            state.stitched_approx = true;
            self.enter_approx_path(pools, tbl, state, toks);
            if !state.approx_path {
                return;
            }
        } else {
            let ns = approx_namespace(state.namespace, state.owner);
            for (fe, we) in entries {
                let b = state.sealed.len();
                let parent = if b == 0 { None } else { state.sealed.get(b - 1).copied() };
                let we_opt = self.entry_is_valid_kv(pools, BlockKind::Window, we).then_some(we);
                let Ok(id) = self.tree.insert_in_namespace(
                    ns,
                    parent,
                    b * BLOCK,
                    &toks[b * BLOCK..(b + 1) * BLOCK],
                    BlockHandles::new(fe, we_opt),
                ) else {
                    return;
                };
                if let Some(canon) = self.tree.handle(id) {
                    let full_stale = !self.entry_is_valid_kv(pools, BlockKind::Full, canon.full());
                    let win_stale = canon
                        .window()
                        .is_some_and(|cw| !self.entry_is_valid_kv(pools, BlockKind::Window, cw));
                    if full_stale || win_stale || (canon.window().is_none() && we_opt.is_some()) {
                        let best_f = if full_stale { fe } else { canon.full() };
                        let best_w = if win_stale || canon.window().is_none() { we_opt } else { canon.window() };
                        let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
                    }
                }
                if self.tree.pin(id).is_err() {
                    self.tree.prune_unreferenced(id);
                    return;
                }
                state.sealed.push(id);
            }
        }
        if state.owner != 0 && end <= toks.len() {
            let sealed_end = state.sealed.len() * BLOCK;
            state.tail_toks.clear();
            if end >= sealed_end && end - sealed_end < BLOCK {
                state.tail_toks.extend_from_slice(&toks[sealed_end..end]);
            }
        }
        // The step's block boundary: the one it ended on, or the one it crossed with the `cs` it had there.
        let boundary = if end >= BLOCK && end.is_multiple_of(BLOCK) {
            Some((end, None))
        } else {
            crossed
                .filter(|&(at, _)| at >= BLOCK && at.is_multiple_of(BLOCK) && at < end && end - at < BLOCK)
                .map(|(at, cs)| (at, Some(cs)))
        };
        if let Some((at, kept_cs)) = boundary {
            if state.sealed.len() * BLOCK >= at {
                let cs = kept_cs.unwrap_or_else(read_cs);
                self.take_turn_checkpoint(pools, tbl, state, at, cs);
            }
        }
    }

    /// Make `end` the lane's pending turn-end start: hold one reference on each Window block a start there
    /// binds, then let go of the checkpoint this one replaces. The lane's table has every one of those blocks
    /// now, live and sealed; if it does not, the lane is left with no checkpoint and the reason.
    fn take_turn_checkpoint(
        &mut self,
        pools: &mut BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
        end: usize,
        cs: Vec<u8>,
    ) {
        let mut window = Vec::with_capacity(WINDOW / BLOCK);
        let mut miss = None;
        for b in end.saturating_sub(WINDOW) / BLOCK..end / BLOCK {
            let bi = BlockIndex::new(b as u32);
            match tbl.get(BlockKind::Window, bi).ok().flatten() {
                Some(we) if self.entry_is_valid_kv(pools, BlockKind::Window, we) => window.push((bi, we)),
                Some(_) => miss = Some(TurnEndMiss::BlockNotLive),
                None => miss = Some(TurnEndMiss::BlockMissing),
            }
        }
        if miss.is_none() {
            for &(_, we) in &window {
                pools.window.record_mut(we.slot()).unwrap().add_ref().expect("hold turn checkpoint window block");
            }
            Self::drop_turn_checkpoint(pools, state);
            state.turn_ckpt_miss = None;
            state.turn_ckpt = Some(TurnCheckpoint { end, cs, window });
        } else {
            state.turn_ckpt_miss = miss;
        }
    }

    /// Let go of the lane's pending turn-end start and the Window references it holds.
    fn drop_turn_checkpoint(pools: &mut BlockPools, state: &mut LaneBlockState) {
        let Some(ckpt) = state.turn_ckpt.take() else { return };
        Self::release_turn_checkpoint_holds(pools, &ckpt.window);
    }

    fn release_turn_checkpoint_holds(pools: &mut BlockPools, window: &[(BlockIndex, BlockEntry)]) {
        for &(_, we) in window {
            let rec = pools.window.record_mut(we.slot()).expect("held window slot record");
            debug_assert_eq!(rec.generation(), we.generation(), "a held window slot is never retaken");
            if rec.generation() == we.generation() {
                rec.drop_ref().expect("drop turn checkpoint window hold");
            }
        }
    }

    /// The lane's turn ends: save its pending checkpoint (`state.turn_ckpt`) as an approximate start in its twin
    /// namespace, before the lane's table is cleared, and say what came of it. The checkpoint's Window holds are
    /// released on every path.
    fn retain_turn_end_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
    ) -> TurnEndStart {
        let ckpt = state.turn_ckpt.take();
        let miss = state.turn_ckpt_miss.take();
        // A start is due at the reply's last block boundary once decode steps completed a block past the prompt:
        // up to the prompt, prefill saved the lane's own start.
        let last_boundary = state.written / BLOCK * BLOCK;
        let due = self.keeps_turn_end_start(state) && last_boundary > state.prompt_len;
        let outcome = match ckpt {
            None if due => TurnEndStart::NotSaved(miss.unwrap_or(TurnEndMiss::NoCheckpoint)),
            None => TurnEndStart::NotDue,
            Some(TurnCheckpoint { end, cs, window }) => {
                let saved = self.save_turn_end_start(pools, tbl, state, end, cs, &window);
                Self::release_turn_checkpoint_holds(pools, &window);
                match saved {
                    Err(miss) => TurnEndStart::NotSaved(miss),
                    Ok(()) if end < last_boundary => TurnEndStart::NotSaved(TurnEndMiss::Behind),
                    Ok(()) => TurnEndStart::Saved,
                }
            }
        };
        match outcome {
            TurnEndStart::NotDue => {}
            TurnEndStart::Saved => self.stats.turn_end_starts_saved += 1,
            TurnEndStart::NotSaved(miss) => self.stats.turn_end_starts_not_saved[miss as usize] += 1,
        }
        outcome
    }

    /// Save a checkpoint (its boundary `end`, the `cs` there and the Window blocks it holds) as the lane's
    /// turn-end start. Holds the same refs and host bytes an exact start does; never spilled, never a donor.
    /// The Window blocks come from the checkpoint's hold: the lane's table may have pruned the oldest since.
    fn save_turn_end_start(
        &mut self,
        pools: &mut BlockPools,
        tbl: &BlockTable,
        state: &mut LaneBlockState,
        end: usize,
        cs: Vec<u8>,
        window: &[(BlockIndex, BlockEntry)],
    ) -> Result<(), TurnEndMiss> {
        if !self.approx_retain
            || !state.approx_path
            || state.owner == 0
            || end < BLOCK
            || !end.is_multiple_of(BLOCK)
            || state.sealed.len() * BLOCK < end
        {
            return Err(TurnEndMiss::OffPath);
        }
        let tip = state.sealed[end / BLOCK - 1];
        self.tick += 1;
        let now = self.tick;
        if self.starts.contains_key(&tip) {
            let (save_turn, now_ms) = if !self.card_lease.is_zero() && state.owner != 0 {
                (self.ensure_save_owner_turn(state), self.now_ms())
            } else {
                (0, 0)
            };
            if let Some(existing) = self.starts.get_mut(&tip) {
                existing.reasons |= PROMPT;
                existing.last_used_tick = now;
                if save_turn != 0 {
                    existing.last_owner = state.owner;
                    existing.owner_turn = save_turn;
                    existing.last_used_ms = now_ms;
                }
                state.reply_saved_pos = end;
                state.reply_saved_id = Some(tip);
            }
            return Ok(());
        }
        let mut entries = Vec::with_capacity(end / BLOCK + WINDOW / BLOCK);
        for b in 0..(end / BLOCK) {
            let bi = BlockIndex::new(b as u32);
            let Some(fe) = tbl.get(BlockKind::Full, bi).ok().flatten() else { return Err(TurnEndMiss::BlockMissing) };
            entries.push((BlockKind::Full, bi, fe));
        }
        entries.extend(window.iter().map(|&(bi, we)| (BlockKind::Window, bi, we)));
        if !entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e)) {
            return Err(TurnEndMiss::BlockNotLive);
        }
        for &(kind, _, e) in &entries {
            pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain turn-end start ref");
            self.inc_start_slot_ref(kind, e.slot());
        }
        self.tree.retain_start(tip).expect("retain turn-end start in EntryTree");
        let (save_turn, now_ms) = if !self.card_lease.is_zero() && state.owner != 0 {
            (self.ensure_save_owner_turn(state), self.now_ms())
        } else {
            (0, 0)
        };
        let st = RetainedStart {
            namespace: approx_namespace(state.namespace, state.owner),
            approx: true,
            scope: state.namespace,
            pos: end,
            cs,
            reasons: PROMPT,
            slot_bytes: Self::checkpoint_slot_bytes(pools, &entries),
            entries,
            toks: Vec::new(),
            reuse: RecentReuse::default(),
            created_tick: Some(now),
            last_used_tick: now,
            last_owner: if save_turn != 0 { state.owner } else { 0 },
            owner_turn: save_turn,
            last_used_ms: now_ms,
        };
        self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
        self.starts.insert(tip, st);
        state.reply_saved_pos = end;
        state.reply_saved_id = Some(tip);
        self.stats.approx_starts_saved += 1;
        *self.approx_per_scope.entry(state.namespace).or_insert(0) += 1;
        self.enforce_approx_scope_cap(pools, state.namespace, Some(tip));
        self.enforce_retained_host_budget(pools, Some(tip));
        Ok(())
    }

    /// `INK_RELEASE_SUPERSEDED_STARTS` (on by default in serve): when a turn completes, release the approximate starts its own chain
    /// passed through, the conversation's earlier turns. The turn's prompt-end and turn-end starts stay, and they
    /// hold every `Full` block of the chain, so no K/V is lost. What goes is each earlier start's `cs` copy and
    /// its trailing `Window` blocks.
    ///
    /// A start pins `WINDOW / BLOCK` (16) `Window` slots whatever the K/V mode, a card saves two a turn, and
    /// binding one refreshes every older start of its chain, so they never age out on their own. Left alone a
    /// chain pins about one `Window` slot for each `Full` slot it adds, at five times the bytes: no byte split of
    /// the pool covers that. On 2026-12-02 (M5 Max, 24 lanes, `--kv8`, a 64 GiB pool of 1,966 window and 54,796
    /// full slots) 214 starts, about 9 a card, wanted 3,424 window slots and held all but 2 while 63% of the full
    /// slots sat free; pool pressure evicted 1,093 starts, the only useful start of cards waiting on a tool
    /// among them.
    ///
    /// Only the lane's own chain is touched (`state.sealed`), and only below a start this turn keeps. Another
    /// conversation under the same card id, every exact start, and the chain of a turn that was cancelled or
    /// never finished its prompt (its retry may need the turn before) are left to the LRU.
    /// specs/KvWindowPins.tla (`ChainPinsBounded`, `CompletedTurnKeepsItsStart`, `CancelledTurnKeepsItsStart`).
    fn release_superseded_turn_starts(&mut self, pools: &mut BlockPools, state: &LaneBlockState, cancelled: bool) {
        if !self.release_superseded_starts
            || cancelled
            || !state.approx_path
            || state.owner == 0
            || state.written < state.prompt_len
        {
            return;
        }
        let ns = approx_namespace(state.namespace, state.owner);
        let keep = [state.prompt_saved_id, state.reply_saved_id];
        // The deepest start this turn keeps in the twin, and only when it is on this lane's chain.
        let Some(kept_blocks) = keep
            .iter()
            .flatten()
            .filter_map(|sid| {
                let st = self.starts.get(sid)?;
                let blocks = st.pos / BLOCK;
                (st.approx && st.namespace == ns && blocks > 0 && state.sealed.get(blocks - 1) == Some(sid))
                    .then_some(blocks)
            })
            .max()
        else {
            return;
        };
        let superseded: Vec<SealedId> = state.sealed[..kept_blocks - 1]
            .iter()
            .copied()
            .filter(|sid| {
                !keep.contains(&Some(*sid)) && self.starts.get(sid).is_some_and(|st| st.approx && st.namespace == ns)
            })
            .collect();
        for sid in superseded {
            self.evict_start_inner(pools, sid, false, None, EvictCause::Superseded);
        }
    }

    /// Release a conversation's earlier approximate starts when its turn completes
    /// (`INK_RELEASE_SUPERSEDED_STARTS`, on by default). Off (`=0`): every start stays until the LRU evicts it.
    pub fn set_release_superseded_starts(&mut self, enabled: bool) {
        self.release_superseded_starts = enabled;
    }

    #[cfg(test)]
    pub fn release_superseded_starts_enabled(&self) -> bool {
        self.release_superseded_starts
    }

    /// `INK_RETAIN_LRU=1`: evict retained starts by plain LRU under the card lease ([`EvictionRank::lru_cmp`]).
    pub fn set_retain_lru(&mut self, lru: bool) {
        self.retain_lru = lru;
    }

    #[cfg(test)]
    pub fn retain_lru_enabled(&self) -> bool {
        self.retain_lru
    }

    /// 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).
    #[cfg(test)]
    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);
    }

    /// Execute post-verify draft release, retained block-length update, sliding-window retirement,
    /// committed-head validation, and dirty GPU block-table upload through the single shared
    /// [`crate::blocks::finalize_verify_blocks_at`] production helper.
    #[allow(clippy::too_many_arguments)]
    pub fn finish_verify_span_and_sync<D>(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        allocated: &[(BlockKind, BlockIndex)],
        p0: usize,
        n_keep: usize,
        sync_dirty: D,
    ) -> Result<VerifyBlockFinalize, String>
    where
        D: FnMut(BlockKind, &BlockPool, &mut BlockTable) -> Result<usize, String>,
    {
        let committed_len = p0 + n_keep;
        let fin = crate::blocks::finalize_verify_blocks_at(
            pools,
            tbl,
            allocated,
            p0,
            committed_len,
            EXT,
            BLOCK,
            |_, _, _| {},
            sync_dirty,
        )?;
        if n_keep > 0 {
            state.written = fin.committed_len;
        }
        self.stats.window_pruned += fin.window_pruned;
        Ok(fin)
    }

    /// Slice-backed wrapper around [`Self::finish_verify_span_and_sync`] for CPU/unit fixtures.
    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn finish_verify_span_to_slices(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        allocated: &[(BlockKind, BlockIndex)],
        p0: usize,
        n_keep: usize,
        full_dst: &mut [u64],
        win_dst: &mut [u64],
    ) -> Result<VerifyBlockFinalize, String> {
        self.finish_verify_span_and_sync(pools, tbl, state, allocated, p0, n_keep, |kind, pool, tbl| match kind {
            BlockKind::Full => tbl.sync_dirty_to_slice(kind, pool, full_dst).map_err(|e| format!("{e}")),
            BlockKind::Window => tbl.sync_dirty_to_slice(kind, pool, win_dst).map_err(|e| format!("{e}")),
        })
    }

    /// 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.approx || 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();
            }
            let window = &pools.window;
            self.stitch_guards.retain(|&(s, g)| window.record(s).is_ok_and(|r| r.generation() == g && r.refs() > 0));
            self.stitch_guards.push((w_slot, w_gen));
            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;
        }
        if self.evict_for_slots(pools, need_win, n_stitch_blks, None).is_err() {
            return StitchStartOutcome::PoolBusy;
        }
        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,
                toks: toks.to_vec(),
                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()
                        && self.evict_for_slots(pools, need_win, 0, None).is_err()
                    {
                        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);
                    // Same provenance as a RAM stitch: the lane seals into its twin from here on.
                    self.enter_approx_path(pools, tbl, state, &ps.toks);
                    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
                        || st.approx
                        || 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 && self.evict_for_slots(pools, need_win, 0, Some(sid)).is_err() {
                    return StitchApplyOutcome::PoolBusy;
                }
                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
                        || st.approx
                        || 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
                };
                if self.evict_for_slots(pools, need_win, n_stitch_blks, Some(sid)).is_err() {
                    return StitchApplyOutcome::PoolBusy;
                }
                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;
                }
                if self.evict_for_slots(pools, need_win, n_stitch_blks, None).is_err() {
                    return StitchApplyOutcome::PoolBusy;
                }
                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);
        // With `approx_retain`, the now-approximate lane seals into its twin namespace from here on, so the
        // same card's next turn can resume from this turn's work.
        self.enter_approx_path(pools, tbl, state, toks);
        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) {
        self.release_lane_with_toks(pools, tbl, state, None, false);
    }

    /// Release a lane taken off the GPU by KV pool preemption: retain any completed decode checkpoint and refresh
    /// its soft lease, without evicting earlier starts as superseded or recording an intermediate `OwnerPriorTurn`.
    pub fn release_lane_preempted(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
    ) -> TurnEndStart {
        self.release_lane_inner(pools, tbl, state, None, false, true)
    }

    /// [`Self::release_lane`] with the lane's committed tokens, saving its turn-end start first. Returns what
    /// came of that start.
    pub fn release_lane_with_toks(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        committed_toks: Option<&[u32]>,
        cancelled: bool,
    ) -> TurnEndStart {
        self.release_lane_inner(pools, tbl, state, committed_toks, cancelled, false)
    }

    fn release_lane_inner(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
        committed_toks: Option<&[u32]>,
        cancelled: bool,
        preempted: bool,
    ) -> TurnEndStart {
        if let Some(lane_idx) = state.bound_lane.take() {
            self.cancel_ikv_stage(pools, lane_idx);
        }
        let turn_end = self.retain_turn_end_start(pools, tbl, state);
        self.release_superseded_turn_starts(pools, state, cancelled || preempted);
        self.settle_lease_at_release(state, cancelled);
        tbl.clear_entries(pools).expect("clear lane block table");
        let sealed_snapshot = std::mem::take(&mut state.sealed);
        let tip = sealed_snapshot.last().copied();
        for &id in &sealed_snapshot {
            self.tree.unpin(id);
        }
        if let Some(tip) = tip {
            self.tree.prune_unreferenced(tip);
        }
        if !preempted
            && state.owner != 0
            && state.written > 0
            && (state.written >= state.prompt_len || !self.owner_prior.contains_key(&state.owner))
        {
            let live_pos_and_tip = sealed_snapshot
                .iter()
                .enumerate()
                .rev()
                .find(|&(_, &id)| self.tree.contains_node(id))
                .map(|(idx, &id)| ((idx + 1) * BLOCK, id));
            let (live_chain_len, live_tip) = match live_pos_and_tip {
                Some((len, id)) => (len, Some(id)),
                None => (0, None),
            };
            let prompt_tip_id = state.prompt_saved_id.filter(|&id| self.tree.contains_node(id));
            let reply_tip_id = state.reply_saved_id.filter(|&id| self.tree.contains_node(id));
            let prompt_saved_pos = if prompt_tip_id.is_some() { state.prompt_saved_pos } else { 0 };
            let reply_saved_pos = if reply_tip_id.is_some() { state.reply_saved_pos } else { 0 };
            let (tail_toks, total_len, truncated_tail) = match committed_toks {
                Some(toks) if toks.len() >= live_chain_len => {
                    let rem = toks.len() - live_chain_len;
                    let take_n = rem.min(BLOCK - 1);
                    (
                        toks[live_chain_len..live_chain_len + take_n].to_vec(),
                        toks.len(),
                        rem >= BLOCK,
                    )
                }
                _ => {
                    if live_chain_len == sealed_snapshot.len() * BLOCK && state.tail_toks.len() < BLOCK {
                        let tail = std::mem::take(&mut state.tail_toks);
                        let tlen = live_chain_len + tail.len();
                        (tail, state.written.max(tlen), state.written > tlen)
                    } else {
                        (Vec::new(), state.written.max(live_chain_len), state.written > live_chain_len)
                    }
                }
            };
            if !self.owner_prior.contains_key(&state.owner) && self.owner_prior.len() >= MAX_OWNER_PRIOR_ENTRIES {
                if let Some((&oldest_owner, _)) = self.owner_prior.iter().min_by_key(|(_, v)| v.seq) {
                    if let Some(evicted_prior) = self.owner_prior.remove(&oldest_owner) {
                        self.unregister_prior_checkpoint_ids(oldest_owner, &evicted_prior);
                    }
                }
            }
            let seq = self.next_owner_prior_seq;
            self.next_owner_prior_seq = self.next_owner_prior_seq.saturating_add(1);
            let new_prior = OwnerPriorTurn {
                seq,
                prompt_saved_pos,
                prompt_len: state.prompt_len,
                reply_saved_pos,
                total_len,
                prompt_tip_id,
                reply_tip_id,
                tip_id: live_tip,
                spilled_tip_id: None,
                spilled_prompt_tip_id: None,
                tail_toks,
                truncated_tail,
                evicted: state.prompt_saved_pos > prompt_saved_pos || state.reply_saved_pos > reply_saved_pos,
            };
            if let Some(old_prior) = self.owner_prior.insert(state.owner, new_prior) {
                self.unregister_prior_checkpoint_ids(state.owner, &old_prior);
            }
            if let Some(cur_prior) = self.owner_prior.get(&state.owner).cloned() {
                self.register_prior_checkpoint_ids(state.owner, &cur_prior);
            }
        }
        state.namespace = 0;
        state.prompt_len = 0;
        state.written = 0;
        state.stitched_approx = false;
        state.approx_path = false;
        state.owner = 0;
        state.side_call = false;
        state.save_owner_turn = 0;
        state.prompt_saved_pos = 0;
        state.prompt_saved_id = None;
        state.bound_start_id = None;
        state.reply_saved_pos = 0;
        state.reply_saved_id = None;
        state.tail_toks.clear();
        state.observed_prior = ObservedPrior::default();
        state.internal_resume = false;
        state.resume_reply_tokens = 0;
        self.stats.lanes_released += 1;
        turn_end
    }

    /// Release a lane whose step gave invalid logits (NaN or infinite), keeping nothing of it for a later request.
    ///
    /// The K/V the lane wrote, or the K/V it read, holds the values that made those logits, and attention does not
    /// cancel them: a masked row is read with a zero weight, and zero times NaN is NaN. A start point kept over
    /// such blocks would hand them to the next request with the same prefix, which would fail the same way, every
    /// time, until the start happened to be evicted. So the lane keeps no turn-end start and no lease, and every
    /// retained start that shares a block with it is evicted without spilling (the spill store never receives
    /// suspect K/V). Starts that share no block with the lane stay. Returns how many starts were evicted.
    ///
    /// A block another in-flight lane still holds stays alive under that lane, which reads the same values and
    /// fails here in its turn.
    ///
    /// The idea is from chadlyb/erisinky a317c508 (Chad, GPL-3.0-or-later), whose single-session engine zeroes its
    /// K/V caches and drops its session and snapshot after invalid logits, "so the next request starts clean".
    pub fn release_lane_invalid(
        &mut self,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        state: &mut LaneBlockState,
    ) -> usize {
        let key = |kind: BlockKind, e: BlockEntry| (kind_idx(kind) as u8, e.slot().get(), e.generation());
        let mut suspect: HashSet<(u8, u32, u32)> = tbl.entries().map(|(_, e)| key(e.kind(), e)).collect();
        if let Some(ckpt) = &state.turn_ckpt {
            suspect.extend(ckpt.window.iter().map(|&(_, we)| key(BlockKind::Window, we)));
        }
        Self::drop_turn_checkpoint(pools, state);
        state.turn_ckpt_miss = Some(TurnEndMiss::OffPath);
        self.release_lane_with_toks(pools, tbl, state, None, true);
        // deepest first, then least recently used: a fixed order, whatever order the map yields them in
        let mut victims: Vec<(std::cmp::Reverse<usize>, u64, SealedId)> = self
            .starts
            .iter()
            .filter(|(_, st)| st.entries.iter().any(|&(kind, _, e)| suspect.contains(&key(kind, e))))
            .map(|(&sid, st)| (std::cmp::Reverse(st.pos), st.last_used_tick, sid))
            .collect();
        victims.sort_by_key(|&(pos, tick, _)| (pos, tick));
        let mut evicted = 0;
        for (_, _, sid) in victims {
            if self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid) {
                evicted += 1;
            }
        }
        let mut pending_victims: Vec<u64> = self
            .pending_spills
            .iter()
            .filter(|(_, pending)| {
                pending
                    .claimed_keys
                    .iter()
                    .any(|sk| self.spill_key_to_entry.get(sk).is_some_and(|ek| suspect.contains(ek)))
            })
            .map(|(&spill_id, _)| spill_id)
            .collect();
        pending_victims.sort_unstable();
        for spill_id in pending_victims {
            self.fail_pending_spill(pools, spill_id);
        }
        evicted
    }

    /// 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);
        self.stop_spill_writer(pools);
        while self.evict_one_lru_start_with_cause(pools, false, None, EvictCause::Shutdown) {}
        let window = &pools.window;
        self.stitch_guards.retain(|&(s, g)| window.record(s).is_ok_and(|r| r.generation() == g && r.refs() > 0));
        self.latest_owner_turn.clear();
        self.owner_prior.clear();
        self.prior_checkpoint_owners.clear();
    }
}

#[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 !self.entry_is_valid_kv(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;
                        }
                    }
                }
            }
            if let Some(ckpt) = &st.turn_ckpt {
                for &(_, we) in &ckpt.window {
                    if self.is_stitch_guard(we) || !entry_is_live_sealed(pools, BlockKind::Window, we) {
                        all_lane_entries_live = false;
                    }
                    table_win_refs[we.slot().pool_index().get() as usize] += 1;
                }
            }
            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;
    mod spill_writer;
    #[cfg(not(standalone_blocks))]
    mod file_reuse;
    mod turn_end_start;

    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);
                        }
                    }
                }
                ServeStepPlan::Mixed { .. } => unreachable!("mixed_steps defaults to false"),
            }
            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 disk read barrier on this spill dir so lane 1 stays held inside its cold
        // SSD read while unrelated Ready lane 0 executes 8 non-blocking decode steps.
        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 e = entered.0.lock().unwrap();
            let (_guard, timeout) = entered
                .1
                .wait_timeout_while(e, crate::serve::TEST_HANG_GUARD, |entered| !*entered)
                .unwrap();
            assert!(!timeout.timed_out(), "hang guard: background restore worker did not enter read");
        }

        // Run 8 decode steps on Ready lane 0 while lane 1 is held on `release` inside its cold SSD read:
        // completing all 8 steps before `release` opens proves `poll_restores` and planning never block on I/O.
        for dec_pos in 64usize..72 {
            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());
        }
        assert!(!*release.0.lock().unwrap(), "restore barrier stayed closed across all 8 decode steps");

        // 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 began = Instant::now();
        let mut finished = None;
        while began.elapsed() < crate::serve::TEST_HANG_GUARD {
            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 { prompt_len: 64, ..Default::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);
    }

    // ---- Approximate reuse: a returning turn resumes from its own conversation's saved work ----

    /// A conversation's twin in auth namespace `ns`, as serve derives it from the secret salt and the card id.
    fn own(ns: u64, card: &str) -> u64 {
        approx_twin("test-salt", ns, Some(card))
    }

    /// A donor prompt whose file span a later conversation's prompt contains at another offset, so that
    /// conversation's lane stitches (becomes approximate). Returns the shared file span.
    fn seed_stitch_donor(cache: &mut ServeBlockCache, pools: &mut BlockPools, ns: u64, kvb: u32) -> Vec<u32> {
        seed_stitch_donor_span(cache, pools, ns, kvb, 3200)
    }

    /// [`seed_stitch_donor`] with a file span of `span_len` tokens (`span_len + 385` a block multiple plus one).
    fn seed_stitch_donor_span(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        ns: u64,
        kvb: u32,
        span_len: u32,
    ) -> Vec<u32> {
        let file_span: Vec<u32> = (0..span_len).map(|i| 10_000 + i).collect();
        let mut prompt_a: Vec<u32> = (0..128u32).map(|i| 1_000 + i).collect();
        prompt_a.extend_from_slice(&file_span);
        prompt_a.extend((0..257u32).map(|i| 40_000 + i));
        let whole = prompt_a.len() / BLOCK;
        assert_eq!(prompt_a.len(), whole * BLOCK + 1, "the donor prompt ends one token past a block boundary");
        let mut tbl = BlockTable::new(128).unwrap();
        let mut st = LaneBlockState { namespace: ns, prompt_len: prompt_a.len(), ..Default::default() };
        for b in 0..whole {
            let p0 = b * BLOCK;
            cache.ensure_span_blocks(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(), &prompt_a[p0..p0 + BLOCK], kvb);
            cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt_a, p0, BLOCK, || fake_cs(0x11));
        }
        cache.ensure_span_blocks(pools, &mut tbl, whole * BLOCK, 1).unwrap();
        cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt_a, whole * BLOCK, 1, || fake_cs(0x12));
        cache.release_lane(pools, &mut tbl, &mut st);
        file_span
    }

    /// Turn 1 of conversation `owner` in `ns`: a prompt that stitches from the donor, prefilled to the end, then
    /// `reply_len` decoded tokens with `seal_decode_block` as serve calls it. Returns (prompt, reply).
    fn stitched_turn_one(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        ns: u64,
        owner: u64,
        file_span: &[u32],
        reply_len: usize,
    ) -> (Vec<u32>, Vec<u32>) {
        let mut prompt: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
        prompt.extend_from_slice(file_span); // [147 .. 3347)
        prompt.extend((0..2817u32).map(|i| 60_000 + i)); // 6164 tokens
        let mut tbl = BlockTable::new(160).unwrap();
        let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
        assert!(cache.match_and_bind(pools, &mut tbl, &mut st, &prompt).is_none(), "turn 1 starts cold");
        let plans = cache.plan_stitches(pools, ns, &prompt, 0);
        assert_eq!(plans.len(), 1, "turn 1 stitches the donor's file span");
        cache.ensure_span_blocks(pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
        cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, 0, plans[0].stitch_start, || fake_cs(0x31));
        let out = cache.apply_stitch_plan(pools, &mut tbl, &mut st, &prompt, &plans[0]);
        assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
        assert!(st.stitched_approx);
        let mut p = st.written;
        while p < prompt.len() {
            let next = effective_pf_target(p, prompt.len());
            cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
            cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, p, next - p, || fake_cs((next / BLOCK) as u8));
            p = next;
        }
        let reply: Vec<u32> = (0..reply_len as u32).map(|i| 70_000 + i).collect();
        let mut history = prompt.clone();
        for (d, &tok) in reply.iter().enumerate() {
            let pos = prompt.len() + d;
            history.push(tok);
            cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(pools, &tbl, &mut st, &history, pos, || fake_cs(0x77));
        }
        cache.release_lane(pools, &mut tbl, &mut st);
        (prompt, reply)
    }

    fn turn_two(prompt: &[u32], reply: &[u32]) -> Vec<u32> {
        let mut t = prompt.to_vec();
        t.extend_from_slice(reply);
        t.extend((0..300u32).map(|i| 80_000 + i)); // the tool result
        t
    }

    #[test]
    fn stitched_turn_resumes_from_its_own_saved_work_with_stitch_on() {
        // Red on v2.0.4 (`approx_retain` off reproduces it exactly): a stitched lane saves nothing, so its
        // returning turn binds no start at all and re-prefills everything.
        for approx_retain in [false, true] {
            let kvb = 1u32;
            let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_kv_stitch(true);
            cache.set_approx_retain(approx_retain);
            let ns = 7;
            let file_span = seed_stitch_donor(&mut cache, &mut pools, ns, kvb);
            let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, ns, own(ns, "card-a"), &file_span, 100);
            let t2 = turn_two(&prompt, &reply);
            let mut tbl = BlockTable::new(160).unwrap();
            let mut st = LaneBlockState { namespace: ns, owner: own(ns, "card-a"), ..Default::default() };
            let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2);
            if !approx_retain {
                assert!(bound.is_none(), "v2.0.4: a stitched turn leaves nothing to resume from");
                cache.release_lane(&mut pools, &mut tbl, &mut st);
                cache.shutdown(&mut pools);
                assert_zero_pool_leaks(&pools);
                continue;
            }
            let (at, cs) = bound.expect("turn 2 resumes from turn 1's own saved work");
            // Turn 1's prompt (6164) and reply (100) end at 6264; the reply's last whole block ends at 6208.
            assert_eq!(at, 6208, "the credit covers turn 1's prompt and its reply up to the last full block");
            assert_eq!(cs, fake_cs(0x77), "the start carries the reply boundary's cs");
            assert!(at >= prompt.len(), "credit covers the whole of turn 1's prompt");
            assert!(st.stitched_approx && st.approx_path, "a resumed lane is approximate and keeps sealing in its twin");
            let new_tokens = t2.len() - prompt.len() - reply.len();
            let rows_to_prefill = t2.len() - at;
            assert!(rows_to_prefill <= new_tokens + BLOCK, "turn 2 prefills its new tokens (+ < 1 block of reply)");
            let s = cache.stats();
            assert_eq!(s.approx_start_matches, 1);
            assert_eq!(s.approx_cached_tokens_total, at as u64);
            assert_eq!(s.cached_tokens_total, 0, "exact cached tokens never count an approximate resume");
            assert_eq!(s.approx_starts_saved, 2, "the twin keeps PROMPT and the turn end only, never EVERY");
            let mut approx_pos: Vec<usize> = cache.starts.values().filter(|s| s.approx).map(|s| s.pos).collect();
            approx_pos.sort_unstable();
            assert_eq!(approx_pos, vec![6144, 6208], "an approximate lane retains only its PROMPT and turn-end starts");
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    #[test]
    fn approximate_starts_are_bound_to_owner_and_auth_scope_and_never_exact() {
        let kvb = 1u32;
        // (case, turn 2's owner, turn 2's namespace, approx_retain for turn 2, may it resume turn 1's work)
        let cases: [(&str, u64, u64, bool, bool); 5] = [
            ("same conversation, same key", own(7, "card-a"), 7, true, true),
            ("another conversation in the same namespace", own(7, "card-b"), 7, true, false),
            ("the same conversation under another key", own(8, "card-a"), 8, true, false),
            ("no conversation header", 0, 7, true, false),
            ("exact mode (no approximate reuse)", own(7, "card-a"), 7, false, false),
        ];
        for (name, owner, ns2, approx_retain2, expect) in cases {
            let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_kv_stitch(true);
            cache.set_approx_retain(true);
            let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
            let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
            let t2 = turn_two(&prompt, &reply);
            cache.set_approx_retain(approx_retain2);
            let mut tbl = BlockTable::new(160).unwrap();
            let mut st = LaneBlockState { namespace: ns2, owner, ..Default::default() };
            let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2);
            let approx = bound.is_some() && st.stitched_approx;
            assert_eq!(approx, expect, "{name}");
            if !expect {
                assert!(!st.approx_path, "{name}: never an approximate start");
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    #[test]
    fn approximate_saves_stay_out_of_the_exact_chain_and_are_never_stitch_donors() {
        let kvb = 1u32;
        let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
        let exact_before = cache.starts.values().filter(|s| !s.approx).count();
        let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
        assert_eq!(cache.starts.values().filter(|s| !s.approx).count(), exact_before, "no exact start from a stitched lane");
        assert_eq!(cache.tree.deepest_start_in_namespace(7, &prompt).at, 0, "an exact lookup never finds turn 1's work");
        assert!(cache.starts.values().any(|s| s.approx), "turn 1 saved approximate starts");
        for bucket in cache.stitch_index.values() {
            for (sid, _) in bucket {
                assert!(!cache.starts.get(sid).is_some_and(|s| s.approx), "an approximate start is never a donor");
            }
        }
        let t2 = turn_two(&prompt, &reply);
        let mut tbl = BlockTable::new(160).unwrap();
        let mut st = LaneBlockState { namespace: 7, owner: own(7, "card-a"), ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2).is_some());
        assert!(st.stitched_approx && st.approx_path);
        let at = st.written;
        cache.ensure_span_blocks(&mut pools, &mut tbl, at, t2.len() - at).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &t2, at, t2.len() - at, || fake_cs(0x99));
        assert_eq!(cache.tree.deepest_start_in_namespace(7, &t2).at, 0, "turn 2's work stays out of the exact chain");
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    /// Two lanes of one conversation, admitted cold together, whose prompts share a donor's file span to
    /// different depths: lane A's holds all 4,096 tokens of it (`[147 .. 4243)`), lane B's leaves it at 2,880.
    /// Both stitch from 1,216. A heals from 2,688 and holds its zero `Window` guard across blocks `26 .. 42`.
    /// B heals from 1,344, so B's healing ramp `[1344 .. 2880)` prefills those same blocks itself.
    struct SiblingStitch {
        pools: BlockPools,
        cache: ServeBlockCache,
        prompt_a: Vec<u32>,
        prompt_b: Vec<u32>,
        tbl_a: BlockTable,
        st_a: LaneBlockState,
        tbl_b: BlockTable,
        st_b: LaneBlockState,
        guard_a: BlockEntry,
        guard_b: BlockEntry,
    }

    fn sibling_lanes_stitched_to_different_depths() -> SiblingStitch {
        let kvb = 1u32;
        let ns = 7;
        let owner = own(ns, "card-a");
        let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        let file_span = seed_stitch_donor_span(&mut cache, &mut pools, ns, kvb, 4096);
        let mut prompt_a: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
        prompt_a.extend_from_slice(&file_span);
        prompt_a.extend((0..2817u32).map(|i| 60_000 + i));
        let mut prompt_b: Vec<u32> = prompt_a[..2880].to_vec();
        prompt_b.extend((0..600u32).map(|i| 90_000 + i));

        let mut tbl_a = BlockTable::new(160).unwrap();
        let mut st_a = LaneBlockState { namespace: ns, owner, prompt_len: prompt_a.len(), ..Default::default() };
        let mut tbl_b = BlockTable::new(160).unwrap();
        let mut st_b = LaneBlockState { namespace: ns, owner, prompt_len: prompt_b.len(), ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a).is_none(), "lane A starts cold");
        assert!(cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b, &prompt_b).is_none(), "lane B starts cold");
        let plans_a = cache.plan_stitches(&pools, ns, &prompt_a, 0);
        let plans_b = cache.plan_stitches(&pools, ns, &prompt_b, 0);
        assert_eq!((plans_a.len(), plans_b.len()), (1, 1));
        assert_eq!((plans_a[0].stitch_start, plans_a[0].heal_start, plans_a[0].span_end), (1216, 2688, 4243));
        assert_eq!((plans_b[0].stitch_start, plans_b[0].heal_start, plans_b[0].span_end), (1216, 1344, 2880));

        // Each prefills the left ramp `[0 .. 1216)` as an exact lane, then stitches and enters the twin.
        for (tbl, st, prompt, plan) in
            [(&mut tbl_a, &mut st_a, &prompt_a, &plans_a[0]), (&mut tbl_b, &mut st_b, &prompt_b, &plans_b[0])]
        {
            cache.ensure_span_blocks(&mut pools, tbl, 0, plan.stitch_start).unwrap();
            cache.finish_prefill_span(&mut pools, tbl, st, prompt, 0, plan.stitch_start, || fake_cs(0x31));
            let out = cache.apply_stitch_plan(&mut pools, tbl, st, prompt, plan);
            assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
            assert!(st.stitched_approx && st.approx_path, "a stitched lane seals into its conversation's twin");
        }
        assert_eq!((st_a.written, st_b.written), (2688, 1344));

        // A guard is one zero-filled, sealed, live `Window` slot bound across the stitched blocks of the
        // lane's trailing window: `26 .. 42` for lane A, `19 .. 21` for lane B.
        let win = |tbl: &BlockTable, b: u32| tbl.get(BlockKind::Window, BlockIndex::new(b)).unwrap();
        let guard_a = win(&tbl_a, 41).expect("lane A's guard");
        let guard_b = win(&tbl_b, 20).expect("lane B's guard");
        assert_ne!(guard_a, guard_b);
        for b in 0..42u32 {
            assert_eq!(win(&tbl_a, b), (b >= 26).then_some(guard_a), "lane A window block {b}");
        }
        assert_eq!(win(&tbl_b, 19), Some(guard_b));
        for g in [guard_a, guard_b] {
            assert!(entry_is_live_sealed(&pools, BlockKind::Window, g));
            assert!(pools.window.slot_bytes(g.slot()).unwrap().iter().all(|&x| x == 0), "a guard slot is zeros");
        }
        // The two twin chains are the same nodes as far as the prompts agree.
        assert_eq!((st_a.sealed.len(), st_b.sealed.len()), (42, 21));
        assert_eq!(st_a.sealed[..21], st_b.sealed[..]);
        SiblingStitch { pools, cache, prompt_a, prompt_b, tbl_a, st_a, tbl_b, st_b, guard_a, guard_b }
    }

    /// The byte lane B stamps across each `Window` block it computes.
    const LANE_B_WINDOW: u8 = 0xB1;

    impl SiblingStitch {
        /// Lane B prefills `blocks` of its healing ramp, one block a step, stamping the `Window` K/V it computes.
        fn lane_b_heals(&mut self, blocks: std::ops::Range<usize>) {
            for b in blocks {
                let (p0, bi) = (b * BLOCK, BlockIndex::new(b as u32));
                self.cache.ensure_span_blocks(&mut self.pools, &mut self.tbl_b, p0, BLOCK).unwrap();
                let own = self.tbl_b.get(BlockKind::Window, bi).unwrap().expect("lane B's own window block");
                self.pools.window.slot_bytes_mut(own.slot()).unwrap().fill(LANE_B_WINDOW);
                let (tbl, st) = (&mut self.tbl_b, &mut self.st_b);
                self.cache.finish_prefill_span(&mut self.pools, tbl, st, &self.prompt_b, p0, BLOCK, || fake_cs(0x41));
            }
        }

        /// Lane B's `Window` entry for block `b`, which must be the K/V lane B computed and what the twin names.
        fn assert_lane_b_reads_its_own_window(&self, b: usize) {
            let bi = BlockIndex::new(b as u32);
            let we = self.tbl_b.get(BlockKind::Window, bi).unwrap().expect("a live window block");
            assert_ne!(we, self.guard_a, "block {b}: lane B bound lane A's zero guard slot");
            assert!(
                self.pools.window.slot_bytes(we.slot()).unwrap().iter().all(|&x| x == LANE_B_WINDOW),
                "block {b}: lane B reads Window K/V it did not compute"
            );
            let twin = self.cache.tree.handle(self.st_b.sealed[b]).expect("lane B's twin block");
            assert_eq!(twin.window(), Some(we), "block {b}: the twin names the K/V lane B computed");
        }

        fn release_both_and_check_leaks(mut self) {
            self.cache.release_lane(&mut self.pools, &mut self.tbl_a, &mut self.st_a);
            self.cache.release_lane(&mut self.pools, &mut self.tbl_b, &mut self.st_b);
            self.cache.shutdown(&mut self.pools);
            assert_zero_pool_leaks(&self.pools);
        }
    }

    #[test]
    fn a_stitch_never_publishes_its_zero_guard_slot_as_a_tree_window_handle() {
        // Red before the fix: `enter_approx_path` stored the lane's table entry as each twin block's `Window`
        // handle, and after a stitch that entry is the guard, so blocks 19 and 20 named lane B's guard and
        // blocks `26 .. 42` lane A's. `finish_prefill_span` binds a live canonical `Window` handle in place
        // of a lane's own block, so the handle must be K/V some lane computed for that block.
        let s = sibling_lanes_stitched_to_different_depths();
        for (b, &id) in s.st_a.sealed.iter().enumerate() {
            let h = s.cache.tree.handle(id).expect("a pinned twin block");
            assert_ne!(h.window(), Some(s.guard_a), "block {b}: lane A's zero guard is published as its Window K/V");
            assert_ne!(h.window(), Some(s.guard_b), "block {b}: lane B's zero guard is published as its Window K/V");
            // The stitched `Full` K/V is published as before: the twin still covers the stitched span.
            let fe = s.tbl_a.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().expect("lane A full block");
            assert_eq!(h.full(), fe, "block {b}: lane A's Full block is the twin's");
        }
        // Each lane still reads its own guard: what a stitch publishes changes, not the stitch.
        for b in 26..42u32 {
            assert_eq!(s.tbl_a.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), Some(s.guard_a));
        }
        for b in 19..21u32 {
            assert_eq!(s.tbl_b.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), Some(s.guard_b));
        }
        s.release_both_and_check_leaks();
    }

    #[test]
    fn a_lane_healing_across_a_siblings_stitch_guard_keeps_its_own_window_kv() {
        // Red before the fix: sealing block 26, lane B found lane A's guard as the block's live canonical
        // `Window` handle and bound it in place of the K/V it had just computed, and so on through block 41.
        // At 2,880, where B's prompt leaves A's, 13 of the 16 blocks in B's window were zeros.
        let mut s = sibling_lanes_stitched_to_different_depths();
        s.lane_b_heals(21..45);
        // Lane A has not moved: it still holds its guard, and the guard is still live.
        assert_eq!(s.st_a.written, 2688);
        assert!(entry_is_live_sealed(&s.pools, BlockKind::Window, s.guard_a));
        // Lane B is where its prompt leaves lane A's. Its tail and its reply read `Window` blocks `29 ..= 44`.
        assert_eq!(s.st_b.written, 2880);
        assert_eq!(s.prompt_a[..2880], s.prompt_b[..2880]);
        assert_ne!(s.prompt_a[2880], s.prompt_b[2880]);
        let first_live = (s.st_b.written - (WINDOW - 1)) / BLOCK;
        assert_eq!(first_live, 29);
        for b in first_live..45 {
            s.assert_lane_b_reads_its_own_window(b);
        }
        s.release_both_and_check_leaks();
    }

    #[test]
    fn a_sealing_lane_never_binds_a_stitch_guard_the_tree_names() {
        // The second check, with the tree as the old publish left it: lane A's guard named as block 26's
        // `Window` handle. A lane sealing block 26 keeps the block it computed and replaces the guard in the
        // tree. Red without the guard test in `finish_prefill_span`.
        let mut s = sibling_lanes_stitched_to_different_depths();
        let node = s.st_a.sealed[26];
        let full = s.cache.tree.handle(node).expect("lane A's twin block 26").full();
        assert!(s.cache.tree.set_handle(node, BlockHandles::new(full, Some(s.guard_a))));
        s.lane_b_heals(21..27);
        assert_eq!(s.st_b.sealed[26], node, "lane B sealed the block lane A published");
        s.assert_lane_b_reads_its_own_window(26);
        s.release_both_and_check_leaks();
    }

    #[test]
    fn a_stitch_guard_never_enters_retained_starts_turn_end_starts_or_spills() {
        // Red before the fix: when `apply_stitch_plan` runs with a short healing ramp (`prompt_ckpt - heal_start`
        // `< WINDOW`), `finish_prefill_span` at `prompt_ckpt` and `retain_turn_end_start` at a block-aligned reply
        // boundary both saw the live sealed zero guard in `tbl[Window, win_lo .. heal_blk]` and retained an
        // approximate start whose `entries` pinned and bound the zero guard slot.
        let kvb = 1u32;
        let ns = 7;
        let owner = own(ns, "card-short");
        let dir = ScratchDir::new("stitch-guard-spill");
        let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, kvb).unwrap();
        let mut pools = BlockPools::with_capacities(256, 128, kvb).unwrap();
        let mut cache = ServeBlockCache::with_spill(store);
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);

        let file_span = seed_stitch_donor_span(&mut cache, &mut pools, ns, kvb, 3200);
        let (&donor_sid, _) = cache
            .starts
            .iter()
            .find(|(_, s)| !s.approx && s.pos == 3584)
            .expect("donor PROMPT start at 3584");

        // Prompt length 2561 (`prompt_ckpt == 2560 = 40 * 64`). Stitching `[1024 .. 2048)` leaves blocks
        // `16 .. 32` bound to the zero guard, so at `prompt_ckpt = 2560` (`win_lo = 24`) blocks `24 .. 32`
        // in `tbl` are still the zero guard slot.
        let mut prompt: Vec<u32> = (0..128u32).map(|i| 3_000 + i).collect();
        prompt.extend_from_slice(&file_span[..2433]);
        assert_eq!(prompt.len(), 2561);
        let plan = StitchSpanPlan {
            span_start: 128,
            stitch_start: 1024,
            heal_start: 2048,
            span_end: 2561,
            source: StitchSource::Retained { sid: donor_sid, src_start: 1024 },
        };

        let mut tbl = BlockTable::new(128).unwrap();
        let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plan.stitch_start).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, plan.stitch_start, || fake_cs(0x31));
        let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &prompt, &plan);
        assert!(matches!(out, StitchApplyOutcome::Applied { stitched_tokens: 1024, .. }));
        let guard = tbl.get(BlockKind::Window, BlockIndex::new(31)).unwrap().expect("stitch guard at block 31");
        assert!(pools.window.slot_bytes(guard.slot()).unwrap().iter().all(|&x| x == 0));

        for b in 32..40usize {
            let p0 = b * BLOCK;
            cache.ensure_span_blocks(&mut pools, &mut tbl, p0, BLOCK).unwrap();
            let we = tbl.get(BlockKind::Window, BlockIndex::new(b as u32)).unwrap().unwrap();
            pools.window.slot_bytes_mut(we.slot()).unwrap().fill(LANE_B_WINDOW);
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, p0, BLOCK, || fake_cs(0x42));
        }
        assert_eq!(st.written, 2560);
        for s in cache.starts.values() {
            assert!(
                s.entries.iter().all(|&(_, _, e)| e != guard),
                "a PROMPT start at 2560 must never retain a zero stitch guard slot"
            );
        }

        // Prefill the 1-token prompt tail and decode 63 reply tokens to complete block 40 at `end = 2624`,
        // where `win_lo = 25` and blocks `25 .. 32` still hold `guard`.
        cache.ensure_span_blocks(&mut pools, &mut tbl, 2560, 1).unwrap();
        let we40 = tbl.get(BlockKind::Window, BlockIndex::new(40)).unwrap().unwrap();
        pools.window.slot_bytes_mut(we40.slot()).unwrap().fill(LANE_B_WINDOW);
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 2560, 1, || fake_cs(0x43));

        let mut hist = prompt.clone();
        for i in 0..63u32 {
            let pos = 2561 + i as usize;
            hist.push(80_000 + i);
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist, pos, || fake_cs(0x44));
        }
        assert_eq!(st.written, 2624);
        cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&hist), false);

        for s in cache.starts.values() {
            assert!(
                s.entries.iter().all(|&(_, _, e)| e != guard),
                "a turn-end start at 2624 must never retain a zero stitch guard slot"
            );
        }
        for (_, h) in cache.tree.entries() {
            assert_ne!(h.window(), Some(guard), "EntryTree must never hold a zero stitch guard handle");
        }
        assert_eq!(
            pools.window.record(guard.slot()).unwrap().refs(),
            0,
            "once the stitched lane releases, zero references to its guard slot may remain"
        );
        assert!(cache.spilled_starts.is_empty(), "an approximate lane never spills to SSD");

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

    #[test]
    fn exact_lane_reply_is_sealed_and_resumed_by_its_next_turn() {
        // Without stitching: on v2.0.4 the next turn resumes at turn 1's PROMPT start only (8256) and re-prefills
        // the whole reply; with approximate reuse it resumes past the reply's last full block.
        for approx_retain in [false, true] {
            let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(approx_retain);
            let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
            let mut tbl = BlockTable::new(512).unwrap();
            let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
            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;
            }
            let mut history = turn1.clone();
            for d in 0..200u32 {
                let pos = turn1.len() + d as usize;
                history.push(90_000 + d);
                cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
                cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
                cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x55));
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            let mut turn2 = history.clone();
            turn2.extend((0..140u32).map(|i| 60000 + i));
            let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
            let (at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &turn2).expect("a start");
            if approx_retain {
                // 8266 + 200 = 8466; the reply's last full block ends at 8448.
                assert_eq!(at, 8448, "the next turn resumes past the reply");
                assert!(st2.stitched_approx, "decode-written K/V makes the resumed lane approximate");
            } else {
                assert_eq!(at, 8256, "v2.0.4: only turn 1's PROMPT start");
                assert!(!st2.stitched_approx);
            }
            // The exact chain still serves turn 1's prompt exactly, to anyone in the namespace.
            assert_eq!(cache.tree.deepest_start_in_namespace(0, &turn2).at, 8256);
            cache.release_lane(&mut pools, &mut tbl, &mut st2);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    // ---- Window slots: a completed turn releases its conversation's earlier starts (specs/KvWindowPins.tla) ----

    /// One card turn on its own lane: bind, prefill to the prompt's end in the spans serve plans, decode
    /// `reply_len` tokens with `seal_decode_block` as serve calls it, and stop before the release.
    struct CardTurn {
        tbl: BlockTable,
        st: LaneBlockState,
        history: Vec<u32>,
        resumed_at: usize,
    }

    fn card_turn_open(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        ns: u64,
        owner: u64,
        prompt: &[u32],
        reply_len: usize,
    ) -> CardTurn {
        let mut tbl = BlockTable::new(2048).unwrap();
        let mut st = LaneBlockState { namespace: ns, owner, ..Default::default() };
        let resumed_at = cache.match_and_bind(pools, &mut tbl, &mut st, prompt).map_or(0, |(at, _)| at);
        let mut p = resumed_at;
        while p < prompt.len() {
            let next = effective_pf_target(p, prompt.len());
            cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
            cache.finish_prefill_span(pools, &mut tbl, &mut st, prompt, p, next - p, || fake_cs(1));
            p = next;
        }
        let mut history = prompt.to_vec();
        for _ in 0..reply_len {
            let pos = history.len();
            history.push(0x4000_0000 | pos as u32);
            cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(pools, &tbl, &mut st, &history, pos, || fake_cs(2));
        }
        CardTurn { tbl, st, history, resumed_at }
    }

    fn card_turn_close(cache: &mut ServeBlockCache, pools: &mut BlockPools, mut turn: CardTurn, cancelled: bool) -> Vec<u32> {
        cache.release_lane_with_toks(pools, &mut turn.tbl, &mut turn.st, Some(&turn.history), cancelled);
        turn.history
    }

    /// A whole turn. Returns (where it resumed, the history its next turn extends).
    fn card_turn(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        owner: u64,
        prompt: &[u32],
        reply_len: usize,
    ) -> (usize, Vec<u32>) {
        let turn = card_turn_open(cache, pools, 0, owner, prompt, reply_len);
        let resumed_at = turn.resumed_at;
        (resumed_at, card_turn_close(cache, pools, turn, false))
    }

    fn start_positions(cache: &ServeBlockCache, approx: bool) -> Vec<usize> {
        let mut pos: Vec<usize> = cache.starts.values().filter(|s| s.approx == approx).map(|s| s.pos).collect();
        pos.sort_unstable();
        pos
    }

    fn extended(history: &[u32], new_tokens: usize, tag: u32) -> Vec<u32> {
        let mut prompt = history.to_vec();
        prompt.extend((0..new_tokens as u32).map(|i| tag + i));
        prompt
    }

    #[test]
    fn completed_turn_releases_its_conversations_earlier_starts_and_no_kv() {
        // (supersede, approximate starts after turns 2 and 3)
        let cases: [(bool, [&[usize]; 2]); 2] =
            [(true, [&[9536, 9664], &[10560, 10688]]), (false, [&[8448, 9536, 9664], &[8448, 9536, 9664, 10560, 10688]])];
        let mut used = Vec::new();
        for (supersede, want) in cases {
            let mut pools = BlockPools::records_only_with_capacities(512, 256, 1).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(true);
            cache.set_release_superseded_starts(supersede);
            let card = own(0, "card-a");
            // Turn 1 is exact: EVERY starts to 8192 and its PROMPT start at 8256; the reply's last full block ends at 8448.
            let turn1: Vec<u32> = (0..8266u32).map(|i| 1_000 + i).collect();
            let (at1, h1) = card_turn(&mut cache, &mut pools, card, &turn1, 200);
            assert_eq!(at1, 0);
            assert_eq!(start_positions(&cache, false), [2048, 4096, 6144, 8192, 8256]);
            assert_eq!(start_positions(&cache, true), [8448], "turn 1's turn-end start");
            // Turn 2 resumes past turn 1's reply, saves its PROMPT start at 9536 and its turn-end start at 9664.
            let (at2, h2) = card_turn(&mut cache, &mut pools, card, &extended(&h1, 1100, 200_000), 150);
            assert_eq!(at2, 8448);
            assert_eq!(start_positions(&cache, true), want[0], "supersede {supersede}");
            let turn3 = extended(&h2, 900, 300_000);
            let (at3, h3) = card_turn(&mut cache, &mut pools, card, &turn3, 100);
            assert_eq!(at3, 9664);
            assert_eq!(start_positions(&cache, true), want[1], "supersede {supersede}");
            assert_eq!(start_positions(&cache, false), [2048, 4096, 6144, 8192, 8256], "exact starts are the LRU's");
            assert_eq!(cache.stats().evictions_superseded, if supersede { 3 } else { 0 });
            assert_eq!(cache.stats().evictions_pool_pressure, 0);
            used.push((cache.pool_occupancy(&pools, BlockKind::Window).0, cache.pool_occupancy(&pools, BlockKind::Full).0));

            // What a card's next request can be still resumes where it did: the same prompt again (a retry) at
            // the turn's PROMPT start, and its continuation past the reply.
            let mut tbl = BlockTable::new(2048).unwrap();
            let mut st = LaneBlockState { owner: card, ..Default::default() };
            assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn3).map(|(at, _)| at), Some(10560));
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            let (at4, _) = card_turn(&mut cache, &mut pools, card, &extended(&h3, 500, 400_000), 0);
            assert_eq!(at4, 10688);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
        // The earlier turns' windows are released (16 slots each where they do not overlap); every Full block stays.
        let [(win_on, full_on), (win_off, full_off)] = used[..] else { unreachable!() };
        assert_eq!(full_on, full_off, "the kept starts hold the whole chain");
        assert_eq!(full_off, 10688 / BLOCK);
        // Exact starts at 2048..8192 (16 each) and 8256 (one more block), then one window ending at 10688
        // (PROMPT 10560 and turn-end 10688 overlap: 18 blocks). Left alone, turn 1's turn-end start pins 3 more
        // and turn 2's two starts 16 more.
        assert_eq!(win_on, 4 * 16 + 1 + 18);
        assert_eq!(win_off, win_on + 3 + 16);
    }

    #[test]
    fn superseded_starts_are_only_the_completed_turns_own_chain() {
        let mut pools = BlockPools::records_only_with_capacities(512, 256, 1).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_approx_retain(true);
        cache.set_release_superseded_starts(true);
        let card = own(0, "card-a");
        let turn1: Vec<u32> = (0..8266u32).map(|i| 1_000 + i).collect();
        let (_, h1) = card_turn(&mut cache, &mut pools, card, &turn1, 200);
        let (_, h2) = card_turn(&mut cache, &mut pools, card, &extended(&h1, 1100, 200_000), 150);
        assert_eq!(start_positions(&cache, true), [9536, 9664]);

        // A cancelled turn keeps the turn before it: its retry, or an edited last message, may resume there.
        let turn3 = extended(&h2, 900, 300_000);
        let open = card_turn_open(&mut cache, &mut pools, 0, card, &turn3, 100);
        assert_eq!(open.resumed_at, 9664);
        card_turn_close(&mut cache, &mut pools, open, true);
        assert_eq!(start_positions(&cache, true), [9536, 9664, 10560, 10688], "a cancelled turn releases nothing");
        assert_eq!(cache.stats().evictions_superseded, 1);
        // Its retry completes: bound at the cancelled turn's PROMPT start, it releases everything below.
        let (at3, h3) = card_turn(&mut cache, &mut pools, card, &turn3, 100);
        assert_eq!(at3, 10560);
        assert_eq!(start_positions(&cache, true), [10560, 10688]);
        assert_eq!(cache.stats().evictions_superseded, 3);

        // A turn that ends before its prompt is prefilled (a failed step) is not a completed turn either, though
        // the start it bound sits at its prompt checkpoint.
        let unfinished = extended(&h3, 20, 0x0045_0000);
        let mut tbl = BlockTable::new(2048).unwrap();
        let mut st = LaneBlockState { owner: card, ..Default::default() };
        assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &unfinished).map(|(at, _)| at), Some(10688));
        assert!(st.prompt_saved_id.is_some() && st.written < st.prompt_len);
        cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, None, false);
        assert_eq!(start_positions(&cache, true), [10560, 10688]);
        assert_eq!(cache.stats().evictions_superseded, 3);

        // A second conversation under the same card id (the twin is per card) that leaves the first at turn 1's
        // prompt end: it is another chain in the same twin, and neither conversation's turn releases the other's.
        let sibling1 = extended(&turn1, 700, 500_000);
        let (at_s1, hs1) = card_turn(&mut cache, &mut pools, card, &sibling1, 100);
        assert_eq!(at_s1, 8256, "the sibling starts from turn 1's exact PROMPT start");
        assert_eq!(start_positions(&cache, true), [9024, 10560, 10688]);
        let (at4, h4) = card_turn(&mut cache, &mut pools, card, &extended(&h3, 500, 400_000), 70);
        assert_eq!(at4, 10688);
        assert_eq!(start_positions(&cache, true), [9024, 11200, 11264], "the sibling's start outlives the first's turn");
        let (at_s2, _) = card_turn(&mut cache, &mut pools, card, &extended(&hs1, 300, 600_000), 0);
        assert_eq!(at_s2, 9024);
        let (at5, _) = card_turn(&mut cache, &mut pools, card, &extended(&h4, 200, 700_000), 0);
        assert_eq!(at5, 11264);

        // A request with no card id, and a card with approximate reuse off, save no approximate start to release.
        let before = cache.stats().evictions_superseded;
        let other: Vec<u32> = (0..3000u32).map(|i| 800_000 + i).collect();
        let (_, ho) = card_turn(&mut cache, &mut pools, 0, &other, 200);
        let (at_o, _) = card_turn(&mut cache, &mut pools, 0, &extended(&ho, 300, 900_000), 0);
        assert_eq!(at_o, 2944, "an anonymous turn resumes at its exact PROMPT start");
        assert_eq!(cache.stats().evictions_superseded, before);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    /// 2026-12-02, M5 Max 128 GB, 24 lanes, `--kv8 -c 131072`, `INK_KV_POOL_BYTES=64GiB`, sparse sketch on:
    /// 1,966 window + 54,796 full slots. Thirty minutes in: 1,964 window slots used, 20,094 full slots used,
    /// 214 retained starts, 1,093 starts evicted for pool pressure, no admission deferred.
    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn kv8_64_gib_window_slots_are_not_held_by_earlier_turns_while_full_slots_are_free() {
        const LANES: usize = 24;
        const ROUNDS: usize = 7;
        const IDLE_FROM: usize = 3; // card 0 waits on a tool from this round on, while the other 23 keep working
        #[cfg(not(standalone_blocks))]
        let (n_window, n_full) = {
            let gib = 1u64 << 30;
            crate::engine::Engine::plan_serve_block_pools_for(
                64 * gib,
                crate::blocks::KVB_KV8,
                4096,
                131_072,
                LANES,
                64 * gib,
                15,
                true,
                true,
            )
            .unwrap()
        };
        #[cfg(standalone_blocks)]
        let (n_window, n_full) = (1_966usize, 54_796usize);
        assert_eq!((n_window, n_full), (1_966, 54_796), "the 64 GiB --kv8 pool of 2026-12-02");
        // 24 lanes at rest hold 17 window blocks each; the other 1,558 slots were held by retained starts alone.
        assert_eq!(n_window - LANES * 17, 1_558);

        let mut seen = Vec::new();
        for supersede in [false, true] {
            let mut pools = BlockPools::records_only_with_capacities(n_full, n_window, crate::blocks::KVB_KV8).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(true);
            cache.set_max_retained_host_bytes(28 << 30);
            cache.set_release_superseded_starts(supersede);
            // Every card shares the system prompt and tools (4,224 tokens), then has its own task.
            let shared: Vec<u32> = (0..4_224u32).map(|i| 1_000 + i).collect();
            let mut history: Vec<Vec<u32>> = (0..LANES as u32).map(|c| extended(&shared, 876, (c + 1) << 20)).collect();
            let mut open: Vec<Option<CardTurn>> = (0..LANES).map(|_| None).collect();
            let mut card0_turn_end = 0usize;
            for round in 0..ROUNDS {
                for c in 0..LANES {
                    // Finish the turn in flight (a 134-token reply), then start the next: 800 new prompt tokens.
                    if let Some(turn) = open[c].take() {
                        history[c] = card_turn_close(&mut cache, &mut pools, turn, false);
                        history[c] = extended(&history[c], 800, ((c as u32 + 1) << 20) | ((round as u32) << 12));
                    }
                    if c == 0 && round >= IDLE_FROM {
                        continue;
                    }
                    let turn = card_turn_open(&mut cache, &mut pools, 0, own(0, &format!("card-{c}")), &history[c], 134);
                    if c == 0 {
                        card0_turn_end = (turn.history.len() / BLOCK) * BLOCK;
                    }
                    open[c] = Some(turn);
                }
            }
            let (win_used, win_cap) = cache.pool_occupancy(&pools, BlockKind::Window);
            let (full_used, full_cap) = cache.pool_occupancy(&pools, BlockKind::Full);
            let stats = cache.stats();
            // Card 0's tool returns: its next turn extends the history its last turn left.
            let back = card_turn_open(&mut cache, &mut pools, 0, own(0, "card-0"), &history[0], 0);
            let starts = cache.retained_start_count();
            // What the lanes and the retained starts want, were no two windows to overlap.
            let wanted = LANES * 17 + starts * (WINDOW / BLOCK);
            seen.push((win_used, full_used, stats.evictions_pool_pressure, starts, back.resumed_at));
            assert_eq!((win_cap, full_cap), (1_966, 54_796));
            assert_eq!(stats.admit_deferred_pool_pressure, 0);
            if supersede {
                assert_eq!(back.resumed_at, card0_turn_end, "card 0 resumes where its last turn ended");
                assert_eq!(stats.evictions_pool_pressure, 0, "no start is evicted for a window slot");
                assert!(win_used * 100 <= win_cap * 75, "window slots {win_used} of {win_cap}");
                assert!(stats.evictions_superseded > 0);
                // A card keeps its turn's two starts, the two of the turn before while the next is in flight,
                // and its first turn's exact starts.
                assert!(starts <= 5 * LANES, "{starts} starts");
                assert!(wanted <= win_cap + LANES * 2, "{wanted} window slots wanted of {win_cap}");
            } else {
                // The default is 2026-12-02's pattern (214 starts, about 9 a card, wanting 3,424 window slots of
                // 1,966): the window pool is full, most of the full pool is free, starts are evicted for pool
                // pressure, and the waiting card has lost its saved work.
                assert!(starts >= 8 * LANES, "{starts} starts");
                assert!(wanted > win_cap * 3 / 2, "{wanted} window slots wanted of {win_cap}");
                assert!(win_used + 16 > win_cap, "window slots {win_used} of {win_cap}");
                assert!(full_used * 100 < full_cap * 40, "full slots {full_used} of {full_cap}");
                assert!(stats.evictions_pool_pressure > 0);
                assert!(back.resumed_at < card0_turn_end, "card 0 resumed at {} of {card0_turn_end}", back.resumed_at);
            }
            card_turn_close(&mut cache, &mut pools, back, true);
            for turn in open.into_iter().flatten() {
                card_turn_close(&mut cache, &mut pools, turn, true);
            }
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
        eprintln!(
            "kv8 64 GiB, 24 cards (window used, full used, pool-pressure evictions, starts, card 0 resumed at): off {:?}, on (the serve default) {:?}",
            seen[0], seen[1]
        );
    }

    /// A two-turn tool loop on `/v1/messages`, through the real render and block cache: turn 1 thinks 600 tokens,
    /// then calls a tool; turn 2 sends back the blocks the route sent (`anthropic_content` on the generated
    /// tokens) and the tool result. Without its thinking (dropped, as an unsigned block still is) the prompt leaves
    /// the lane's history one token past the previous prompt, at the thinking, and the lane resumes at the previous
    /// prompt's last block. With it rendered back, the prompt holds the whole previous reply token for token, as the
    /// chat route's echoed `reasoning_content` does, and an approximate lane resumes at the reply's last block.
    /// Without approximate reuse neither route resumes inside a reply: decode-written K/V is never exact.
    #[test]
    fn an_echoed_thinking_block_keeps_the_previous_reply_reusable() {
        use serde_json::json;
        let tk = crate::tokenizer::Tokenizer::for_byte_test();
        let sp = crate::serve::Specials::try_from_tokenizer(&tk).unwrap();
        let render_chat = |req: &serde_json::Value| crate::serve::prompt::render_limited(&tk, &sp, req, "low", usize::MAX, &[]).unwrap();
        let render_msgs = |req: &serde_json::Value| {
            let (chat, cont) = crate::serve::messages::translate_messages(req).unwrap();
            crate::serve::prompt::render_limited(&tk, &sp, &chat, "low", usize::MAX, &cont).unwrap()
        };
        let system = "You-are-a-coding-agent.".repeat(300);
        let task = "Fix-the-failing-test-in-the-repo.".repeat(8);
        let schema = json!({"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]});
        let result = "drwxr-xr-x-src-tests-Cargo.toml-".repeat(16);
        let thinking = "t".repeat(600);
        let msgs1 = json!({"max_tokens": 20480, "thinking": {"type": "adaptive"}, "output_config": {"effort": "low"},
            "tools": [{"name": "bash", "description": "Run a command", "input_schema": schema}],
            "system": [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}],
            "messages": [{"role": "user", "content": [{"type": "text", "text": task}]}]});
        let p1 = render_msgs(&msgs1);
        // What the model generates: thinking, then the tool call, as the template writes them.
        let mut reply: Vec<u32> = vec![sp.msg_model, sp.c_think];
        tk.encode_plain_limited(&thinking, &mut reply, usize::MAX);
        reply.push(sp.end);
        reply.push(sp.msg_model);
        tk.encode_plain_limited("bash", &mut reply, usize::MAX);
        reply.push(sp.c_tool);
        tk.encode_plain_limited("{\"name\":\"bash\",\"args\":{\"command\":\"ls-la\"}}", &mut reply, usize::MAX);
        reply.extend([sp.end, sp.end_sampling]);
        let mut history = p1.clone();
        history.extend_from_slice(&reply);
        // The client's copy of turn 1 is what the route sent for those tokens.
        let sent = crate::serve::reply::anthropic_content(&tk, &sp, &reply, "n", 1);
        assert_eq!(sent.iter().map(|b| b["type"].as_str().unwrap()).collect::<Vec<_>>(), ["thinking", "tool_use"]);
        let turn2 = |assistant: Vec<serde_json::Value>| {
            let mut m = msgs1.clone();
            m["messages"].as_array_mut().unwrap().extend([
                json!({"role": "assistant", "content": assistant}),
                json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": sent[1]["id"], "content": result}]})]);
            render_msgs(&m)
        };
        let echoed = turn2(sent.clone());
        let mut unsigned = sent.clone();
        unsigned[0].as_object_mut().unwrap().remove("signature");
        let dropped = turn2(unsigned);
        let mut edited = sent.clone();
        edited[0]["thinking"] = json!(format!("{thinking}."));
        assert_eq!(turn2(edited), dropped, "an edited block is dropped like an unsigned one");
        // The chat route's turn 2 for the same exchange, reasoning echoed: the same tokens.
        let chat2 = json!({"tools": [{"type": "function", "function": {"name": "bash", "description": "Run a command", "parameters": schema}}],
            "messages": [{"role": "system", "content": [{"type": "text", "text": system}]}, {"role": "user", "content": [{"type": "text", "text": task}]},
                {"role": "assistant", "content": "", "reasoning_content": thinking, "tool_calls": [{"id": sent[1]["id"], "type": "function",
                    "function": {"name": "bash", "arguments": "{\"command\":\"ls-la\"}"}}]},
                {"role": "tool", "tool_call_id": sent[1]["id"], "content": result}]});
        assert_eq!(echoed, render_chat(&chat2), "an echoed block renders as the chat route's reasoning_content");
        assert!(echoed.starts_with(&history), "turn 2 holds the whole previous reply, token for token");
        let common = |t: &[u32]| t.iter().zip(&history).take_while(|(a, b)| a == b).count();
        assert_eq!(common(&dropped), p1.len() + 1, "dropped: the prompt leaves the lane at the thinking");
        assert_eq!(common(&echoed), history.len());
        let resume = |turn: &[u32], approx_retain: bool| {
            let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(approx_retain);
            let mut tbl = BlockTable::new(512).unwrap();
            let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
            assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p1).is_none());
            let mut p = 0;
            while p < p1.len() {
                let next = effective_pf_target(p, p1.len());
                cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
                cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p1, p, next - p, || fake_cs((next / BLOCK) as u8));
                p = next;
            }
            for pos in p1.len()..history.len() {
                cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
                cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
                cache.seal_decode_block(&mut pools, &tbl, &mut st, &history[..=pos], pos, || fake_cs(0x55));
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
            let at = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, turn).map_or(0, |(at, _)| at);
            cache.release_lane(&mut pools, &mut tbl, &mut st2);
            cache.shutdown(&mut pools);
            at
        };
        let floor = |n: usize| n / BLOCK * BLOCK;
        for approx_retain in [false, true] {
            let (before, after) = (resume(&dropped, approx_retain), resume(&echoed, approx_retain));
            eprintln!(
                "REUSE approx_retain={approx_retain}: prompt1={} reply={} (thinking {}) | dropped: turn2={} reused={before} reprefill={} | echoed: turn2={} reused={after} reprefill={}",
                p1.len(), reply.len(), thinking.len(), dropped.len(), dropped.len() - before, echoed.len(), echoed.len() - after
            );
            assert_eq!(before, floor(p1.len()), "dropped: the lane resumes at the previous prompt's last block");
            let expect = if approx_retain { floor(history.len()) } else { floor(p1.len()) };
            assert_eq!(after, expect, "echoed: an approximate lane resumes at the previous reply's last block");
        }
    }

    #[test]
    fn a_large_retained_host_cap_keeps_starts_past_512_mib() {
        // v2.0.4 clamps the host cap to 512 MiB; an explicit cap keeps more.
        assert_eq!(ServeBlockCache::recommended_host_budget_bytes(u64::MAX), DEFAULT_MAX_RETAINED_HOST_BYTES);
        for (cap, kept) in [(DEFAULT_MAX_RETAINED_HOST_BYTES, false), (1u64 << 30, true)] {
            let mut pools = BlockPools::with_capacities(256, 128, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_max_retained_host_bytes(cap);
            // Two prompts, one EVERY start each, whose host copies (300 MiB each) total 600 MiB: past 512 MiB.
            let big_cs = 300usize << 20;
            for prompt in 0..2u32 {
                let toks: Vec<u32> = (0..2048u32).map(|i| prompt * 10_000 + i).collect();
                let mut tbl = BlockTable::new(64).unwrap();
                let mut st = LaneBlockState::default();
                for b in 0..(2048 / BLOCK) {
                    cache.ensure_span_blocks(&mut pools, &mut tbl, b * BLOCK, BLOCK).unwrap();
                    cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &toks, b * BLOCK, BLOCK, || vec![0u8; big_cs]);
                }
                cache.release_lane(&mut pools, &mut tbl, &mut st);
            }
            assert_eq!(cache.retained_start_count() == 2, kept, "cap {cap}");
            if kept {
                assert!(cache.retained_host_bytes_now() > DEFAULT_MAX_RETAINED_HOST_BYTES);
            }
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }
    }

    #[test]
    fn approx_twin_is_keyed_by_the_secret_salt_and_never_the_exact_namespace() {
        // Unkeyed (the v1 FNV owner), a client could compute or collide another conversation's owner offline.
        let a = approx_twin("salt-one", 7, Some("card-a"));
        assert_ne!(a, approx_twin("salt-two", 7, Some("card-a")), "the twin depends on the server's secret salt");
        assert_ne!(a, approx_twin("salt-one", 8, Some("card-a")), "and on the auth namespace");
        assert_ne!(a, approx_twin("salt-one", 7, Some("card-b")), "and on the conversation id");
        assert_ne!(a, 7);
        assert_eq!(approx_twin("salt-one", 7, None), 0, "no conversation id, no twin");
        assert_eq!(approx_twin("salt-one", 7, Some("")), 0);
        // Length-prefixed: an id can't be shifted across the salt boundary.
        assert_ne!(approx_twin("ab", 7, Some("c")), approx_twin("a", 7, Some("bc")));
    }

    #[test]
    fn exact_bind_paths_refuse_an_approximate_start_even_in_their_own_namespace() {
        // Defence in depth: a twin that coincided with an exact namespace must still never bind on an exact path.
        let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let toks: Vec<u32> = (0..2100u32).collect();
        let mut tbl = BlockTable::new(512).unwrap();
        let mut st = LaneBlockState { namespace: 5, ..Default::default() };
        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(1));
            p = next;
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        // Force the coincidence: mark every start in namespace 5 approximate.
        for s in cache.starts.values_mut() {
            s.approx = true;
        }
        let mut st2 = LaneBlockState { namespace: 5, ..Default::default() };
        let mut longer = toks.clone();
        longer.extend(0..40u32);
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &longer).is_none(), "match_and_bind");
        let mut st3 = LaneBlockState { namespace: 5, ..Default::default() };
        assert!(
            matches!(cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st3, &longer), AdmitBindOutcome::Immediate(None)),
            "begin_admit_bind"
        );
        cache.release_lane(&mut pools, &mut tbl, &mut st3);
        for s in cache.starts.values_mut() {
            s.approx = false;
        }
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn approximate_bind_gives_up_rather_than_spin_on_an_index_desync() {
        let kvb = 1u32;
        let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
        let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
        // Desync: drop the approximate starts from the index but leave the tree's start marks.
        let approx: Vec<SealedId> = cache.starts.iter().filter(|(_, s)| s.approx).map(|(&id, _)| id).collect();
        let removed: Vec<(SealedId, RetainedStart)> =
            approx.iter().map(|id| (*id, cache.starts.remove(id).unwrap())).collect();
        let t2 = turn_two(&prompt, &reply);
        let mut tbl = BlockTable::new(160).unwrap();
        let mut st = LaneBlockState { namespace: 7, owner: own(7, "card-a"), ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2).is_none(), "returns, never spins");
        for (id, s) in removed {
            cache.starts.insert(id, s);
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn reply_sealing_resumes_after_a_step_that_skipped_a_boundary() {
        // A DSpark verify step can write past a block boundary without a seal call landing on it. Sealing must
        // catch up from the lane's sealed frontier, or every later reply block is lost.
        let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_approx_retain(true);
        let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
        let mut tbl = BlockTable::new(512).unwrap();
        let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
        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(2));
            p = next;
        }
        let mut history = turn1.clone();
        for d in 0..200u32 {
            let pos = turn1.len() + d as usize;
            history.push(90_000 + d);
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            if pos == 8319 {
                continue; // the boundary at 8320 is crossed inside a verify step: no seal call lands on it
            }
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x56));
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        let mut turn2 = history.clone();
        turn2.extend((0..140u32).map(|i| 60000 + i));
        let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
        let (at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &turn2).expect("a start");
        assert_eq!(at, 8448, "sealing caught up after the skipped boundary");
        cache.release_lane(&mut pools, &mut tbl, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn one_scope_churning_conversations_cannot_evict_another_scopes_approximate_work() {
        let kvb = 1u32;
        let mut pools = BlockPools::with_capacities(2048, 640, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        cache.set_max_approx_starts_per_scope(8);
        let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
        let _ = seed_stitch_donor(&mut cache, &mut pools, 9, kvb);
        let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 9, own(9, "victim"), &file_span, 100);
        let victim_starts = cache.approx_per_scope.get(&9).copied().unwrap_or(0);
        assert!(victim_starts > 0);
        for i in 0..6 {
            let card = format!("churn-{i}");
            stitched_turn_one(&mut cache, &mut pools, 7, own(7, &card), &file_span, 100);
            assert!(cache.approx_per_scope.get(&7).copied().unwrap_or(0) <= 8, "scope 7 is held to its cap");
        }
        assert_eq!(cache.approx_per_scope.get(&9).copied().unwrap_or(0), victim_starts, "scope 9 is untouched");
        let mut tbl = BlockTable::new(160).unwrap();
        let mut st = LaneBlockState { namespace: 9, owner: own(9, "victim"), ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn_two(&prompt, &reply)).is_some());
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn async_ikv_stitch_gets_the_same_approximate_provenance_as_a_ram_stitch() {
        // A completed background .ikv install must enter the twin path like a RAM stitch: before this, the lane
        // became approximate but never sealed, so its next turn had nothing to resume.
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;
        let dir = ScratchDir::new("ikv-approx-provenance");
        #[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;
        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");
        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());
        let mut pools = BlockPools::with_capacities(256, 96, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        cache.set_ikv_catalog(cat);
        let owner = own(0, "card-ikv");

        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)); // 3411 tokens; PROMPT start at 3392
        let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
        assert_eq!(plans.len(), 1);
        let mut tbl = BlockTable::new(96).unwrap();
        let mut st = LaneBlockState { namespace: 0, owner, 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, plans[0].stitch_start).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, plans[0].stitch_start, || fake_cs(1));
        assert_eq!(
            cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
            StitchStartOutcome::Staging
        );
        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!(done.stitched_tokens.is_some());
        assert!(st.stitched_approx && st.approx_path, "a completed .ikv install enters the twin path");
        let mut p = st.written;
        while p < prompt.len() {
            let next = effective_pf_target(p, prompt.len());
            cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, p, next - p, || fake_cs(0x44));
            p = next;
        }
        cache.release_lane(&mut pools, &mut tbl, &mut st);
        assert!(cache.starts.values().any(|s| s.approx && s.pos == 3392), "its PROMPT start was saved in the twin");
        assert_eq!(cache.tree.deepest_start_in_namespace(0, &prompt).at, 0, "and never in the exact chain");

        // Turn 2 resumes it exactly as a RAM-stitched turn does: an approximate start, so serve records
        // `reuse.source = "approx"` (it reads `stitched_approx` after the bind).
        let mut turn2 = prompt.clone();
        turn2.extend((0..200u32).map(|i| 95_000 + i));
        let mut tbl2 = BlockTable::new(96).unwrap();
        let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
        let (at, _) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2).expect("turn 2 resumes");
        assert_eq!(at, 3392);
        assert!(st2.stitched_approx && st2.approx_path, "classified approximate, as a RAM stitch is");
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }
    #[test]
    fn finalize_verify_span_then_seal_decode_block_across_boundary_retains_later_reply_start() {
        let mut pools = BlockPools::with_capacities(64, 64, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_approx_retain(true);
        let owner = approx_twin("srv-salt", 0, Some("card-verify-seal"));

        let prompt: Vec<u32> = (0..60u32).map(|i| 5_000 + i).collect();
        let mut tbl = BlockTable::new(16).unwrap();
        let mut fg = vec![crate::blocks::CLEARED_GPU_TABLE_ENTRY; 16];
        let mut wg = vec![crate::blocks::CLEARED_GPU_TABLE_ENTRY; 16];
        let mut st = LaneBlockState { namespace: 0, owner, prompt_len: prompt.len(), ..Default::default() };

        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, prompt.len()).unwrap();
        tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
        tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, prompt.len(), || fake_cs(0x10));

        let mut history = prompt.clone();
        history.push(6_000); // sampled at prefill end (pos 60)
        for pos in [60usize, 61] {
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
            tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x20));
            history.push(6_001 + (pos - 60) as u32);
        }

        // Speculative verify step at p0 = 62 with k = 3, n_keep = 4 -> committed_len = 66 (crosses 64 without landing on 64).
        let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 62, 4).unwrap();
        tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
        tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
        let fin = cache
            .finish_verify_span_to_slices(&mut pools, &mut tbl, &mut st, &alloc, 62, 4, &mut fg, &mut wg)
            .expect("finalize_verify_blocks_at across block 0 -> 1");
        assert_eq!(fin.committed_len, 66);
        history.extend_from_slice(&[7_000, 7_001, 7_002, 7_003]);
        cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, 65, || fake_cs(0xAA));
        assert!(st.approx_path, "crossing block 0 inside verify enters twin path and seals block 0");
        assert_eq!(st.sealed.len(), 1);
        assert!(st.turn_ckpt.is_none(), "non-aligned end=66 must not record a misaligned cs at 64");

        // Continue decoding [66..128) to complete block 1 at pos = 127 (end = 128).
        for pos in 66usize..128 {
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0xBB));
            history.push(8_000 + pos as u32);
        }
        assert_eq!(st.sealed.len(), 2);
        cache.release_lane(&mut pools, &mut tbl, &mut st);

        let mut turn2 = history[..128].to_vec();
        turn2.extend((0..40u32).map(|i| 9_000 + i));
        let mut tbl2 = BlockTable::new(16).unwrap();
        let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
        let (at, cs) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2).expect("turn 2 resumes at 128");
        assert_eq!(at, 128);
        assert_eq!(cs, fake_cs(0xBB));
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_protects_latest_turn_prompt_and_turn_end_starts_until_expiry() {
        let mut pools = BlockPools::with_capacities(4, 4, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_approx_retain(true);
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);

        let owner_a = approx_twin("lease-salt", 1, Some("card-a"));

        // Card A Turn 1 at t = 1_000 ms: stitch/enter approx path, save PROMPT start at 64 and turn-end start at 128.
        // Together these hold 2 Full + 2 Window slots with older LRU ticks (1 and 2).
        let prompt_a: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
        st_a.stitched_approx = true;
        cache.enter_approx_path(&pools, &tbl_a, &mut st_a, &prompt_a);
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 64).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 0, 64, || fake_cs(0xA1));
        assert_eq!(cache.stats().approx_starts_saved, 1);

        let mut hist_a = prompt_a.clone();
        hist_a.push(11_000);
        for pos in 64usize..128 {
            cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
            cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xA2));
            hist_a.push(11_001 + (pos - 64) as u32);
        }
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
        assert_eq!(cache.stats().approx_starts_saved, 2, "both PROMPT@64 and turn_end@128 saved");

        // At t = 5_000 ms (< 31_000 ms), anonymous request 1 saves a newer-tick unleased exact start (2 Full + 2 Window).
        cache.advance_test_clock_ms(4_000);
        let anon1: Vec<u32> = (0..128u32).map(|i| 20_000 + i).collect();
        let mut tbl_u1 = BlockTable::new(8).unwrap();
        let mut st_u1 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_u1, &mut st_u1, &anon1);
        cache.ensure_span_blocks(&mut pools, &mut tbl_u1, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_u1, &mut st_u1, &anon1, 0, 128, || fake_cs(0xB1));
        cache.release_lane(&mut pools, &mut tbl_u1, &mut st_u1);
        assert_eq!(cache.retained_start_count(), 3);

        // At t = 10_000 ms (still inside 30 s lease), anonymous request 2 needs 2 Full + 2 Window slots.
        // LeasedProtectedWhenUnleasedSuffices: Tier-0 anon1 must be evicted, keeping BOTH of Card A's Turn 1 starts!
        cache.advance_test_clock_ms(5_000);
        let anon2: Vec<u32> = (0..128u32).map(|i| 30_000 + i).collect();
        let mut tbl_u2 = BlockTable::new(8).unwrap();
        let mut st_u2 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_u2, &mut st_u2, &anon2);
        cache.ensure_span_blocks(&mut pools, &mut tbl_u2, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_u2, &mut st_u2, &anon2, 0, 128, || fake_cs(0xB2));
        cache.release_lane(&mut pools, &mut tbl_u2, &mut st_u2);

        let mut probe_anon1 = anon1.clone();
        probe_anon1.push(99);
        assert_eq!(cache.peek_match_len_in_namespace(&pools, 1, &probe_anon1), 0, "unleased anon1 must be evicted first");
        let twin_a = approx_namespace(1, owner_a);
        let mut a_positions: Vec<usize> =
            cache.starts.values().filter(|st| st.namespace == twin_a).map(|st| st.pos).collect();
        a_positions.sort_unstable();
        assert_eq!(
            a_positions,
            vec![64, 128],
            "both Card A PROMPT@64 and turn_end@128 starts must remain resident under active lease"
        );

        // Advance clock by 21_000 ms -> t = 31_000 ms (>= 1_000 + 30_000): Card A's lease has now expired!
        // Card A's starts (ticks 1, 2) are now Tier-0 and older than anon2 (tick 4), so demanding 2 slots evicts Card A!
        cache.advance_test_clock_ms(21_000);
        let anon3: Vec<u32> = (0..128u32).map(|i| 40_000 + i).collect();
        let mut tbl_u3 = BlockTable::new(8).unwrap();
        let mut st_u3 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_u3, &mut st_u3, &anon3);
        cache.ensure_span_blocks(&mut pools, &mut tbl_u3, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_u3, &mut st_u3, &anon3, 0, 128, || fake_cs(0xB3));
        cache.release_lane(&mut pools, &mut tbl_u3, &mut st_u3);

        let mut probe_anon2 = anon2.clone();
        probe_anon2.push(99);
        assert_eq!(cache.peek_match_len_in_namespace(&pools, 1, &probe_anon2), 128, "newer anon2 survives after Card A expiry");
        assert_eq!(
            cache.starts.values().filter(|st| st.namespace == twin_a).count(),
            0,
            "expired Card A starts are evicted by LRU"
        );

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

    #[test]
    fn card_lease_unleases_prior_turn_immediately_and_never_causes_false_exhaustion() {
        // 1. PriorTurnImmediatelyUnleased + enforce_approx_scope_cap:
        //    Card B Turn 1 saves S_B1 (tick 1), Card A Turn 1 saves S_A1 (tick 2), then 1 s later Card B Turn 2
        //    binds S_B1 (bumping S_B1 to tick 3 > S_A1's tick 2!) and saves S_B2 (tick 4) under scope cap = 2.
        //    S_B1 must be immediately unleased as soon as Turn 2 saves, so enforce_approx_scope_cap evicts S_B1
        //    (Tier-0, tick 3) rather than Card A's actively leased S_A1 (Tier-1, tick 2)!
        {
            let mut pools = BlockPools::with_capacities(16, 16, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(true);
            cache.set_card_lease(Duration::from_secs(30));
            cache.set_max_approx_starts_per_scope(2);
            cache.set_test_clock_ms(1_000);

            let owner_a = approx_twin("lease-salt", 7, Some("card-a"));
            let owner_b = approx_twin("lease-salt", 7, Some("card-b"));

            let pb1: Vec<u32> = (0..64u32).map(|i| 1_000 + i).collect();
            let mut tbl = BlockTable::new(8).unwrap();
            let mut stb1 = LaneBlockState { namespace: 7, owner: owner_b, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stb1, &pb1);
            stb1.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut stb1, &pb1);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb1, &pb1, 0, 64, || fake_cs(0x11));
            cache.release_lane(&mut pools, &mut tbl, &mut stb1);

            cache.advance_test_clock_ms(1_000);
            let pa1: Vec<u32> = (0..64u32).map(|i| 2_000 + i).collect();
            let mut sta1 = LaneBlockState { namespace: 7, owner: owner_a, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut sta1, &pa1);
            sta1.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut sta1, &pa1);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut sta1, &pa1, 0, 64, || fake_cs(0x22));
            cache.release_lane(&mut pools, &mut tbl, &mut sta1);

            // At t = 3_000 ms (only 2 s after S_B1!), Card B Turn 2 binds S_B1 and saves S_B2 at 128.
            cache.advance_test_clock_ms(1_000);
            let mut pb2 = pb1.clone();
            pb2.extend((0..64u32).map(|i| 3_000 + i));
            let mut stb2 = LaneBlockState { namespace: 7, owner: owner_b, ..Default::default() };
            let (bound_at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut stb2, &pb2).expect("bind S_B1");
            assert_eq!(bound_at, 64);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 64, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb2, &pb2, 64, 64, || fake_cs(0x33));
            cache.release_lane(&mut pools, &mut tbl, &mut stb2);

            assert_eq!(cache.retained_start_count(), 2, "scope cap kept exactly 2 approx starts");
            let mut probe_a = pa1.clone();
            probe_a.push(99);
            let mut sta2 = LaneBlockState { namespace: 7, owner: owner_a, ..Default::default() };
            let bound_a = cache.match_and_bind(&mut pools, &mut tbl, &mut sta2, &probe_a);
            assert_eq!(
                bound_a.as_ref().map(|(at, _)| *at),
                Some(64),
                "Card A's leased S_A1 must survive when Card B's prior-turn S_B1 is unleased"
            );
            cache.release_lane(&mut pools, &mut tbl, &mut sta2);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // 2. NoFalseExhaustion + host budget Tier-0-before-Tier-1:
        //    When 100% of pool slots are occupied by actively leased starts (Card A @ tick 1, Card B @ tick 2),
        //    can_satisfy_span and ensure_span_blocks MUST still succeed by evicting the oldest-tick Tier-1 start!
        {
            let mut pools = BlockPools::with_capacities(2, 2, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_card_lease(Duration::from_secs(30));
            cache.set_test_clock_ms(5_000);

            let owner_a = approx_twin("lease-salt", 3, Some("card-a"));
            let owner_b = approx_twin("lease-salt", 3, Some("card-b"));

            let pa: Vec<u32> = (0..64u32).map(|i| 50_000 + i).collect();
            let mut tbl = BlockTable::new(4).unwrap();
            let mut sta = LaneBlockState { namespace: 3, owner: owner_a, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut sta, &pa);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut sta, &pa, 0, 64, || vec![0xAA; 4096]);
            cache.release_lane(&mut pools, &mut tbl, &mut sta);

            cache.advance_test_clock_ms(1_000);
            let pb: Vec<u32> = (0..64u32).map(|i| 60_000 + i).collect();
            let mut stb = LaneBlockState { namespace: 3, owner: owner_b, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stb, &pb);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb, &pb, 0, 64, || vec![0xBB; 4096]);
            cache.release_lane(&mut pools, &mut tbl, &mut stb);

            // Both slots are now held by actively leased starts (t = 6_000 ms < 35_000 ms).
            let mut tbl_c = BlockTable::new(4).unwrap();
            assert!(cache.can_satisfy_span(&pools, &tbl_c, 0, 64), "leased starts must remain reclaimable");
            cache
                .ensure_span_blocks(&mut pools, &mut tbl_c, 0, 64)
                .expect("soft lease must evict oldest-tick leased start rather than PoolExhausted");
            tbl_c.clear_entries(&mut pools).unwrap();

            let mut probe_b = pb.clone();
            probe_b.push(1);
            assert_eq!(
                cache.peek_match_len_in_namespace(&pools, 3, &probe_b),
                64,
                "newer leased start Card B survives when oldest leased start Card A is reclaimed"
            );

            // Host budget Tier-0-before-Tier-1: add an unleased start (newer tick), then tighten host budget
            // via a 3rd save so enforce_retained_host_budget must pick between leased Card B (older tick) and unleased!
            let pu1: Vec<u32> = (0..64u32).map(|i| 70_000 + i).collect();
            let mut stu1 = LaneBlockState { namespace: 3, owner: 0, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stu1, &pu1);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut stu1, &pu1, 0, 64, || vec![0xCC; 4096]);
            cache.release_lane(&mut pools, &mut tbl, &mut stu1);

            cache.set_max_retained_host_bytes(5_000);
            cache.enforce_retained_host_budget(&mut pools, None);
            assert_eq!(cache.retained_start_count(), 1);
            assert_eq!(
                cache.peek_match_len_in_namespace(&pools, 3, &probe_b),
                64,
                "enforce_retained_host_budget must evict unleased start before leased Card B"
            );

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

    #[test]
    fn card_lease_survives_same_owner_short_missed_and_unsaved_admissions() {
        let mut pools = BlockPools::with_capacities(7, 7, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_approx_retain(true);
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);

        let owner_a = approx_twin("lease-salt", 1, Some("card-a"));
        let owner_b = approx_twin("lease-salt", 1, Some("card-b"));
        let owner_c = approx_twin("lease-salt", 1, Some("card-c"));
        let twin_a = approx_namespace(1, owner_a);

        // Card A Turn 1 at t = 1_000 ms saves PROMPT@64 and turn_end@128 (2 Full + 2 Window slots, ticks 1 & 2).
        let prompt_a: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
        st_a.stitched_approx = true;
        cache.enter_approx_path(&pools, &tbl_a, &mut st_a, &prompt_a);
        cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 64).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 0, 64, || fake_cs(0xA1));

        let mut hist_a = prompt_a.clone();
        hist_a.push(11_000);
        for pos in 64usize..128 {
            cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
            cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xA2));
            hist_a.push(11_001 + (pos - 64) as u32);
        }
        cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

        // Card B saves Turn 1 (pb1@128, tick 3) then Turn 2 (pb2@128, tick 4), leaving pb1@128 prior-turn unleased
        // with a newer LRU tick (3 > 1, 2) and 1 free slot remaining in the (7, 7) pools.
        cache.advance_test_clock_ms(1_000);
        let pb1: Vec<u32> = (0..128u32).map(|i| 20_000 + i).collect();
        let mut tbl_b = BlockTable::new(8).unwrap();
        let mut st_b1 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b1, &pb1);
        cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b1, &pb1, 0, 128, || fake_cs(0xB1));
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b1);

        cache.advance_test_clock_ms(1_000);
        let pb2: Vec<u32> = (0..128u32).map(|i| 30_000 + i).collect();
        let mut st_b2 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
        let _ = cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b2, &pb2);
        cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 128).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b2, &pb2, 0, 128, || fake_cs(0xB2));
        cache.release_lane(&mut pools, &mut tbl_b, &mut st_b2);

        // Same-owner (Card A) non-saving turns while TTL remains:
        // (a) <= 1-token short requests via both begin_admit_bind_in_namespace and match_and_bind
        cache.advance_test_clock_ms(1_000);
        let mut tbl_short = BlockTable::new(8).unwrap();
        let mut st_short = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
        assert!(matches!(
            cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_short, &mut st_short, 1, &[777]),
            AdmitBindOutcome::Immediate(None)
        ));
        cache.release_lane(&mut pools, &mut tbl_short, &mut st_short);
        st_short.owner = owner_a;
        assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_short, &mut st_short, 1, &[888]).is_none());
        cache.release_lane(&mut pools, &mut tbl_short, &mut st_short);

        // (b) Non-matching 20-token request (< 64 tokens, prefills unsealed block and releases without saving)
        let miss_toks: Vec<u32> = (0..20u32).map(|i| 80_000 + i).collect();
        let mut tbl_miss = BlockTable::new(8).unwrap();
        let mut st_miss = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
        assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_miss, &mut st_miss, 1, &miss_toks).is_none());
        cache.ensure_span_blocks(&mut pools, &mut tbl_miss, 0, 20).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_miss, &mut st_miss, &miss_toks, 0, 20, || fake_cs(0xEE));
        cache.release_lane(&mut pools, &mut tbl_miss, &mut st_miss);

        // (c) Cancelled return at t = 20_000 ms that binds Card A's turn_end@128 and releases without saving:
        //     refreshes turn_end@128's TTL to 20_000 ms without advancing latest_owner_turn or stripping PROMPT@64!
        cache.set_test_clock_ms(20_000);
        let mut hit_cancel = hist_a[..128].to_vec();
        hit_cancel.extend_from_slice(&[90_001, 90_002]);
        let mut tbl_hit = BlockTable::new(8).unwrap();
        let mut st_hit = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
        assert!(matches!(
            cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_hit, &mut st_hit, 1, &hit_cancel),
            AdmitBindOutcome::Immediate(Some((128, _)))
        ));
        cache.release_lane(&mut pools, &mut tbl_hit, &mut st_hit);

        // At t = 22_000 ms (< 31_000 ms), Card C demands 3 blocks (1 free + 2 reclaimed slots).
        // Card A's Turn 1 starts (PROMPT@64 and turn_end@128) MUST remain leased and survive over unleased pb1@128!
        cache.set_test_clock_ms(22_000);
        let mut tbl_c = BlockTable::new(8).unwrap();
        let mut st_c = LaneBlockState { namespace: 1, owner: owner_c, ..Default::default() };
        let pc: Vec<u32> = (0..192u32).map(|i| 95_000 + i).collect();
        let _ = cache.match_and_bind_in_namespace(&mut pools, &mut tbl_c, &mut st_c, 1, &pc);
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 192).unwrap();
        cache.release_lane(&mut pools, &mut tbl_c, &mut st_c);

        let mut a_positions: Vec<usize> =
            cache.starts.values().filter(|st| st.namespace == twin_a).map(|st| st.pos).collect();
        a_positions.sort_unstable();
        assert_eq!(
            a_positions,
            vec![64, 128],
            "Card A Turn 1 PROMPT@64 and turn_end@128 must stay leased across short, missed, and cancelled returns"
        );

        // At t = 35_000 ms (>= 1_000 + 30_000, < 20_000 + 30_000), PROMPT@64 expired while bound turn_end@128 stays leased.
        cache.set_test_clock_ms(35_000);
        let leased_at_35s = cache.leased_starts();
        let sid_64 = *cache.starts.iter().find(|(_, st)| st.namespace == twin_a && st.pos == 64).unwrap().0;
        let sid_128 = *cache.starts.iter().find(|(_, st)| st.namespace == twin_a && st.pos == 128).unwrap().0;
        assert!(!leased_at_35s.contains(&sid_64), "PROMPT@64 expires 30 s after its 1_000 ms save");
        assert!(leased_at_35s.contains(&sid_128), "turn_end@128 TTL was extended to 50_000 ms on the 20_000 ms bind");

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

    #[test]
    fn card_lease_excludes_every_only_checkpoints_and_keeps_zero_lease_noop() {
        // 2. Exact lane with owner != 0 on a 2200-token prompt + decode to 2240:
        //    saves EVERY-only@2048 (tick 1), PROMPT@2176 (tick 2), and turn_end@2240 (tick 3).
        //    Under competing eviction while TTL remains, EVERY-only@2048 is Tier-0 unleased (evicted even before a
        //    newer-tick unleased start at tick 4!), while PROMPT@2176 and turn_end@2240 stay Tier-1 leased and survive!
        {
            let mut pools = BlockPools::with_capacities(64, 24, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(true);
            cache.set_card_lease(Duration::from_secs(30));
            cache.set_test_clock_ms(1_000);

            let owner_a = approx_twin("lease-salt", 1, Some("card-every"));
            let owner_b = approx_twin("lease-salt", 1, Some("card-rival"));
            let twin_a = approx_namespace(1, owner_a);

            let prompt_a: Vec<u32> = (0..2200u32).map(|i| 10_000 + i).collect();
            let mut tbl_a = BlockTable::new(64).unwrap();
            let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
            for b in 0..(2176 / BLOCK) {
                cache.ensure_span_blocks(&mut pools, &mut tbl_a, b * BLOCK, BLOCK).unwrap();
                cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, b * BLOCK, BLOCK, || {
                    fake_cs((b & 0xff) as u8)
                });
            }
            cache.ensure_span_blocks(&mut pools, &mut tbl_a, 2176, 2200 - 2176).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 2176, 2200 - 2176, || fake_cs(0xEE));

            let mut hist_a = prompt_a.clone();
            hist_a.push(30_000);
            for pos in 2200usize..2240 {
                cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
                cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
                cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xFF));
                hist_a.push(30_001 + (pos - 2200) as u32);
            }
            cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);

            let mut saved_pos: Vec<usize> = cache.starts.values().map(|st| st.pos).collect();
            saved_pos.sort_unstable();
            assert_eq!(saved_pos, vec![2048, 2176, 2240]);

            // Add a newer-tick unleased start (128 tokens = 2 Window slots, tick 4 > EVERY@2048's tick 1).
            cache.advance_test_clock_ms(1_000);
            let unleased_toks: Vec<u32> = (0..128u32).map(|i| 50_000 + i).collect();
            let mut tbl_u = BlockTable::new(8).unwrap();
            let mut st_u = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl_u, &mut st_u, &unleased_toks);
            cache.ensure_span_blocks(&mut pools, &mut tbl_u, 0, 128).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl_u, &mut st_u, &unleased_toks, 0, 128, || fake_cs(0xCC));
            cache.release_lane(&mut pools, &mut tbl_u, &mut st_u);

            // At t = 5_000 ms (< 31_000 ms), Card B demands free_win + 2 Window slots (reclaiming 2 Window slots).
            // EVERY@2048 (tick 1, Tier-0 unleased) must be evicted BEFORE newer unleased_toks@128 (tick 4)!
            cache.advance_test_clock_ms(3_000);
            let free_win = pools.window.count_free_up_to(usize::MAX);
            assert!(free_win + 2 <= WINDOW / BLOCK);
            let mut tbl_b1 = BlockTable::new(32).unwrap();
            let mut st_b1 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
            let pb1: Vec<u32> = (0..((free_win + 2) * BLOCK) as u32).map(|i| 60_000 + i).collect();
            let _ = cache.match_and_bind(&mut pools, &mut tbl_b1, &mut st_b1, &pb1);
            cache.ensure_span_blocks(&mut pools, &mut tbl_b1, 0, (free_win + 2) * BLOCK).unwrap();

            assert!(
                !cache.starts.values().any(|st| st.pos == 2048),
                "EVERY-only checkpoint at 2048 must be Tier-0 unleased and evicted first"
            );
            assert!(cache.starts.values().any(|st| st.pos == 128), "newer unleased start survives first eviction");
            assert!(cache.starts.values().any(|st| st.namespace == 1 && st.pos == 2176), "PROMPT@2176 survives");
            assert!(cache.starts.values().any(|st| st.namespace == twin_a && st.pos == 2240), "turn_end@2240 survives");

            // Demand 2 more Window slots: remaining Tier-0 unleased@128 is evicted while PROMPT@2176 & turn_end@2240 survive!
            let mut tbl_b2 = BlockTable::new(16).unwrap();
            cache.ensure_span_blocks(&mut pools, &mut tbl_b2, 0, 2 * BLOCK).unwrap();
            assert!(!cache.starts.values().any(|st| st.pos == 128), "Tier-0 unleased@128 evicted next");
            assert!(cache.starts.values().any(|st| st.namespace == 1 && st.pos == 2176), "leased PROMPT@2176 survives");
            assert!(
                cache.starts.values().any(|st| st.namespace == twin_a && st.pos == 2240),
                "leased turn_end@2240 survives"
            );

            tbl_b2.clear_entries(&mut pools).unwrap();
            cache.release_lane(&mut pools, &mut tbl_b1, &mut st_b1);
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

        // 1. With card_lease == Duration::ZERO (default off), owned saves and binds do zero turn/clock bookkeeping.
        {
            let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
            let mut cache = ServeBlockCache::new();
            cache.set_approx_retain(true);
            cache.set_test_clock_ms(5_000);
            let owner = approx_twin("lease-salt", 1, Some("card-zero"));

            let prompt: Vec<u32> = (0..64u32).map(|i| 1_000 + i).collect();
            let mut tbl = BlockTable::new(8).unwrap();
            let mut st = LaneBlockState { namespace: 1, owner, ..Default::default() };
            let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt);
            st.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut st, &prompt);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 64, || fake_cs(0x01));
            let mut hist = prompt.clone();
            hist.push(2_000);
            for pos in 64usize..128 {
                cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
                cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
                cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist, pos, || fake_cs(0x02));
                hist.push(2_001 + (pos - 64) as u32);
            }
            cache.release_lane(&mut pools, &mut tbl, &mut st);
            assert_eq!(cache.next_owner_turn, 0, "disabled card lease must not advance next_owner_turn");
            assert!(cache.latest_owner_turn.is_empty(), "disabled card lease must not populate latest_owner_turn");
            assert!(
                cache.starts.values().all(|s| s.last_owner == 0 && s.owner_turn == 0 && s.last_used_ms == 0),
                "disabled card lease must leave per-start lease fields zeroed"
            );
            cache.shutdown(&mut pools);
            assert_zero_pool_leaks(&pools);
        }

    }

    // Card lease measured from the end of a turn, held while the card is in flight (INK_CARD_LEASE_SECS).
    // Every test drives time through the test clock; none reads real time.

    const LEASE_NS: u64 = 5;
    const LEASE_CS_BYTES: usize = 4096;

    /// Bind `toks` for `owner` and prefill `[p0, p0 + t)`; returns the bound position (0 on a miss).
    fn lease_prefill(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        st: &mut LaneBlockState,
        toks: &[u32],
        t: usize,
        tag: u8,
    ) -> usize {
        let at = cache.match_and_bind(pools, tbl, st, toks).map(|(at, _)| at).unwrap_or(0);
        cache.ensure_span_blocks(pools, tbl, at, t).unwrap();
        cache.finish_prefill_span(pools, tbl, st, toks, at, t, || vec![tag; LEASE_CS_BYTES]);
        at
    }

    /// Decode `[from, to)` one token at a time, advancing the test clock `ms_per_token` per token.
    fn lease_decode(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        tbl: &mut BlockTable,
        st: &mut LaneBlockState,
        from: usize,
        to: usize,
        ms_per_token: u64,
    ) {
        for pos in from..to {
            cache.ensure_span_blocks(pools, tbl, pos, 1).unwrap();
            cache.finish_decode_span(pools, tbl, st, pos);
            cache.advance_test_clock_ms(ms_per_token);
        }
    }

    /// Save one anonymous (owner 0, never leased) start of `len` tokens and release its lane.
    fn lease_save_anon(
        cache: &mut ServeBlockCache,
        pools: &mut BlockPools,
        base: u32,
        len: usize,
        tag: u8,
    ) -> Vec<u32> {
        let toks: Vec<u32> = (0..len as u32).map(|i| base + i).collect();
        let mut tbl = BlockTable::new(8).unwrap();
        let mut st = LaneBlockState { namespace: LEASE_NS, owner: 0, ..Default::default() };
        let _ = lease_prefill(cache, pools, &mut tbl, &mut st, &toks, len, tag);
        cache.release_lane(pools, &mut tbl, &mut st);
        toks
    }

    fn lease_resident(cache: &ServeBlockCache, pools: &BlockPools, toks: &[u32]) -> usize {
        let mut probe = toks.to_vec();
        probe.push(7);
        cache.peek_match_len_in_namespace(pools, LEASE_NS, &probe)
    }

    /// Host-budget pressure that keeps exactly one of the resident 64-token starts.
    fn lease_squeeze_to_one(cache: &mut ServeBlockCache, pools: &mut BlockPools) {
        cache.set_max_retained_host_bytes(LEASE_CS_BYTES as u64 + 1_000);
        cache.enforce_retained_host_budget(pools, None);
        assert_eq!(cache.retained_start_count(), 1);
        cache.set_max_retained_host_bytes(DEFAULT_MAX_RETAINED_HOST_BYTES);
    }

    #[test]
    fn card_lease_counts_from_release_so_a_card_back_after_a_long_decode_hits_its_prompt_start() {
        // Regression (a): prefill ends at t = 1 s, the reply decodes 40 tokens over 40 s (longer than the
        // 30 s lease) and seals no new 64-token block, the lane releases at t = 41 s and the card is back
        // 4 s later. Pool pressure in between must take the unleased anonymous start, not the card's.
        let mut pools = BlockPools::with_capacities(3, 3, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
        assert_eq!(cache.retained_start_count(), 1, "PROMPT start @64 saved at t = 1 s");
        lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000);
        cache.release_lane(&mut pools, &mut tbl_a, &mut sta); // t = 41 s

        cache.advance_test_clock_ms(2_000); // t = 43 s
        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 128, 0xB1);
        // The pool is now full (A: 1 + 1, anon1: 2 + 2); a second 128-token request must evict.
        let _ = lease_save_anon(&mut cache, &mut pools, 30_000, 128, 0xB2);
        assert_eq!(lease_resident(&cache, &pools, &anon1), 0, "unleased anon1 is evicted first");

        cache.advance_test_clock_ms(2_000); // t = 45 s, 4 s after release
        let mut turn2 = pa.clone();
        turn2.extend((0..30u32).map(|i| 11_000 + i));
        let mut tbl2 = BlockTable::new(8).unwrap();
        let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        let bound = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2);
        assert_eq!(
            bound.map(|(at, cs)| (at, cs == vec![0xA1; LEASE_CS_BYTES])),
            Some((64, true)),
            "the card's PROMPT start must survive: its lease counts from release, not from prefill"
        );
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_holds_an_in_flight_lanes_prompt_start_past_the_lease_window() {
        // Regression (b): the lane is still decoding 40 s after its prefill; under host-budget pressure the
        // newer anonymous start goes, never the in-flight card's PROMPT start.
        let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
        lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000); // t = 41 s, still bound

        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &anon1), 0, "the unleased anonymous start is evicted");
        assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the in-flight card's PROMPT start is held");

        cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
        assert!(cache.held_starts.is_empty() && sta.lease_holds.is_empty(), "release drops every hold");
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_holds_a_bound_start_while_prefill_has_not_reached_the_next_block() {
        // Turn 2 binds turn 1's start @64 with a 70-token delta (prompt checkpoint 128 != 64, so the lane
        // records no prompt_saved_id) and stalls 40 s before prefill crosses 128. The bound start stays held.
        let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl = BlockTable::new(8).unwrap();
        let mut st1 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st1, &pa, 64, 0xA1);
        cache.release_lane(&mut pools, &mut tbl, &mut st1);

        cache.advance_test_clock_ms(1_000); // t = 2 s
        let mut turn2 = pa.clone();
        turn2.extend((0..70u32).map(|i| 11_000 + i));
        let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        let at = lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st2, &turn2, 36, 0xA2);
        assert_eq!(at, 64);
        assert_eq!(st2.prompt_saved_id, None, "no prompt checkpoint at the bound position");
        cache.advance_test_clock_ms(40_000); // t = 42 s, prefill of [100, 134) not yet run

        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &anon1), 0);
        assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the bound start is held while its lane is in flight");

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

    #[test]
    fn card_lease_short_turn_that_saves_nothing_refreshes_its_bound_start_at_release() {
        // Turn 2 adds 20 prompt tokens and a 40-token reply: it seals nothing, so it never allocates a save
        // turn. It decodes for 40 s; at release the bound start's lease must restart, so the card's turn 3,
        // 4 s later and after pressure, still binds it.
        let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl = BlockTable::new(8).unwrap();
        let mut st1 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st1, &pa, 64, 0xA1);
        cache.release_lane(&mut pools, &mut tbl, &mut st1);

        cache.advance_test_clock_ms(1_000); // t = 2 s
        let mut turn2 = pa.clone();
        turn2.extend((0..20u32).map(|i| 11_000 + i));
        let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        assert_eq!(lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st2, &turn2, 20, 0xA2), 64);
        lease_decode(&mut cache, &mut pools, &mut tbl, &mut st2, 84, 124, 1_000);
        assert_eq!(st2.save_owner_turn, 0, "the short turn saved nothing");
        cache.release_lane(&mut pools, &mut tbl, &mut st2); // t = 42 s

        cache.advance_test_clock_ms(2_000); // t = 44 s
        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &anon1), 0);

        cache.advance_test_clock_ms(2_000); // t = 46 s
        let mut turn3 = turn2.clone();
        turn3.extend((0..10u32).map(|i| 12_000 + i));
        let mut st3 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st3, &turn3).map(|(at, _)| at);
        assert_eq!(bound, Some(64), "turn 3 binds the start turn 2 used");
        cache.release_lane(&mut pools, &mut tbl, &mut st3);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_admission_progresses_when_every_start_is_leased() {
        // Regression (c): one start is held by an in-flight lane, the other was released 0 s ago (leased);
        // a 128-token admission needs 2 + 2 slots with only 1 + 1 free. Leases are a tier, not a filter, so
        // the released card's start yields and admission proceeds; the in-flight lane's start stays.
        let mut pools = BlockPools::with_capacities(3, 3, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
        let owner_b = approx_twin("lease-salt", LEASE_NS, Some("card-b"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
        cache.advance_test_clock_ms(40_000); // t = 41 s, A still bound

        let pb: Vec<u32> = (0..64u32).map(|i| 40_000 + i).collect();
        let mut tbl_b = BlockTable::new(8).unwrap();
        let mut stb = LaneBlockState { namespace: LEASE_NS, owner: owner_b, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_b, &mut stb, &pb, 64, 0xB1);
        cache.release_lane(&mut pools, &mut tbl_b, &mut stb);
        assert_eq!(cache.leased_starts().len(), cache.retained_start_count(), "every resident start is leased");

        let mut tbl_c = BlockTable::new(8).unwrap();
        assert!(cache.can_satisfy_span(&pools, &tbl_c, 0, 128), "leased starts stay reclaimable");
        cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 128).expect("a lease never blocks admission");
        tbl_c.clear_entries(&mut pools).unwrap();
        assert_eq!(lease_resident(&cache, &pools, &pb), 0, "the released card's leased start yields");
        assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the in-flight card's start stays");

        cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_ends_one_lease_window_after_release() {
        // Regression (d): released at t = 41 s, the start is leased until t = 71 s and evictable from then on.
        let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
        lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000);
        cache.release_lane(&mut pools, &mut tbl_a, &mut sta); // t = 41 s

        cache.advance_test_clock_ms(29_999); // t = 70.999 s: still leased
        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &anon1), 0);
        assert_eq!(lease_resident(&cache, &pools, &pa), 64, "leased until release + lease window");

        let anon2 = lease_save_anon(&mut cache, &mut pools, 30_000, 64, 0xB2);
        cache.advance_test_clock_ms(1); // t = 71 s: lease over
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &pa), 0, "an expired lease no longer protects the start");
        assert_eq!(lease_resident(&cache, &pools, &anon2), 64);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn card_lease_cancelled_release_drops_the_cards_lease() {
        // A cancelled card (client gone, 499) neither keeps nor refreshes a lease: its start falls to the
        // unleased tier at once, so dead cards do not hold memory against the cards that admit next.
        let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_card_lease(Duration::from_secs(30));
        cache.set_test_clock_ms(1_000);
        let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));

        let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
        cache.advance_test_clock_ms(1_000);
        cache.release_lane_with_toks(&mut pools, &mut tbl_a, &mut sta, None, true); // cancelled at t = 2 s
        assert!(cache.leased_starts().is_empty(), "a cancelled card keeps no lease");

        cache.advance_test_clock_ms(1_000); // t = 3 s, well inside what would have been the lease
        let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
        lease_squeeze_to_one(&mut cache, &mut pools);
        assert_eq!(lease_resident(&cache, &pools, &pa), 0, "the cancelled card's start is evicted by plain LRU");
        assert_eq!(lease_resident(&cache, &pools, &anon1), 64);
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    #[test]
    fn a_lane_failed_on_invalid_logits_leaves_no_start_over_its_blocks() {
        // chadlyb/erisinky a317c508, in this cache's terms. `pa` fails with invalid logits after its prefill. `pb`
        // has the same first 64 tokens, so the two share that block, and `pb` ended normally before. `pc` shares
        // nothing with either.
        let mut pools = BlockPools::with_capacities(16, 16, 2).unwrap();
        let mut cache = ServeBlockCache::new();
        let head: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
        let with_tail = |base: u32| -> Vec<u32> { head.iter().copied().chain((0..64u32).map(|i| base + i)).collect() };
        let (pa, pb) = (with_tail(20_000), with_tail(30_000));
        let full_slots = |tbl: &BlockTable| -> Vec<Slot> {
            (0..2u32).map(|b| tbl.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap().slot()).collect()
        };

        let mut tbl_b = BlockTable::new(8).unwrap();
        let mut stb = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
        lease_prefill(&mut cache, &mut pools, &mut tbl_b, &mut stb, &pb, 128, 0xB1);
        let shared = full_slots(&tbl_b)[0];
        cache.release_lane(&mut pools, &mut tbl_b, &mut stb);
        let pc = lease_save_anon(&mut cache, &mut pools, 40_000, 128, 0xC1);
        assert_eq!((lease_resident(&cache, &pools, &pb), lease_resident(&cache, &pools, &pc)), (128, 128));

        // pa prefills its whole prompt and saves its PROMPT start, as a prefill step does before anything is sampled
        let mut tbl_a = BlockTable::new(8).unwrap();
        let mut sta = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
        assert_eq!(lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 128, 0xA1), 0);
        let held = full_slots(&tbl_a);
        let held_entries: Vec<BlockEntry> = tbl_a.entries().map(|(_, e)| e).collect();
        assert_eq!(held[0], shared, "pa shares pb's first block");
        assert_eq!(lease_resident(&cache, &pools, &pa), 128);
        // the K/V behind the invalid logits: fp16 NaN in every word of both blocks pa read
        for &s in &held {
            for w in pools.full.slot_bytes_mut(s).unwrap().chunks_exact_mut(2) {
                w.copy_from_slice(&0x7e00u16.to_le_bytes());
            }
        }

        assert_eq!(cache.release_lane_invalid(&mut pools, &mut tbl_a, &mut sta), 2, "pa's start and pb's");
        assert_eq!(lease_resident(&cache, &pools, &pa), 0, "the failed prompt has no start left to bind");
        assert_eq!(lease_resident(&cache, &pools, &pb), 0, "nor has the prompt that shares a block with it");
        assert_eq!(lease_resident(&cache, &pools, &pc), 128, "a start over other blocks stays");
        assert_eq!(cache.stats().evictions_stale_invalid, 2);
        for &s in &held {
            assert_eq!(pools.full.record(s).unwrap().refs(), 0, "nothing holds the failed lane's blocks");
        }

        // the same prompt again: nothing cached, so it prefills from position 0 into blocks of its own, which the
        // pool hands out as new generations (the engine zeroes or wholly overwrites a taken slot before it is read)
        let mut tbl_r = BlockTable::new(8).unwrap();
        let mut str_ = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl_r, &mut str_, &pa).is_none());
        cache.ensure_span_blocks(&mut pools, &mut tbl_r, 0, 128).unwrap();
        for b in 0..2u32 {
            let e = tbl_r.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap();
            assert!(!held_entries.contains(&e), "the retry holds none of the failed lane's blocks");
        }
        cache.finish_prefill_span(&mut pools, &mut tbl_r, &mut str_, &pa, 0, 128, || vec![0xA2; LEASE_CS_BYTES]);
        cache.release_lane(&mut pools, &mut tbl_r, &mut str_);
        assert_eq!(lease_resident(&cache, &pools, &pa), 128, "and the retry's own start is kept as usual");

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

    #[test]
    fn multi_span_retained_stitches_retain_approx_prompt_and_reply_starts() {
        let kvb = 1u32;
        let ns = 5u64;
        let mut pools = BlockPools::with_capacities(640, 256, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);

        let prefill_to = |cache: &mut ServeBlockCache,
                          pools: &mut BlockPools,
                          tbl: &mut BlockTable,
                          st: &mut LaneBlockState,
                          toks: &[u32],
                          from: usize,
                          to: usize,
                          cs_tag: u8| {
            let mut p = from;
            while p < to {
                let next = effective_pf_target(p, to).min(p + 512);
                cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
                let lo_blk = p / BLOCK;
                let hi_blk = (next - 1) / BLOCK;
                for b in lo_blk..=hi_blk {
                    let p0 = b * BLOCK;
                    if p0 + BLOCK <= next {
                        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(),
                            &toks[p0..p0 + BLOCK],
                            kvb,
                        );
                    }
                }
                cache.finish_prefill_span(pools, tbl, st, toks, p, next - p, || fake_cs(cs_tag));
                p = next;
            }
        };

        // Seed 2 distinct exact stitch donors (`donor_a`, `donor_b`, each 3,200 tokens >= MIN_STITCH_TOKENS) in `ns`.
        let donor_a: Vec<u32> = (0..3200u32).map(|i| 100_000 + i).collect();
        let donor_b: Vec<u32> = (0..3200u32).map(|i| 200_000 + i).collect();
        for (idx, (lead_base, donor, tail_base)) in
            [(10_000u32, &donor_a, 40_000u32), (20_000u32, &donor_b, 50_000u32)].into_iter().enumerate()
        {
            let mut seed: Vec<u32> = (0..128u32).map(|i| lead_base + i).collect();
            seed.extend_from_slice(donor);
            seed.extend((0..129u32).map(|i| tail_base + i)); // 3,457 tokens -> exact PROMPT start at 3,456
            let mut tbl_s = BlockTable::new(96).unwrap();
            let mut st_s = LaneBlockState { namespace: ns, owner: 0, prompt_len: seed.len(), ..Default::default() };
            prefill_to(&mut cache, &mut pools, &mut tbl_s, &mut st_s, &seed, 0, seed.len(), 0x10 + idx as u8);
            cache.release_lane(&mut pools, &mut tbl_s, &mut st_s);
        }
        assert_eq!(cache.stats().start_points_saved, 4); // EVERY@2048 + PROMPT@3456 per seed

        // Build 2-span prompt:
        // - Span 1: `donor_a` at [256..3456) -> aligned shift (+128), zero-copy 10 blocks [1280..1920).
        // - Span 2: `donor_b` at [3603..6803) -> unaligned shift (3603 % 64 == 19), row-copy 9 blocks [4672..5248).
        // - Total prompt = 6,948 tokens -> `prompt_ckpt` = 6,912 (108 blocks + 36 tail tokens).
        let build_prompt = |prefix_base: u32| -> Vec<u32> {
            let mut p: Vec<u32> = (0..256u32).map(|i| prefix_base + i).collect();
            p.extend_from_slice(&donor_a);
            p.extend((0..147u32).map(|i| 400_000 + i));
            p.extend_from_slice(&donor_b);
            p.extend((0..145u32).map(|i| 500_000 + i));
            p
        };

        let run_two_span_turn1 = |cache: &mut ServeBlockCache,
                                  pools: &mut BlockPools,
                                  owner: u64,
                                  prompt: &[u32],
                                  reply_len: usize|
         -> Vec<u32> {
            let plans = cache.plan_stitches(pools, ns, prompt, 0);
            assert_eq!(plans.len(), 2, "must plan 2 disjoint stitch spans");
            assert_eq!((plans[0].stitch_start, plans[0].heal_start), (1280, 1920));
            assert_eq!((plans[1].stitch_start, plans[1].heal_start), (4672, 5248));

            let mut tbl = BlockTable::new(160).unwrap();
            let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
            assert!(matches!(
                cache.begin_admit_bind_in_namespace(pools, 0, &mut tbl, &mut st, ns, prompt),
                AdmitBindOutcome::Immediate(None)
            ));

            prefill_to(cache, pools, &mut tbl, &mut st, prompt, 0, plans[0].stitch_start, 0x21);
            let out1 = cache.apply_stitch_plan(pools, &mut tbl, &mut st, prompt, &plans[0]);
            assert_eq!(out1, StitchApplyOutcome::Applied { stitched_tokens: 640, zero_copy_blocks: 10 });
            assert!(st.stitched_approx && st.approx_path);
            assert_eq!(st.sealed.len(), plans[0].heal_start / BLOCK);

            prefill_to(cache, pools, &mut tbl, &mut st, prompt, plans[0].heal_start, plans[1].stitch_start, 0x22);
            assert_eq!(st.sealed.len(), plans[1].stitch_start / BLOCK);

            let out2 = cache.apply_stitch_plan(pools, &mut tbl, &mut st, prompt, &plans[1]);
            assert_eq!(out2, StitchApplyOutcome::Applied { stitched_tokens: 576, zero_copy_blocks: 0 });
            assert!(st.stitched_approx && st.approx_path);
            assert_eq!(
                st.sealed.len(),
                plans[1].heal_start / BLOCK,
                "second stitch span must extend state.sealed in twin approx_namespace"
            );
            for b in (plans[1].stitch_start / BLOCK)..(plans[1].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(),
                    &prompt[b * BLOCK..(b + 1) * BLOCK],
                    kvb,
                );
            }

            prefill_to(cache, pools, &mut tbl, &mut st, prompt, plans[1].heal_start, prompt.len(), 0x23);
            assert_eq!(st.prompt_saved_pos, 6912, "Turn 1 must retain PROMPT start at 6912 after 2 stitches");

            let mut hist = prompt.to_vec();
            for step in 0..reply_len {
                let pos = prompt.len() + step;
                hist.push(800_000 + step as u32);
                cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
                cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
                cache.seal_decode_block(pools, &tbl, &mut st, &hist, pos, || fake_cs(0x24));
            }
            cache.release_lane_with_toks(pools, &mut tbl, &mut st, Some(&hist), false);
            hist
        };

        // Subcase 1a: < 64-token reply (20 tokens -> 6,968 < 6,976, zero decode blocks sealed) -> `hit_prompt_end`.
        let owner_a = approx_twin("multi-stitch", ns, Some("card-a"));
        let prompt_a1 = build_prompt(300_000);
        let hist_a1 = run_two_span_turn1(&mut cache, &mut pools, owner_a, &prompt_a1, 20);
        let mut turn_a2 = hist_a1.clone();
        turn_a2.extend(900_000u32..900_080);
        let obs_a2 = cache.observe_prior(owner_a, &turn_a2);
        let mut tbl_a2 = BlockTable::new(160).unwrap();
        let mut st_a2 = LaneBlockState { namespace: ns, owner: owner_a, ..Default::default() };
        let out_a2 = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_a2, &mut st_a2, ns, &turn_a2);
        let matched_a2 = match out_a2 {
            AdmitBindOutcome::Immediate(Some((at, _))) => at,
            other => panic!("expected Turn 2 approx bind at 6912, got {other:?}"),
        };
        assert_eq!(matched_a2, 6912);
        assert!(st_a2.stitched_approx && st_a2.approx_path);
        let (reason_a2, div_a2) =
            ServeBlockCache::classify_observed_reuse(owner_a, matched_a2, false, obs_a2, &st_a2.sealed);
        assert_eq!(reason_a2, "hit_prompt_end");
        assert_eq!(div_a2, None);
        cache.release_lane(&mut pools, &mut tbl_a2, &mut st_a2);

        // Subcase 1b: >= 64-token reply (100 tokens -> 7,048, sealing decode blocks through 7,040) -> `hit_reply_end`.
        let owner_b = approx_twin("multi-stitch", ns, Some("card-b"));
        let prompt_b1 = build_prompt(310_000);
        let hist_b1 = run_two_span_turn1(&mut cache, &mut pools, owner_b, &prompt_b1, 100);
        let mut turn_b2 = hist_b1.clone();
        turn_b2.extend(910_000u32..910_080);
        let obs_b2 = cache.observe_prior(owner_b, &turn_b2);
        let mut tbl_b2 = BlockTable::new(160).unwrap();
        let mut st_b2 = LaneBlockState { namespace: ns, owner: owner_b, ..Default::default() };
        let out_b2 = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_b2, &mut st_b2, ns, &turn_b2);
        let matched_b2 = match out_b2 {
            AdmitBindOutcome::Immediate(Some((at, _))) => at,
            other => panic!("expected Turn 2 approx bind at 7040, got {other:?}"),
        };
        assert_eq!(matched_b2, 7040);
        assert!(matched_b2 > prompt_b1.len());
        assert!(st_b2.stitched_approx && st_b2.approx_path);
        let (reason_b2, div_b2) =
            ServeBlockCache::classify_observed_reuse(owner_b, matched_b2, false, obs_b2, &st_b2.sealed);
        assert_eq!(reason_b2, "hit_reply_end");
        assert_eq!(div_b2, None);
        cache.release_lane(&mut pools, &mut tbl_b2, &mut st_b2);

        // Exact namespace isolation: anonymous request sees zero approximate starts.
        let mut tbl_exact = BlockTable::new(160).unwrap();
        let mut st_exact = LaneBlockState { namespace: ns, owner: 0, ..Default::default() };
        assert_eq!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_exact, &mut st_exact, ns, &turn_b2), None);

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

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

        let dir = ScratchDir::new("ikv-multi-stitch");
        #[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"multi-stitch-ikv-hmac-key-32byte").unwrap();
        let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;

        let cart1_toks: Vec<u32> = (0..3200u32).map(|i| 120_000 + i).collect();
        let cart2_toks: Vec<u32> = (0..3200u32).map(|i| 180_000 + i).collect();
        for (fname, src_name, ctoks) in
            [("alpha.ikv", "src/alpha.rs", &cart1_toks), ("beta.ikv", "src/beta.rs", &cart2_toks)]
        {
            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, &ctoks[p * BLOCK..(p + 1) * BLOCK], kvb);
                full_pages.push(page);
            }
            crate::ikv::write_ikv_cartridge_raw(
                &dir.0.join(fname),
                src_name,
                kvb,
                vocab,
                model_fp,
                false,
                16,
                ctoks,
                &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(), 2);

        let mut pools = BlockPools::with_capacities(512, 192, kvb).unwrap();
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);
        cache.set_ikv_catalog(cat);
        let owner = own(0, "card-ikv-multi");

        let mut prompt: Vec<u32> = (0..83u32).map(|i| 4_000 + i).collect();
        prompt.extend_from_slice(&cart1_toks);
        prompt.extend((0..140u32).map(|i| 50_000 + i));
        prompt.extend_from_slice(&cart2_toks);
        prompt.extend((0..150u32).map(|i| 90_000 + i)); // 6,773 tokens; prompt_ckpt = 6,720

        let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
        assert_eq!(plans.len(), 2, "must plan 2 staged .ikv stitch spans");
        assert!(plans.iter().all(|p| matches!(p.source, StitchSource::Ikv { .. })));

        let mut tbl = BlockTable::new(160).unwrap();
        let mut st = LaneBlockState { namespace: 0, owner, prompt_len: prompt.len(), ..Default::default() };
        let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);

        let prefill_step = |cache: &mut ServeBlockCache,
                            pools: &mut BlockPools,
                            tbl: &mut BlockTable,
                            st: &mut LaneBlockState,
                            from: usize,
                            to: usize| {
            let mut p = from;
            while p < to {
                let next = effective_pf_target(p, to).min(p + 512);
                cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
                cache.finish_prefill_span(pools, tbl, st, &prompt, p, next - p, || fake_cs(0x55));
                p = next;
            }
        };

        prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, 0, plans[0].stitch_start);
        assert_eq!(
            cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
            StitchStartOutcome::Staging
        );
        let done1 = 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!(done1.stitched_tokens.is_some() && !done1.corrupt_fallback);
        assert!(st.stitched_approx && st.approx_path);
        assert_eq!(st.sealed.len(), plans[0].heal_start / BLOCK);

        let resume1 = st.written;
        prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, resume1, plans[1].stitch_start);
        assert_eq!(
            cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[1]),
            StitchStartOutcome::Staging
        );
        let done2 = 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!(done2.stitched_tokens.is_some() && !done2.corrupt_fallback);
        assert!(st.stitched_approx && st.approx_path);
        assert_eq!(
            st.sealed.len(),
            plans[1].heal_start / BLOCK,
            "second staged .ikv stitch must extend state.sealed in twin approx_namespace"
        );

        let resume2 = st.written;
        prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, resume2, prompt.len());
        assert_eq!(st.prompt_saved_pos, 6720);

        let mut hist1 = prompt.clone();
        for step in 0..90usize {
            let pos = prompt.len() + step;
            hist1.push(950_000 + step as u32);
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist1, pos, || fake_cs(0x56));
        }
        cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&hist1), false);

        let mut turn2 = hist1.clone();
        turn2.extend(960_000u32..960_064);
        let obs2 = cache.observe_prior(owner, &turn2);
        let mut tbl2 = BlockTable::new(160).unwrap();
        let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
        let out2 = cache.begin_admit_bind(&mut pools, 0, &mut tbl2, &mut st2, &turn2);
        let matched2 = match out2 {
            AdmitBindOutcome::Immediate(Some((at, _))) => at,
            other => panic!("expected Turn 2 approx bind at 6848 after 2-span .ikv stitch, got {other:?}"),
        };
        assert_eq!(matched2, 6848);
        assert!(st2.stitched_approx && st2.approx_path);
        let (reason2, div2) = ServeBlockCache::classify_observed_reuse(owner, matched2, false, obs2, &st2.sealed);
        assert_eq!(reason2, "hit_reply_end");
        assert_eq!(div2, None);

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

#[cfg(test)]
mod admission_tests;

#[cfg(test)]
#[path = "block_cache/retention_tests.rs"]
mod retention_tests;