memra-server 0.77.0

OpenAI-compatible HTTP serving for the memra CUDA inference engine - single-GPU multi-model step-interleave scheduling on RTX 50-series
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
//! The single GPU worker thread + step-interleave scheduler (BASE-4, MEMRA-BUILD-MAP §4e).
//!
//! WHY a dedicated thread: the CUDA context is THREAD-AFFINE. `Engine` (and every `CudaStream` /
//! `CudaSlice` it owns) must only ever be touched from the one thread that created the context.
//! So we spawn ONE OS thread, build the primary `Engine` on it, load every `HybridModel` on it,
//! and never let an `Engine`/`Cache`/`CudaSlice` cross a thread boundary. Async HTTP handlers run
//! on a separate tokio runtime and submit work over an `mpsc` channel; each request carries a
//! `tokio` mpsc Sender back which the worker uses to stream tokens (and a final Done) to that one
//! request.
//!
//! SCHEDULER LOOP: the worker holds a `Vec<Session>` of active generations. Each iteration it
//! round-robin steps EVERY active session by exactly ONE `decode_step` (one token of prefill OR
//! one decode token), samples, checks stop, streams the token text back on that session's channel,
//! and retires finished sessions. Queued admits fill empty slots up to `MAX_ACTIVE`. This is the
//! interleave: a long generation and a freshly-admitted one make forward progress in the same loop,
//! so the second produces tokens before the first finishes (not serialized end-to-end).

use std::collections::{HashMap, VecDeque};
use std::io::Write as _;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Instant;

use cudarc::driver::CudaSlice;
use memra_engine::Engine;
use memra_engine::cache::Cache;
use memra_engine::decode::{GenParams, StopReason};
use memra_engine::hybrid::HybridModel;
use memra_engine::sampler::{Sampler, SamplerConfig};
use memra_gguf::GgufFile;
use memra_tokenizer::Tokenizer;

/// Max concurrently-active sessions in legacy round-robin mode (MEMRA_SERVE_BATCH=0).
/// Batched scheduling caps at MEMRA_MAX_SESSIONS (default 64). Admits beyond the cap queue (FIFO).
pub const MAX_ACTIVE: usize = 4;

/// `GenParams.max_new` sentinel: the request OMITTED `max_tokens` (gap-scan F2), so the
/// generation budget is CONTEXT-BOUNDED — session ctx minus prompt tokens, model-capped —
/// the OpenAI default-when-omitted semantics, never a silent 128-token truncation.
/// (`budget = max_new.min(room)` makes the sentinel safe everywhere downstream.)
pub const MAX_NEW_CTX_BOUNDED: usize = usize::MAX;

/// Per-tick prefill chunk cap: tokens primed per scheduler tick per session. Priming runs at
/// prefill throughput instead of tokenwise decode, while the per-tick cap keeps round-robin
/// latency for concurrent sessions bounded.
const PREFILL_TICK_T: usize = 1024;

/// A lone fresh interactive request can use the engine's full eight-microbatch PP geometry in
/// one outer `prime_cache` call. Multi-session ticks retain `PREFILL_TICK_T` fairness, and an
/// explicit `MEMRA_PREFILL_TICK` remains authoritative.
const SOLO_PREFILL_TICK_T: usize = 8192;

fn interactive_prefill_budget(
    configured: usize,
    configured_explicitly: bool,
    sole_unfinished: bool,
    fresh: bool,
    queued: usize,
) -> usize {
    if configured_explicitly || !sole_unfinished || !fresh {
        return configured;
    }
    let mut widened = queued.min(SOLO_PREFILL_TICK_T);
    let tail = queued - widened;
    if tail > 0 && tail < memra_engine::hybrid_forward::PRIME_MIN_T {
        widened = queued;
    }
    configured.max(widened)
}

fn tick_trace_enabled() -> bool {
    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var("MEMRA_TICK_TRACE").as_deref() == Ok("1"))
}

/// A model loaded resident on the worker thread: weights + its own tokenizer + config snapshot.
struct LoadedModel {
    model: HybridModel,
    tok: Tokenizer,
    eos_id: u32,
    /// Loaded from a checkpoint DIRECTORY (safetensors/repack) rather than a GGUF file.
    /// Feeds ModelCaps::chat_ok: a dir checkpoint with no chat template 400s on chat
    /// requests (serve-st v1 honesty gate) instead of silently rendering fallback ChatML;
    /// GGUF models keep the historical ChatML fallback.
    from_dir: bool,
    /// Constrained-decoding grammar factory (llguidance TokTrie over this vocab). Built
    /// LAZILY on the first `response_format` request against this model — unconstrained
    /// serving never pays the vocab-trie build. `Err` = vocab unusable (kept, so every
    /// constrained request fails with the same clean message instead of rebuilding).
    constraints: std::cell::OnceCell<Result<crate::constrained::ConstraintFactory, String>>,
}

/// What the worker streams back to one request, over its per-request tokio mpsc channel.
#[derive(Debug, Clone)]
pub enum Event {
    /// One decoded token: the raw id + the incremental text delta (detokenized tail minus prefix).
    Token { id: u32, text: String },
    /// Authoritative terminal token ids for blocking native responses. Streaming consumers ignore
    /// this snapshot; it precedes `Done` and must agree with the per-token event sequence.
    TokenSnapshot(Vec<u32>),
    /// Terminal event: why we stopped + final token count + timing. `n_prompt` / `n_cached`
    /// are WORKER-TRUTH prompt accounting: total prompt tokens this session fed or resumed —
    /// the tokenized RENDERED prompt (tools block included when one was rendered; the
    /// text-prefix spec resume counts the actually-fed remainder) — and how many of those
    /// came from a cache (continuation pool, spec resume, or the cross-request prefix cache)
    /// instead of being computed — the OpenAI `usage.prompt_tokens_details.cached_tokens`
    /// source. ONE source of truth: both counts come off the same rendered-prompt token ids.
    /// `spec` = THIS request's spec-decode acceptance summary (lane/accept-telemetry) —
    /// None on non-spec sessions, so the usage surface is byte-identical when spec is off.
    Done { stop_reason: String, n_tokens: usize, n_prompt: usize, n_cached: usize,
           elapsed_s: f64, spec: Option<SpecUsage> },
    /// The request failed. CLASSIFIED at the producer (`EngineError`) — the HTTP layer maps
    /// the class to a status code instead of calling everything a 400 (G6).
    Error(EngineError),
}

/// THE ERROR TAXONOMY (lane/serve-hardening, 2026-08-06; audit gap G6/G16).
///
/// WHAT WAS BROKEN: `Event::Error(String)` carried no type information, so `main.rs`'s only
/// possible mapping was `bad_request(&msg)` — CUDA faults, VRAM exhaustion, tokenizer
/// failures and genuine client mistakes all left as `400 invalid_request_error`. Two
/// consequences, both bad: 400 is non-retryable by SDK convention (openai-python retries
/// 408/409/429/>=500 only), so a transient GPU blip became a hard user-visible failure that
/// no client would retry; and a real engine fault was invisible in any client's or
/// aggregator's 5xx error-rate view.
///
/// WHERE THE CLASS COMES FROM: the PRODUCER, not a regex over the message. The site that
/// raises the failure is the only place that knows whether the caller or the box is at
/// fault, and a string-matching classifier in the HTTP layer would silently reclassify every
/// time someone reworded an error. The one text-driven rule is deliberate and quoted:
/// `EngineError::engine()` promotes a message containing the driver's own OOM text to
/// `Overloaded`, because a CUDA OOM IS capacity — see `is_cuda_oom`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrClass {
    /// The caller can fix this. -> 400 invalid_request_error.
    InvalidRequest,
    /// Prompt does not fit the context. -> 400 + `code: context_length_exceeded`, the
    /// machine-readable form every client uses to decide "summarize and retry" (G16).
    ContextLength,
    /// Unknown model id. -> 400 + `code: model_not_found`.
    ///
    /// WHY 400 AND NOT 404: OpenRouter's uptime math counts 404 against the provider while
    /// 400 is excluded (§2.2), and "you asked for a model this endpoint does not serve" is
    /// squarely a client error — taking an uptime hit for it would be self-punishment for
    /// someone else's typo. The `code` is what clients branch on either way.
    ModelNotFound,
    /// Admission-time QoS shed: this lane is over its budget RIGHT NOW and a retry in a
    /// couple of seconds will work. -> 429 + Retry-After. Uptime-neutral at OpenRouter, and
    /// their own guidance prefers an early 429 to queueing.
    RateLimit,
    /// The BOX is out of capacity (VRAM exhausted, step OOM past its park budget). -> 503,
    /// not 429: "a 429 that a client cannot fix by waiting should not be a 429", and OpenAI
    /// itself serves overload as 503. This one honestly counts against uptime, because it is
    /// a request we failed to serve.
    Overloaded,
    /// An engine/GPU fault: a step, prefill, graph, or constraint operation failed. -> 500.
    Engine,
}

/// A classified failure. `message` stays the exact producer text (quoted, never rewritten —
/// the evidence-discipline law applies to what the client sees too).
#[derive(Debug, Clone)]
pub struct EngineError {
    pub class: ErrClass,
    pub message: String,
    /// OpenAI `error.param` when the failure names a request field.
    pub param: Option<&'static str>,
}

impl EngineError {
    /// Every invalid-request the WORKER can produce names a request field (it has already been
    /// through request parsing), so there is deliberately no param-less constructor — the
    /// flags doctrine applies to APIs too: no dead arm.
    pub fn invalid_param(message: impl Into<String>, param: &'static str) -> Self {
        Self { class: ErrClass::InvalidRequest, message: message.into(), param: Some(param) }
    }
    pub fn context_length(message: impl Into<String>) -> Self {
        Self { class: ErrClass::ContextLength, message: message.into(), param: Some("messages") }
    }
    pub fn model_not_found(message: impl Into<String>) -> Self {
        Self { class: ErrClass::ModelNotFound, message: message.into(), param: Some("model") }
    }
    pub fn rate_limit(message: impl Into<String>) -> Self {
        Self { class: ErrClass::RateLimit, message: message.into(), param: None }
    }
    pub fn overloaded(message: impl Into<String>) -> Self {
        Self { class: ErrClass::Overloaded, message: message.into(), param: None }
    }
    /// An engine fault. A message carrying the DRIVER'S OWN out-of-memory text is promoted to
    /// `Overloaded` (503 + Retry-After) rather than reported as a 500: the box ran out of
    /// VRAM, which is a capacity condition a retry can clear, not a bug in the engine. The
    /// test is `is_cuda_oom` — the same quoted-text predicate the step-OOM park path uses, so
    /// the two paths can never disagree about what an OOM is.
    pub fn engine(message: impl Into<String>) -> Self {
        let message = message.into();
        let class = if is_cuda_oom(&message) { ErrClass::Overloaded } else { ErrClass::Engine };
        Self { class, message, param: None }
    }
}

/// Per-request spec-decode acceptance summary (lane/accept-telemetry, 2026-08-05): THIS
/// request's own rounds/drafted/accepted, diffed off the session telemetry around each burst
/// (a pool-resumed session carries prior requests' cumulative counts — the diff isolates
/// this request). Rides `Event::Done` into the response `usage` block as an additive
/// OpenAI-safe extension field.
#[derive(Debug, Clone, Copy, Default)]
pub struct SpecUsage {
    pub rounds: u64,
    pub drafted: u64,
    pub accepted: u64,
}

/// A generation request submitted by an HTTP handler to the worker.
pub struct Request {
    pub model: String,
    pub prompt_ids: Vec<u32>,   // already tokenized? no — worker tokenizes (it owns the Tokenizer)
    pub prompt_text: String,
    pub chat: bool,
    pub chat_turns: Vec<memra_tokenizer::chat::Turn>,
    /// Tool schemas pre-serialized (client key order preserved) for the template's <tools> block.
    pub tools_json: Vec<String>,
    pub think: memra_tokenizer::chat::ThinkMode,
    /// step35-dialect reasoning level ("low"/"medium"/"high"), rendered as a string into the
    /// system turn (`Reasoning: {level}\n\n`). Only set by the HTTP layer when the model's
    /// template consumes it (`ModelCaps::effort_levels`); None = the template's own default
    /// (no `Reasoning:` line). Orthogonal to `think`: on switch-carrying templates
    /// `reasoning_effort` maps to ThinkMode instead and this stays None.
    pub reasoning_effort: Option<String>,
    pub params: GenParams,
    pub sampler_cfg: SamplerConfig,
    pub stop_strings: Vec<String>,
    pub trace_id: Option<String>,
    /// PC-ISO cache namespace (lane/pc-iso, 2026-08-02): the tenant isolation salt for
    /// EVERY cross-request KV reuse tier (prefix cache, continuation pool, spec pool) —
    /// the vLLM `cache_salt` design. Derived by the HTTP layer (request `cache_salt`
    /// field; "" = the default single-tenant namespace, byte-identical to pre-PC-ISO).
    pub cache_ns: String,
    /// SESSION AFFINITY explicit tier (lane/session-affinity, 2026-08-05): the client's own
    /// name for this conversation (`session_id`/`user` body field, or the `x-session-id`
    /// header — see `crate::affinity_key`). Some(id) nominates that conversation's parked
    /// session directly; None falls back to the implicit structural fingerprint. Either way
    /// the resume decision is the exact token diff (`affinity_match`), scoped to this
    /// request's own (model, cache_ns) pool.
    pub affinity: Option<String>,
    /// yield lane (x-lane header; default interactive). Drives admission + prefill budgets
    /// (lane/dl-metering QoS gate, ported 2026-08-02 — the metering half stayed behind).
    pub lane: crate::lanes::Lane,
    /// STEP-OOM PARK budget already spent by this request (lane/admit-oom, 2026-08-06).
    /// Always 0 from the HTTP layer; only `park_requeue` sets it, carrying the count across
    /// a re-admit so the retry bound is per-REQUEST and a parked session cannot loop forever.
    pub oom_retries: u32,
    /// Request-owned speculative depth preserved across a step-OOM re-admit. Fresh HTTP
    /// requests leave this None and run the K policy after tokenization; a parked request
    /// carries Some(K), including K=0, so changing queue depth cannot change its decision.
    pub spec_k_replay: Option<usize>,
    /// Constrained decoding (`response_format` json_object/json_schema): the parsed
    /// grammar spec. None = unconstrained — the request takes the exact legacy path
    /// (no factory, no matcher, no masking branch).
    pub grammar: Option<crate::constrained::GrammarSpec>,
    /// Worker-owned rendered/tokenized prompt. Admission may revisit a queued request for many
    /// ticks; cache the result so a 256k request is not re-rendered and re-tokenized per defer.
    /// HTTP and step-OOM replay requests always start with None.
    pub(crate) prepared_prompt: Option<Vec<u32>>,
    /// Debug-only per-request phase timeline. None unless MEMRA_TTFT_TRACE=1.
    pub ttft: Option<Arc<crate::ttft::Trace>>,
    /// per-request stream back to the handler. tokio mpsc so the async side can await it.
    pub tx: tokio::sync::mpsc::UnboundedSender<Event>,
}

/// Chat-template capabilities probed from a loaded model's template at spawn time — the
/// HTTP layer rejects `tools` on models whose template has no tools branch BEFORE the
/// request reaches the worker, and arms the tool-call parser's think gate.
/// Plus the /v1/models metadata surface (serve-tail lane, 2026-08-04): trained context,
/// tokenizer family, chat-template family — worker truth captured once at spawn so the
/// HTTP layer never invents values (unknown = 0/""/None -> honest nulls in the route).
#[derive(Debug, Clone, Default)]
pub struct ModelCaps {
    /// template carries the qwen-class `<tools>` branch (tools + tool_response rendering).
    pub tools_branch: bool,
    /// template appends a `<think>` tail on the generation prompt (qwen think class).
    pub qwen_think: bool,
    /// template has the `enable_thinking` switch (ThinkMode::NoThink is honored).
    pub think_switch: bool,
    /// chat requests are honest against this model: it has a chat template, OR it is a
    /// GGUF (which keeps the historical plain-ChatML fallback). A safetensors/repack DIR
    /// checkpoint without a template 400s on /v1/chat/completions (serve-st v1 honesty
    /// gate) instead of silently rendering a format the model was never trained on.
    pub chat_ok: bool,
    /// model's trained context length (config; 0 = unknown) — /v1/models `context_length`.
    pub context_length: usize,
    /// tokenizer family (the GGUF/HF pre-tokenizer name, e.g. "qwen2"; "" = unknown).
    pub tokenizer: String,
    /// chat-template family ("chatml" / "gemma"); None = no template or unrecognized.
    pub instruct_type: Option<String>,
    /// template consumes a `reasoning_effort` STRING (the step35 dialect: rendered into the
    /// system turn as `Reasoning: {level}\n\n`). When true, the HTTP layer maps the OpenAI
    /// `reasoning_effort` body field onto `Request::reasoning_effort` instead of ThinkMode.
    pub effort_levels: bool,
    /// gemma4 thought-channel dialect (lane/gemma4-serve-gaps, 2026-08-07): the template's
    /// `strip_thinking` splits on `<|channel>thought…<channel|>`. When true, chat requests
    /// arm the gemma-dialect reasoning splitter so thought text routes to `reasoning` and
    /// the channel tags never reach the client as content.
    pub gemma_think: bool,
    /// Model-provider sampling defaults for OMITTED chat fields. `None` keeps the generic
    /// OpenAI-compatible defaults in the HTTP layer. Step35 uses StepFun's published API
    /// defaults (temperature 0.5, top_p 0.9); explicit client values always win.
    pub chat_temperature_default: Option<f32>,
    pub chat_top_p_default: Option<f32>,
}

/// Control messages into the worker. Currently just generation requests; /models and /health are
/// served from the cached model-name list captured at spawn (no need to round-trip the worker).
pub enum Cmd {
    Generate(Box<Request>),
}

/// Pending-admission gauge (lane/admission-latency, 2026-08-06): the HTTP handler increments
/// it right before sending `Cmd::Generate`; the worker decrements at pop (`handle_cmd`). A
/// spec burst polls it at every round boundary (the sse-cadence on_commit hook) and ENDS the
/// burst early when a request is waiting — the tick loop re-checks admission, so a newcomer's
/// wait stops scaling with MEMRA_SPEC_BURST (B128 held admits a whole ~1.3s burst out).
/// Burst size is content-neutral (spec-levers battery): the early exit moves WHEN control
/// returns, never what tokens say. Saturating decrement: a direct-channel sender that never
/// incremented (tests) must not underflow the gauge.
pub static PENDING_ADMITS: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Serving counters + engine-truth step latency, published every 32nd tick.
#[derive(Clone, Default)]
pub struct Metrics {
    pub admitted: u64,
    pub completed: u64,
    pub tokens_out: u64,
    pub step_p50_ms: f32,
    pub step_p99_ms: f32,
    /// worker-truth prompt accounting: total prompt tokens admitted, and how many of
    /// those were served from a cache (continuation pool / spec resume / prefix cache).
    pub prompt_tokens_in: u64,
    pub cached_tokens_in: u64,
    /// cross-request prefix cache state (hits/entries/resident bytes).
    pub prefix_hits: u64,
    pub prefix_entries: u64,
    pub prefix_bytes: u64,
    /// full prefix-cache counter set (lane/cache-metering, 2026-08-07): misses/inserts/
    /// evictions were already counted inside PrefixCache but never published; hit_tokens
    /// is the token-weighted hit mass (sum of entry lengths served) — the numerator the
    /// economics row wants when hits vary in depth.
    pub prefix_misses: u64,
    pub prefix_inserts: u64,
    pub prefix_evictions: u64,
    pub prefix_hit_tokens: u64,
    /// Serving-hardening counters and gauges (lane/cx-cachespec, 2026-08-09). These make
    /// cache/admission latency attributable from `/metrics` instead of requiring a server-log
    /// grep. Defers count admission decisions (a queued request may be deferred on multiple
    /// ticks); parks count successful step-OOM requeues. Pool entry fields are current gauges.
    pub admission_session_defers: u64,
    pub admission_vram_defers: u64,
    pub step_oom_parks: u64,
    pub continuation_pool_hits: u64,
    pub continuation_pool_evictions: u64,
    /// PLAIN-SESSION AFFINITY (lane/plain-affinity): continuation-pool resumes that rewound to a
    /// prompt-end checkpoint on a rewritten-history turn (subset of continuation_pool_hits).
    pub plain_affinity_rewinds: u64,
    pub spec_pool_hits: u64,
    pub spec_pool_misses: u64,
    pub spec_pool_affinity_rewinds: u64,
    pub spec_pool_evictions: u64,
    pub active_sessions: u64,
    pub queued_requests: u64,
    pub continuation_pool_entries: u64,
    pub spec_pool_entries: u64,
    pub cuda_driver_free_bytes: u64,
    pub cuda_pool_reserved_bytes: u64,
    pub cuda_pool_used_bytes: u64,
    pub cuda_pool_cached_bytes: u64,
    /// LCP length histogram (lane/cache-metering): one sample per prefix-cache PROBE —
    /// on a hit, the served entry's token length; on a miss, best_lcp against the pool
    /// (already computed there for the split-learning signal, so the histogram adds no
    /// scan). Buckets: [0], [1,16), [16,32), [32,64), [64,128), [128,256), [256,512),
    /// [512,1024), [1024,2048), [2048,4096), [4096,inf) — the [64,512) window is the
    /// tick-seg segmentation class. Spec-tier and non-batched requests never probe the
    /// prefix cache and are absent by construction.
    pub lcp_hist: [u64; 11],
    /// Per-tenant prompt accounting [prompt_tokens_in, cached_tokens_in], keyed by the
    /// TENANT half of the PC-ISO namespace (`meter_key`): keyring deployments aggregate
    /// one row per tenant across its end-user salts; no-keyring deployments key on the
    /// raw cache_salt ("" = the default namespace). Bounded at METER_TENANT_CAP rows —
    /// overflow traffic lands in "(other)" so a salt-spraying client cannot grow the map.
    pub ns_tokens: HashMap<String, [u64; 2]>,
    /// per-lane QoS counters [interactive, judge, harvest] — the x-lane yield gate
    /// (/yield/metrics, sidecar-compatible shape; lane/dl-metering QoS extraction).
    pub lane_admitted: [u64; 3],
    pub lane_shed: [u64; 3],
    pub lane_completed: [u64; 3],
    pub lane_tokens: [u64; 3],
    pub batch_size_last: usize,
    /// Per-model spec-decode acceptance telemetry (lane/accept-telemetry): cumulative
    /// since the model loaded — models load once per server process, so these counters
    /// reset on (re)load/restart, never mid-run. Empty (absent from /metrics) for models
    /// that never ran a spec burst — zero-cost when spec is off.
    pub spec: HashMap<String, memra_engine::spec::SpecTelemetry>,
    /// Detection-only ADSD acceptance-collapse incidents, keyed by the same tenant row
    /// identity as `ns_tokens`. The worker never evicts or throttles from this counter;
    /// operators apply the existing tenant/lane rate limit after investigation.
    pub adsd_suspect_total: HashMap<String, u64>,
}
pub type SharedMetrics = std::sync::Arc<std::sync::Mutex<Metrics>>;

/// Windowed percentile over decode-step latencies (ms) — the interactive SLO sensor.
/// Engine ground truth: the worker records the wall time of each batched decode tick that
/// advanced at least one interactive session — that IS the client-visible TPOT for that
/// tick. (Shared with out-of-process controllers via the memra-lanes crate.)
use crate::lanes::{Lane, StepStats};

/// Live per-session state on the worker thread. One `Session` per in-flight generation.
/// Holds the per-session `Cache` (model-specific dims — NO sharing between sessions, which is what
/// makes the concurrent streams byte-identical to isolated runs) and per-session `Sampler`.
/// KV PREFIX REUSE (append-only continuation): retired sessions park (fed tokens, Cache,
/// last_logits) here; a new request whose prompt EXACTLY EXTENDS a parked `fed` sequence takes
/// the Cache and primes only the suffix. Correct by construction for hybrid models: the
/// recurrent (conv/ssm) state in the Cache is the state AFTER the last fed token — the exact
/// resume point for an append-only continuation. NO arbitrary-prefix truncation is attempted
/// (GDN state cannot roll back without checkpoints); a non-extending prompt takes the cold path.
/// NOTE chat-template callers: templates that rewrite history (e.g. stripping think blocks from
/// prior assistant turns) break exact-extension and simply miss the pool — raw `prompt_ids`
/// callers (agent loops) always hit. Pool: at most MEMRA_REUSE_POOL entries per model, LRU.
struct ReuseEntry {
    fed: Vec<u32>,
    cache: Cache,
    last_logits: Vec<f32>,
    cap: usize,
    /// PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09): a retire-time checkpoint at a
    /// STABLE PRE-GENERATION boundary, so a later turn that REWRITES history (the pi client
    /// stripping `<think>` from prior assistant turns) can still recognize this conversation and
    /// rewind here — priming only its own delta instead of the whole growing conversation.
    /// `None` for a retire that could not capture one (a rig too tight for the GDN state copy;
    /// resume simply isn't available and the pool falls back to exact-extension only). See
    /// [`PlainCheckpoint`] and the plain-affinity probe in `admit`.
    ckpt: Option<PlainCheckpoint>,
    /// The conversation id the admitting request declared (`Request::affinity` — explicit tier).
    /// `Some(id)` nominates only; the resume decision is the exact token diff (`affinity_match`).
    affinity: Option<String>,
    /// Implicit-tier identity: fingerprint chain of this session's COMMITTED (== `fed`) tokens.
    /// Nominated by a shared leading run with a request's own chain (`fingerprint_affinity`).
    fingerprint: Vec<u64>,
    /// Global park age used only by admission reclaim. Per-key vector order remains unchanged.
    parked_at: Instant,
}
/// A retired PLAIN session's PROMPT-END-class boundary state — the rewind target for
/// plain-session affinity resume (lane/plain-affinity, 2026-08-09). The plain twin of
/// `memra_engine::spec::SpecCheckpoint`, but structurally simpler: a plain session owns one
/// tokenwise `Cache` (no draft scratch, no `last_h` anchor), so the checkpoint is exactly a
/// `Cache::snapshot` at the boundary plus the committed length and the boundary row's host
/// logits (needed to resume decode from the checkpoint when the suffix is empty — though the
/// probe declines empty-suffix resumes, the logits keep the entry self-describing).
///
/// WHY THIS BOUNDARY. The rewrite class this lane exists for mutates the text the session
/// GENERATED, never the prompt bytes the client resends verbatim. So turn N+1's prompt agrees
/// with turn N's committed tokens up to the point where turn N's own generation began — the
/// pre-generation boundary. Checkpointing there makes a resume prime only turn N+1's delta.
///
/// WHY IT IS SAFE TO ROLL BACK (the SWA-ring question, resolved). memra has NO ring buffer:
/// full-attn KV (including step35's SWA layers) is a read-side mask over a full `max_ctx`
/// allocation with absolute rope, so a rollback is a pure per-layer `len` truncation — the
/// exact operation `Cache::rollback` performs. GDN conv/ssm recurrent state has no position
/// index and IS mutated in place, so the snapshot holds a real device copy of it; rollback
/// restores that copy. This is byte-for-byte the state a fresh prime of `fed[..pos]` produces,
/// which is the whole exactness argument (identical to `spec_rewind_to_checkpoint`).
struct PlainCheckpoint {
    snap: memra_engine::cache::CacheSnapshot,
    /// Committed length at the boundary (== `snap.pos`, == cache.pos there).
    pos: usize,
    /// Host logits of row `pos - 1` (the boundary row) — the resume seed for an empty suffix.
    last_logits: Vec<f32>,
}
/// SPEC-session reuse (2026-07-05): a retired spec session parks WHOLE (trunk cache + draft
/// scratch + committed + next_pred). A new greedy request whose prompt exactly extends
/// `committed` resumes it — turn N+1 primes only the suffix (or nothing, the continuation
/// burst). Same exact-extension rule as ReuseEntry; the session-gate oracle covers this path.
struct SpecReuseEntry {
    sess: memra_engine::spec::SpecSession,
    /// detok(committed) — TEXT-level prefix matching (2026-07-06). Token-level starts_with
    /// missed ~50% of chat turn boundaries (detok->retok BPE merges differ at the seam). Text
    /// matching resumes whenever the new prompt string literally extends the parked
    /// conversation; only the remainder is tokenized (no BOS). Same acceptable-divergence class
    /// as llama serve's cache_prompt: the suffix's boundary tokenization may differ from a cold
    /// full-retok — committed tokens stay authoritative, spec==greedy exactness is untouched.
    committed_text: String,
    /// SESSION AFFINITY (lane/session-affinity): the conversation this session belongs to, as
    /// the admitting request declared it — `Some(id)` from the explicit tier
    /// (`session_id`/`user`/`x-session-id`), else None. Nomination only; see `affinity`.
    affinity: Option<String>,
    /// Implicit-tier identity: the fingerprint chain of the session's COMMITTED tokens (no
    /// live tail to drop). Nominated by a shared leading run with a request's own chain.
    fingerprint: Vec<u64>,
    /// Global park age used only by admission reclaim. Pool ownership/identity stays unchanged.
    parked_at: Instant,
}
/// Parked-cache pool cap per model (MEMRA_REUSE_POOL, default 2 — each parked cache holds
/// its full KV, ~119MB at ctx 8192 on the 9B, so the cap is a VRAM budget knob).
/// KNOWN CASCADE at the default (pinned 2026-07-31): park-on-retire evicts LRU
/// unconditionally, so a SEQUENTIAL multi-turn workload of N>cap sessions evicts each
/// next request's entry one step ahead of its arrival (0/N resumes), while the same
/// requests arriving CONCURRENTLY all probe the intact pool first (hit). Raise the cap
/// to >= the expected concurrent-session count when VRAM allows.
fn reuse_pool_per_model() -> usize {
    static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *N.get_or_init(|| std::env::var("MEMRA_REUSE_POOL").ok()
        .and_then(|v| v.parse().ok()).unwrap_or(2))
}
/// Minimum parked prefix worth reusing (below this, cold prime is cheaper than bookkeeping).
const REUSE_MIN_PREFIX: usize = 16;

/// F5 (spec-pool thrash, 2026-08-05 — research/specpool-20260804): learned per-model
/// spec-session sizing, process-lifetime (VRAM geometry is static per server run;
/// a restart re-probes). Two lessons the worker remembers so pool misses stop
/// re-paying doomed multi-GB cudaMalloc walks every turn:
#[derive(Default)]
struct SpecSizing {
    /// Models OBSERVED VRAM-tight: a spec-session alloc failed while a parked pool
    /// entry existed. Later misses on these models evict the (dead-weight) pool
    /// BEFORE allocating — the same eviction the failure path forced anyway, minus
    /// the failed alloc + full realloc churn (the owner's live thrash: "spec pool
    /// evicted (1) after alloc failure" once per request, every turn a miss).
    /// Rigs where ghost + new session both fit never set the flag and keep the
    /// parked entry's resume value.
    evict_first: std::collections::HashSet<String>,
    /// model -> largest ctx ask known to fit after a GENUINE (empty-pool) alloc
    /// failure — the right-size ladder's landing point. Later asks start here
    /// instead of re-laddering; never exceeds the request's own ctx_cap.
    learned_ctx: HashMap<String, usize>,
}

/// Worker-owned cumulative counters for the two whole-session reuse tiers. Prefix-cache
/// counters live on `PrefixCache` itself; these remain separate because speculative sessions
/// deliberately bypass that trunk-only cache.
#[derive(Default)]
struct ReuseMetrics {
    continuation_hits: u64,
    continuation_evictions: u64,
    spec_hits: u64,
    spec_misses: u64,
    spec_affinity_rewinds: u64,
    spec_evictions: u64,
    /// PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09): continuation-pool hits that
    /// resumed via a rewind checkpoint (rewritten-history turn) rather than exact extension.
    /// Subset of `continuation_hits`; the per-turn resume count the affinity gate reads out.
    plain_affinity_rewinds: u64,
}

/// Exact context allocation for a cache with one physically capped row class.
fn context_cache_bytes(
    bytes_per_token: usize,
    ring_bytes_per_token: usize,
    ring_rows: usize,
    ctx_cap: usize,
) -> usize {
    let flat = bytes_per_token.saturating_sub(ring_bytes_per_token);
    flat.saturating_mul(ctx_cap).saturating_add(
        ring_bytes_per_token.saturating_mul(ctx_cap.min(ring_rows)),
    )
}

/// Per-model request-shaped admission estimate. Full-attention rows scale with the request's
/// context cap; Step35 SWA rows stop at their physical ring cap. Everything else is a measured
/// high-water residual, never lowered by reuse or allocator-pool hits.
#[derive(Debug)]
struct AdmissionCostModel {
    plain_bytes_per_token: usize,
    spec_bytes_per_token: usize,
    plain_ring_bytes_per_token: usize,
    spec_ring_bytes_per_token: usize,
    ring_rows: usize,
    activation_bytes: usize,
    last_logged: Option<(usize, bool, usize)>,
}

impl AdmissionCostModel {
    fn new(model: &HybridModel) -> Self {
        let (plain_bytes_per_token, plain_ring_bytes_per_token, plain_ring_rows) =
            model.plain_session_kv_shape();
        let (spec_bytes_per_token, spec_ring_bytes_per_token, spec_ring_rows) =
            model.spec_session_kv_shape();
        debug_assert!(plain_ring_rows == 0 || spec_ring_rows == 0 || plain_ring_rows == spec_ring_rows);
        Self {
            plain_bytes_per_token,
            spec_bytes_per_token,
            plain_ring_bytes_per_token,
            spec_ring_bytes_per_token,
            ring_rows: plain_ring_rows.max(spec_ring_rows),
            activation_bytes: 0,
            last_logged: None,
        }
    }

    fn bytes_per_token(&self, spec: bool) -> usize {
        if spec {
            self.spec_bytes_per_token
        } else {
            self.plain_bytes_per_token
        }
    }

    fn ring_bytes_per_token(&self, spec: bool) -> usize {
        if spec {
            self.spec_ring_bytes_per_token
        } else {
            self.plain_ring_bytes_per_token
        }
    }

    fn context_bytes(&self, ctx_cap: usize, spec: bool) -> usize {
        context_cache_bytes(
            self.bytes_per_token(spec),
            self.ring_bytes_per_token(spec),
            self.ring_rows,
            ctx_cap,
        )
    }

    fn estimate(&self, ctx_cap: usize, spec: bool) -> usize {
        self.context_bytes(ctx_cap, spec)
            .saturating_add(self.activation_bytes)
    }

    /// Learn only the fixed residual beyond the exact context allocation.
    /// Returns the new high-water value when it moved.
    fn observe(&mut self, observed_bytes: usize, ctx_cap: usize, spec: bool) -> Option<usize> {
        let context = self.context_bytes(ctx_cap, spec);
        let residual = observed_bytes.saturating_sub(context);
        if residual > self.activation_bytes {
            self.activation_bytes = residual;
            Some(residual)
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RequestShape {
    ctx_cap: usize,
    budget: usize,
    need: usize,
}

impl RequestShape {
    /// Context-linear capacity admission must reserve for this request. Finite requests normally
    /// allocate `ctx_cap = prompt + max_new + 8`; an affinity grow uses the request-shaped
    /// speculative safety bound (`need`, +64) so ContextFull cannot preempt MaxNew. Charging the
    /// larger value keeps that small growth honest without inheriting the server's global cap.
    fn admission_cap(self) -> usize {
        self.ctx_cap.max(self.need)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParkedPool {
    Plain,
    Spec,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ParkedCandidate {
    pool: ParkedPool,
    key: PoolKey,
    index: usize,
    parked_at: Instant,
}

fn older_parked(
    current: Option<ParkedCandidate>,
    candidate: ParkedCandidate,
) -> Option<ParkedCandidate> {
    match current {
        Some(oldest) if oldest.parked_at <= candidate.parked_at => Some(oldest),
        _ => Some(candidate),
    }
}

fn oldest_parked_candidate(
    candidates: impl IntoIterator<Item = ParkedCandidate>,
) -> Option<ParkedCandidate> {
    candidates.into_iter().fold(None, older_parked)
}

fn oldest_parked(
    reuse: &HashMap<PoolKey, Vec<ReuseEntry>>,
    spec_reuse: &HashMap<PoolKey, Vec<SpecReuseEntry>>,
) -> Option<ParkedCandidate> {
    let plain = reuse.iter().flat_map(|(key, pool)| {
        pool.iter().enumerate().map(move |(index, entry)| ParkedCandidate {
            pool: ParkedPool::Plain,
            key: key.clone(),
            index,
            parked_at: entry.parked_at,
        })
    });
    let spec = spec_reuse.iter().flat_map(|(key, pool)| {
        pool.iter().enumerate().map(move |(index, entry)| ParkedCandidate {
            pool: ParkedPool::Spec,
            key: key.clone(),
            index,
            parked_at: entry.parked_at,
        })
    });
    oldest_parked_candidate(plain.chain(spec))
}

/// Drop exactly one globally-oldest parked session without changing either pool's shape.
fn evict_oldest_parked(
    reuse: &mut HashMap<PoolKey, Vec<ReuseEntry>>,
    spec_reuse: &mut HashMap<PoolKey, Vec<SpecReuseEntry>>,
    metrics: &mut ReuseMetrics,
) -> Option<ParkedPool> {
    let candidate = oldest_parked(reuse, spec_reuse)?;
    match candidate.pool {
        ParkedPool::Plain => {
            let empty = {
                let pool = reuse.get_mut(&candidate.key)
                    .expect("oldest plain parked entry vanished");
                drop(pool.remove(candidate.index));
                pool.is_empty()
            };
            if empty {
                reuse.remove(&candidate.key);
            }
            metrics.continuation_evictions += 1;
        }
        ParkedPool::Spec => {
            let empty = {
                let pool = spec_reuse.get_mut(&candidate.key)
                    .expect("oldest spec parked entry vanished");
                drop(pool.remove(candidate.index));
                pool.is_empty()
            };
            if empty {
                spec_reuse.remove(&candidate.key);
            }
            metrics.spec_evictions += 1;
        }
    }
    Some(candidate.pool)
}
/// Right-size ladder slack: a shrunken spec session's cap must cover
/// prompt + budget + this, so the burst-loop ContextFull guard
/// (`committed + k + 3 >= cache_max_ctx`) can NEVER fire before MaxNew — a
/// shrunken session emits exactly the tokens a full-size one would (the F5
/// exactness contract: pool sizing is pure perf). Worst case per burst:
/// committed reaches prompt + budget + overshoot (up to k accepted drafts past
/// max_new) + a carried pending, and the guard adds k + 3; served policy K <= 5
/// (operator pins may be deeper) — 64 covers the normal table with margin at ~2MB of KV.
/// Requests whose budget
/// already spans the whole ctx_cap (max_tokens omitted) cannot shrink and keep
/// the legacy tokenwise fallback on failure.
const SPEC_SHRINK_SLACK: usize = 64;
/// Ladder transient reserve: after a landing, this much VRAM must still be
/// PROBE-allocatable for forward-pass transients — prime chunk slabs (~140MB
/// apiece at MEMRA_PRIME_CHUNK=2048; the serve-script's measured 36.5k probe
/// passed with 1.3GB free) and the FA dequant workspace. Some transients live
/// on PANICKING lazy paths (expect()), so a session that "fits" with zero
/// headroom kills the worker on its first prefill (observed: ladder landed
/// 65536, embed-table upload OOM panic — research/specpool-20260804/
/// server-ladder-miss.log; the embed table is made resident fallibly at landing
/// for that reason). The probe is alloc-and-drop, not a mem_get_info read: the
/// async pool's pinned release threshold keeps freed blocks cached and
/// invisible to free-VRAM queries. A landing that can't clear the probe is
/// DROPPED and the ladder keeps shrinking; if even `need` can't, the request
/// takes the legacy tokenwise fallback (whose own alloc failure is a clean
/// quoted error — the pre-fix behavior, never a panic).
const SPEC_SHRINK_RESERVE: usize = 1536 << 20; // 1.5 GiB

/// PC-ISO pool key (lane/pc-iso, 2026-08-02): every cross-request reuse pool — the prefix
/// cache, the continuation pool, and the spec pool — keys on (model, cache namespace), not
/// model alone. The namespace is the request's `cache_salt` (vLLM cache_salt design, PR
/// #17045): a lookup only ever scans its own (model, ns) pool, so no token-prefix match can
/// cross a trust boundary, and the `cached_tokens` billing field can only reveal the
/// caller's own namespace's history (the CacheProbe/PROMPTPEEK mitigation —
/// research/cache-tools-20260802/REPORT.md §1.4/§4). "" is the default single-tenant
/// namespace: no salt supplied = today's behavior, byte-for-byte.
type PoolKey = (String, String);

/// Log suffix for a pool key's namespace: silent for the default "" namespace (default-path
/// log lines stay byte-identical to pre-PC-ISO), quoted otherwise.
fn ns_suffix(ns: &str) -> String {
    if ns.is_empty() { String::new() } else { format!(", ns {ns:?}") }
}

// ---------------- SESSION AFFINITY (lane/session-affinity, 2026-08-05) ----------------
//
// THE PROBLEM (receipts: research/specpool-20260804/RESULTS.md). The spec pool resumes a
// parked session only when the new prompt EXACTLY EXTENDS it — token-prefix, or (since
// 2026-07-06) text-prefix. Real agent clients rewrite conversation history between turns:
// the owner's client strips `<think>` blocks out of PRIOR assistant turns before re-sending,
// so turn N's prompt is NOT a prefix-extension of turn N-1's committed text. Both probes
// miss, the parked ~4GB session is discarded as dead weight, and every turn re-primes the
// whole growing conversation (11k-14k tokens ~= 3s TTFT vs llama's 0.19s).
//
// Affinity closes that gap by answering a DIFFERENT question than the prefix probes: not
// "does this prompt extend that session's bytes?" but "is this the SAME CONVERSATION as
// that session?". Once a candidate is nominated by identity, the resume decision is made by
// an EXACT token-level diff (see `AffinityMatch`) — identity nominates, bytes decide. That
// split is the whole safety argument: a fingerprint collision can only ever nominate a
// candidate whose committed tokens are then compared exactly, so it can cost a wasted probe,
// never a wrong resume.
//
// TWO TIERS.
//   (a) EXPLICIT (`AffinityKey::Explicit`) — the client names its conversation. Accepted from
//       two conventions, both documented in docs/SERVING.md ("Session affinity"):
//         * `session_id` / `user` request-body fields (OpenAI's `user` is the field real
//           clients already send; `session_id` is the explicit spelling),
//         * the `x-session-id` request header (the convention vLLM/TGI-adjacent proxies use).
//       Body beats header when both appear (the body is the caller's own statement of
//       identity; a header can be injected by an intermediary).
//   (b) IMPLICIT (`AffinityKey::Fingerprint`) — nothing named, so identity is STRUCTURAL: a
//       hash of the conversation's SHAPE that is invariant under exactly the rewrite class we
//       need to survive. See `conversation_fingerprint`.
//
// TENANT SCOPE. Affinity is stored per `PoolKey = (model, cache_ns)`, so an affinity key can
// only ever nominate a session inside its own PC-ISO namespace — affinity adds NO new
// cross-tenant reach beyond what the existing pools already have. (The api-keys lane's
// TenantCtx is not on this branch; when it merges, its per-key namespace derivation flows
// into `cache_ns` and affinity inherits the boundary for free.)

/// Prefix/suffix token window hashed per conversation segment (see `conversation_fingerprint`).
/// Small enough that a rewritten segment BODY doesn't perturb the hash, large enough that
/// distinct segments don't collide: the head pins "which turn is this" (role marker + opening
/// words) and the tail pins the segment's end boundary.
const FP_WINDOW: usize = 8;
/// Minimum segments before an implicit fingerprint is trusted to name a conversation. A
/// one-or-two-segment prompt is a generic opener (a bare system prompt shared by every fresh
/// conversation); nominating on it would cross-link unrelated conversations into one session.
const FP_MIN_SEGMENTS: usize = 3;

/// ROLLBACK SEAM (flags doctrine: the winner is the default; this exists to *disable* it).
/// `MEMRA_AFFINITY=0` makes the affinity probe decline every candidate, so admit falls back to
/// the pre-lane behavior: prefix probes only, cold full prime on a rewritten history.
///
/// This is not a tuning knob — it is the exactness A/B arm. The byte-identity gate
/// (`research/session-affinity-20260805/`) runs the SAME conversation twice, once resuming and
/// once with `MEMRA_AFFINITY=0`, and requires identical per-turn `text_sha`. Disabling the pool
/// outright (`MEMRA_REUSE_POOL=0`) would be a different comparison: it also drops the
/// token/text-prefix resumes, so a divergence could not be attributed to affinity.
fn affinity_enabled() -> bool {
    if memra_engine::pp::pp_host_bounce_active() {
        // Plain-affinity checkpoints call Cache::snapshot through the primary Engine. Hybrid
        // layers owned by another PP stage would therefore be peer-copied on this host class.
        return false;
    }
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("MEMRA_AFFINITY").map(|v| v != "0").unwrap_or(true))
}

/// FNV-1a over a token stream — a stable, allocation-free 64-bit mix. (Not a cryptographic
/// hash and does not need to be: a collision costs one wasted exact-diff probe, never a
/// wrong resume, and the pool it indexes is already tenant-scoped.)
fn fnv1a(seed: u64, toks: &[u32]) -> u64 {
    let mut h = seed;
    for &t in toks {
        for b in t.to_le_bytes() {
            h ^= b as u64;
            h = h.wrapping_mul(0x100000001b3);
        }
    }
    h
}

/// Structural fingerprint of a conversation: the CHAIN of per-segment boundary hashes, one
/// entry per conversation segment in order, each hashing only that segment's (head window,
/// tail window) — never its interior.
///
/// WHY A CHAIN, NOT ONE HASH. Turn N+1 of a conversation has strictly MORE segments than turn
/// N (the previous answer plus a new user turn were appended), so a single whole-conversation
/// digest can never match across turns. Identity is therefore a PREFIX relation over the
/// chain (`fingerprint_affinity`): the parked session's conversation is an ancestor of this
/// request's when their chains share a long-enough leading run.
///
/// WHY BOUNDARY WINDOWS. The rewrite class we must tolerate mutates the INTERIOR of prior
/// assistant segments (a stripped `<think>` block is deleted text inside a turn). Hashing only
/// each segment's first and last few tokens leaves those edits invisible while still separating
/// genuinely different segments. Where a rewrite reaches into a head window too (a `<think>`
/// tag can sit right after the role marker), the chain degrades GRACEFULLY instead of failing:
/// that one segment's hash changes, the shared leading run simply ends earlier, and the
/// candidate is still nominated on the stable prefix (system prompt + early turns, which no
/// client rewrites). Nomination only has to be a good guess — `affinity_match` decides on bytes.
///
/// SEGMENTATION on the raw-prompt path. The owner's client renders the chat template
/// CLIENT-side and posts raw `/v1/completions`, so there is no `chat_turns` structure to walk:
/// the worker sees one flat token stream. Segments are recovered from the stream itself by
/// splitting at the template's own turn-marker tokens (the tokenizer's control tokens — exactly
/// what a chat template emits at every turn boundary: `<|im_start|>`/`<|im_end|>` and friends).
/// The implicit tier therefore works identically for client-rendered raw prompts and for
/// server-rendered `/v1/chat/completions` traffic.
///
/// `is_boundary(tok)` reports whether a token is a template turn marker. `drop_live` excludes
/// the trailing segment (a REQUEST's last segment is the turn being generated — new every turn
/// by construction, so it must not contribute to identity; a PARKED session's committed stream
/// has no such live tail and keeps every segment).
fn conversation_fingerprint(
    toks: &[u32],
    is_boundary: &dyn Fn(u32) -> bool,
    drop_live: bool,
) -> Vec<u64> {
    // Split into segments at boundary tokens. The boundary token itself joins the segment it
    // opens, so a segment's head window carries its own role marker.
    let mut segs: Vec<(usize, usize)> = Vec::new();
    let mut start = 0usize;
    for (i, &t) in toks.iter().enumerate() {
        if is_boundary(t) && i > start {
            segs.push((start, i));
            start = i;
        }
    }
    if start < toks.len() {
        segs.push((start, toks.len()));
    }
    if drop_live && !segs.is_empty() {
        segs.pop();
    }
    segs.iter()
        .map(|&(lo, hi)| {
            let seg = &toks[lo..hi];
            let head = &seg[..FP_WINDOW.min(seg.len())];
            let tail = &seg[seg.len().saturating_sub(FP_WINDOW)..];
            fnv1a(fnv1a(0xcbf29ce484222325, head), tail)
        })
        .collect()
}

/// Length of the leading run two fingerprint chains share. `>= FP_MIN_SEGMENTS` is the
/// nomination bar: below it the shared run is a generic opener (a bare system prompt is
/// byte-identical across every fresh conversation with the same client), and nominating on it
/// would cross-link unrelated conversations. Markerless raw prompts produce a 1-segment chain
/// and so can never clear the bar — non-chat callers keep the plain prefix probes untouched.
fn fingerprint_affinity(a: &[u64], b: &[u64]) -> usize {
    a.iter().zip(b).take_while(|(x, y)| x == y).count()
}

/// Verdict of the EXACT token diff run against an affinity-nominated parked session. Identity
/// nominated the candidate; this decides — on bytes — whether resuming it is EXACT.
///
/// THE EXACTNESS CONTRACT. A resumed session must emit BYTE-IDENTICAL output to a fresh full
/// prime of the same request. The committed tokens in the parked caches are authoritative
/// state: whatever they are, the caches hold exactly their KV/recurrent state. So resuming is
/// exact iff the new prompt begins with the session's ENTIRE committed sequence — then the
/// caches are precisely "the state after the prompt's first `committed.len()` tokens" and only
/// the remaining suffix needs priming. Any DIVERGENCE inside the committed range means the
/// caches hold state for tokens this request does not have, and no amount of suffix priming
/// can repair that (hybrid GDN recurrent state is mutated in place and has no per-position
/// index to truncate). There is one legal repair — roll the session back to the divergence
/// point — and it requires a checkpoint AT that boundary, which a parked session does not
/// carry. So divergence inside the committed range is a full re-prime, always. Correctness
/// first; the affinity win comes from the (dominant) case where the rewrite touches only text
/// the session has not committed yet.
#[derive(PartialEq, Eq, Debug)]
enum AffinityMatch {
    /// The prompt begins with the session's entire committed sequence: resume, prime the
    /// `suffix_from` tail only. (`suffix_from == prompt.len()` = pure continuation burst.)
    Exact { suffix_from: usize },
    /// The prompt diverges from the committed tokens at this index: the parked caches hold
    /// state for tokens this request does not have. Full re-prime.
    Diverged { at: usize },
}

/// Exact token-level diff of a request's prompt against a parked session's committed tokens.
/// The ONLY authority on whether an affinity-nominated session may be resumed.
fn affinity_match(prompt: &[u32], committed: &[u32]) -> AffinityMatch {
    let n = committed.len().min(prompt.len());
    for i in 0..n {
        if prompt[i] != committed[i] {
            return AffinityMatch::Diverged { at: i };
        }
    }
    if prompt.len() < committed.len() {
        // The prompt is a strict PREFIX of committed: the session has generated past what
        // this request contains (a client that dropped its own tail, or a re-issued earlier
        // turn). The caches hold extra committed rows with no boundary checkpoint to trim
        // them at — treat as divergence at the prompt's end.
        return AffinityMatch::Diverged { at: prompt.len() };
    }
    AffinityMatch::Exact { suffix_from: committed.len() }
}

/// Decide whether an affinity candidate can resume and which cache capacity it needs.
/// Identity only nominates; the checkpoint bounds and exact token comparison remain authoritative.
/// A too-small parked cache is a grow request, not a decline: returning the incoming request's
/// charged required capacity lets the caller allocate and restore a larger cache before resume.
fn affinity_resume_target(
    prompt: &[u32],
    committed: &[u32],
    checkpoint_pos: usize,
    parked_cap: usize,
    request_cap: usize,
    identity_matches: bool,
) -> Result<usize, String> {
    if checkpoint_pos == 0 || checkpoint_pos > committed.len() {
        return Err(format!(
            "bad checkpoint pos {checkpoint_pos} of {}",
            committed.len(),
        ));
    }
    match affinity_match(prompt, &committed[..checkpoint_pos]) {
        AffinityMatch::Exact { suffix_from } if suffix_from == checkpoint_pos => {}
        AffinityMatch::Diverged { at } => {
            return Err(format!(
                "history diverged at {at} of checkpoint {checkpoint_pos}",
            ));
        }
        _ => return Err("diff did not land on the checkpoint".into()),
    }
    if prompt.len() == checkpoint_pos {
        return Err("empty suffix".into());
    }
    if !identity_matches {
        return Err("identity did not nominate".into());
    }
    Ok(parked_cap.max(request_cap))
}

/// PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09): the STABLE PRE-GENERATION boundary
/// this prompt's rewind checkpoint should sit at, as a `prompt`-length index.
///
/// WHY NOT PROMPT-END. The spec-tier checkpoint sat at prompt-end and the forced-spec control in
/// `research/cachespec-20260809/RESULTS.md` disproved it: the frozen pi workload's turn N+1
/// diverges from turn N a couple tokens BELOW prompt-end, inside the template's live
/// assistant-generation header (`<|im_start|>assistant\n<think>\n`), which the client rewrites.
/// A checkpoint at prompt-end therefore always sits past the divergence and declines 100% of the
/// time. The fix (RESULTS.md §P0): checkpoint BEFORE the last turn-marker run — the stable point
/// every prior turn's prompt shares.
///
/// HOW. Chat traffic (client- or server-rendered) carries the tokenizer's turn-marker control
/// tokens (`<|im_start|>`/`<|im_end|>` and friends). The last MAXIMAL run of control tokens at
/// the prompt tail is the live generation header; the boundary is just before it. Raw completions
/// with no markers fall back to a conservative guard window (`PLAIN_CKPT_RAW_GUARD`, in the
/// RESULTS.md 8..32 band) trimmed off the end. The exact token diff (`affinity_match`) still
/// DECIDES on bytes, so a mis-located boundary only costs a decline, never a wrong resume — the
/// value 2 the control observed is NEVER hardcoded.
///
/// Returns `None` when no useful boundary exists (prompt too short to be worth a checkpoint, or
/// the boundary would land at/below `REUSE_MIN_PREFIX`). A `Some(b)` always satisfies
/// `REUSE_MIN_PREFIX <= b < prompt.len()`.
fn plain_checkpoint_boundary(prompt: &[u32], is_control: &dyn Fn(u32) -> bool) -> Option<usize> {
    let n = prompt.len();
    if n <= REUSE_MIN_PREFIX + PLAIN_CKPT_RAW_GUARD {
        return None;
    }
    // WHY THE LAST TURN-MARKER, worked through on the pi rewrite. Turn N's session commits
    //   [history][userN] <|im_start|>assistant\n<think>\n [genN...]
    // and its prompt-END is at "<think>\n" (before genN). Turn N+1's prompt is
    //   [history][userN] <|im_start|>assistant\n [genN-with-think-stripped] <|im_end|>
    //     [userN+1] <|im_start|>assistant\n<think>\n
    // The two agree through "<|im_start|>assistant\n" and DIVERGE at the next token: turn N has
    // "<think>", turn N+1 has the stripped answer's first token. That divergence sits a couple
    // tokens BELOW turn N's prompt end — exactly the "diverged at ckpt-2" the forced-spec control
    // measured, which is why a prompt-END checkpoint declines 100% of the time.
    //
    // The stable point every later turn resends verbatim is the START of the live-generation
    // segment: the LAST turn-marker control token (the `<|im_start|>` opening the assistant turn).
    // `committed[..last_marker]` = "[history][userN]<|im_end|>", which turn N+1 reproduces exactly;
    // the whole live turn (marker + role header + generation) becomes the primed suffix. The role
    // name and `<think>` opener are ORDINARY vocab tokens, not control tokens, so they never move
    // the boundary — only the tokenizer's turn markers do. The exact diff at resume still decides
    // on bytes; a mis-located boundary costs a decline, never a wrong resume, and the observed
    // value 2 is NEVER hardcoded.
    if let Some(last_marker) = prompt.iter().rposition(|&t| is_control(t)) {
        if last_marker > REUSE_MIN_PREFIX && last_marker < n {
            return Some(last_marker);
        }
        // The last marker is too early (a giant final turn with no interior markers) or is the
        // final token (a bare closing marker, empty live turn). Fall through to the guard window.
    }
    // Markerless raw completions (or a degenerate marker position): trim a conservative guard
    // window off the end so the live tail — which a re-ask may extend or rewrite — is never
    // inside the checkpoint.
    let b = n - PLAIN_CKPT_RAW_GUARD;
    if b > REUSE_MIN_PREFIX { Some(b) } else { None }
}

/// Conservative guard window for the markerless (raw-completion) path of
/// `plain_checkpoint_boundary`. RESULTS.md §P0 specifies an 8..32 band; 16 is the middle and
/// matches `PRIME_MIN_T`, so a boundary-stopped prime never leaves a sub-floor residual.
const PLAIN_CKPT_RAW_GUARD: usize = 16;

/// Could a PARKED entry for this prompt ever be NOMINATED by the IMPLICIT tier? The implicit
/// tier compares fingerprint chains and requires a shared leading run of `FP_MIN_SEGMENTS`;
/// a prompt whose own chain cannot reach that bar can never be implicitly nominated, so
/// capturing a checkpoint for it — absent an explicit id — is pure cost. WORSE than cost:
/// an armed `ckpt_at` excludes the session from the in-batch fanout and prime-batch paths
/// (they prime monolithically and cannot honor the per-session boundary stop), which is
/// exactly the cache-metering regression the tip battery caught (2026-08-09, 13 checks red:
/// a 5-way shared-prefix raw-`prompt_ids` fanout never fired because every session armed a
/// guard-window checkpoint it could never use — 0 prefix hits, 6 misses/inserts, empty LCP
/// window). Chat-template traffic keeps its markers and clears the bar; raw agent loops that
/// want affinity name their conversation (`session_id`/`user`/`x-session-id`), which arms the
/// capture through the explicit tier instead.
///
/// The chain here is over the PROMPT with `drop_live=false` — the parked entry's chain is
/// taken over `fed` (prompt + generation, no live tail), whose segment count is >= this, so
/// this is the conservative lower bound on what a later request could share.
fn plain_ckpt_nominatable(prompt: &[u32], is_control: &dyn Fn(u32) -> bool) -> bool {
    conversation_fingerprint(prompt, is_control, false).len() >= FP_MIN_SEGMENTS
}

// ---------------- CROSS-REQUEST PREFIX CACHE (lane/prompt-cache, 2026-08-02) ----------------
//
// The continuation pool above only serves a prompt that EXACTLY EXTENDS a retired session's
// whole fed sequence (prompt + generation) — a NEW session that merely shares a system-prompt
// prefix with earlier traffic always misses. The prefix cache closes that gap: entries are
// compact device copies of primed state at a TOKEN boundary, keyed by the exact token-id
// prefix, and are REUSABLE (a hit deep-copies the entry into the new session's cache — one
// marketplace system prompt serves any number of sessions, unlike the move-out pool).
//
// WHY snapshots, not truncation: hybrid models (qwen35-class GDN) carry recurrent conv/ssm
// state that cannot roll back to an arbitrary shorter prefix, so a longer cache can never be
// trimmed to the shared prefix. Instead the state is captured AT the boundary while a fresh
// session primes:
//   - SEED: a cold session's full prompt is inserted at prefill-done (before any decode).
//   - LCP SPLIT (the learning step): a cold miss whose prompt shares >= PREFIX_CACHE_MIN_TOKENS
//     tokens with an existing entry splits its own prime at the longest-common-prefix point,
//     snapshots there, then continues — request 3+ of a shared-system-prompt pattern hits.
//
// EXACTNESS CONTRACT (docs/SERVING.md "Prompt caching"): an entry stores the KV/recurrent
// bytes from WHATEVER prime config ran (single, chunked, or concat batch-prime); decode from
// those bytes is deterministic, so serving a hit is bit-identical to the run that computed the
// prefix. Cross-config comparisons (a cached-hit stream vs a whole-prompt fresh prime) inherit
// the documented batched-prime near-tie first-token law — same class, not a new one.
//
// VRAM: entries compete with session KV under MEMRA_PREFIX_CACHE_MB (default 256; 0 disables),
// LRU-evicted, per-model keyed; a failed session-cache alloc evicts the whole cache and
// retries (headroom discipline — sessions always win over the cache).
//
// POLICY: spec sessions bypass the prefix cache entirely (SpecSession owns trunk + draft
// caches; restoring a trunk-only prefix would leave draft state unprimed). The spec tier keeps
// its own continuation pool; the prefix cache serves the batched bulk tier. Legacy round-robin
// mode (MEMRA_SERVE_BATCH=0) also bypasses.
//
// ISOLATION (PC-ISO, lane/pc-iso 2026-08-02): pools key on (model, cache namespace) — see
// PoolKey. Same-namespace traffic shares entries exactly as before; requests carrying
// different `cache_salt` values never see each other's prefixes, in either direction.

/// Prefixes shorter than this are not worth VRAM + copy bookkeeping (also keeps the bare
/// chat-template header — common to every request of a model — out of the cache).
const PREFIX_CACHE_MIN_TOKENS: usize = 64;

/// Max distinct per-tenant metering rows in `Metrics::ns_tokens` (lane/cache-metering).
/// Past the cap, new tenants/salts aggregate under "(other)" — the totals stay exact,
/// only per-row attribution saturates. 256 covers any realistic keyring; the bound
/// exists so an unauthenticated client spraying cache_salt values cannot grow the map.
const METER_TENANT_CAP: usize = 256;

/// ADSD acceptance-collapse detector. The tenant signal is a short request window; the
/// comparison population is a larger rolling window for the same model. A 3-sigma deficit
/// alone is too sensitive once token counts get large, so an incident also requires a
/// collapse-shaped absolute drop and three consecutive anomalous observations. This is an
/// operational signal only: it never changes the lossless verifier or serving policy.
const ADSD_TENANT_WINDOW: usize = 8;
const ADSD_MODEL_WINDOW: usize = 64;
const ADSD_BASELINE_MIN_SAMPLES: usize = 16;
const ADSD_BASELINE_MIN_DRAFTED: u64 = 512;
const ADSD_TENANT_MIN_DRAFTED: u64 = 128;
const ADSD_Z_THRESHOLD: f64 = -3.0;
const ADSD_MIN_RATE_DROP: f64 = 0.20;
const ADSD_REARM_RATE_DROP: f64 = 0.10;
const ADSD_SUSTAINED_OBSERVATIONS: u8 = 3;

#[derive(Default)]
struct AcceptanceWindow {
    samples: VecDeque<(u64, u64)>,
    accepted: u64,
    drafted: u64,
}

impl AcceptanceWindow {
    fn push(&mut self, accepted: u64, drafted: u64, cap: usize) {
        self.samples.push_back((accepted, drafted));
        self.accepted += accepted;
        self.drafted += drafted;
        while self.samples.len() > cap {
            let (old_accepted, old_drafted) = self.samples.pop_front().unwrap();
            self.accepted = self.accepted.saturating_sub(old_accepted);
            self.drafted = self.drafted.saturating_sub(old_drafted);
        }
    }

    fn rate(&self) -> f64 {
        self.accepted as f64 / self.drafted.max(1) as f64
    }
}

#[derive(Default)]
struct TenantAcceptance {
    window: AcceptanceWindow,
    anomalous_observations: u8,
    incident_latched: bool,
}

#[derive(Debug)]
struct AdsdSuspect {
    model: String,
    tenant: String,
    baseline_rate: f64,
    tenant_rate: f64,
    z_score: f64,
    drafted: u64,
}

#[derive(Default)]
struct AdsdDetector {
    model_windows: HashMap<String, AcceptanceWindow>,
    tenant_windows: HashMap<(String, String), TenantAcceptance>,
    suspect_total: HashMap<String, u64>,
}

impl AdsdDetector {
    fn observe(
        &mut self,
        model: &str,
        tenant: &str,
        accepted: u64,
        drafted: u64,
    ) -> Option<AdsdSuspect> {
        if drafted == 0 || accepted > drafted {
            return None;
        }
        let baseline = self.model_windows.get(model).and_then(|window| {
            (window.samples.len() >= ADSD_BASELINE_MIN_SAMPLES
                && window.drafted >= ADSD_BASELINE_MIN_DRAFTED)
                .then(|| window.rate())
        });

        let mut key = (model.to_string(), tenant.to_string());
        if !self.tenant_windows.contains_key(&key)
            && self.tenant_windows.len() >= METER_TENANT_CAP
        {
            key.1 = "(other)".into();
        }
        let state = self.tenant_windows.entry(key.clone()).or_default();
        state.window.push(accepted, drafted, ADSD_TENANT_WINDOW);

        let mut suspect = None;
        if let Some(baseline_rate) = baseline {
            if state.window.samples.len() == ADSD_TENANT_WINDOW
                && state.window.drafted >= ADSD_TENANT_MIN_DRAFTED
            {
                let tenant_rate = state.window.rate();
                let variance = (baseline_rate * (1.0 - baseline_rate)
                    / state.window.drafted as f64)
                    .max(f64::EPSILON);
                let z_score = (tenant_rate - baseline_rate) / variance.sqrt();
                let rate_drop = baseline_rate - tenant_rate;
                let anomalous = rate_drop >= ADSD_MIN_RATE_DROP
                    && z_score <= ADSD_Z_THRESHOLD;
                if anomalous {
                    state.anomalous_observations =
                        state.anomalous_observations.saturating_add(1);
                    if state.anomalous_observations >= ADSD_SUSTAINED_OBSERVATIONS
                        && !state.incident_latched
                    {
                        state.incident_latched = true;
                        suspect = Some(AdsdSuspect {
                            model: model.to_string(),
                            tenant: key.1.clone(),
                            baseline_rate,
                            tenant_rate,
                            z_score,
                            drafted: state.window.drafted,
                        });
                    }
                } else {
                    state.anomalous_observations = 0;
                    if rate_drop <= ADSD_REARM_RATE_DROP {
                        state.incident_latched = false;
                    }
                }
            }
        }

        self.model_windows.entry(model.to_string()).or_default()
            .push(accepted, drafted, ADSD_MODEL_WINDOW);
        if let Some(event) = suspect.as_ref() {
            *self.suspect_total.entry(event.tenant.clone()).or_default() += 1;
        }
        suspect
    }
}

/// Credit one admitted request's prompt/cached token counts to its tenant row
/// (lane/cache-metering). The key is the tenant half of the PC-ISO namespace
/// (`auth::meter_key`); past METER_TENANT_CAP distinct rows, overflow aggregates
/// under "(other)" so the map is bounded while the totals stay exact.
fn meter_account(ns_tokens: &mut HashMap<String, [u64; 2]>, cache_ns: &str,
                 n_prompt: u64, n_cached: u64) {
    let mk = crate::auth::meter_key(cache_ns);
    let row = if ns_tokens.contains_key(mk) || ns_tokens.len() < METER_TENANT_CAP {
        ns_tokens.entry(mk.to_string()).or_default()
    } else {
        ns_tokens.entry("(other)".to_string()).or_default()
    };
    row[0] += n_prompt;
    row[1] += n_cached;
}

/// Add cached-token credit discovered after admission (in-batch prefix fanout).
/// Prompt tokens were already charged by `meter_account` when the request admitted.
fn meter_cached_credit(ns_tokens: &mut HashMap<String, [u64; 2]>, cache_ns: &str,
                       n_cached: u64) {
    meter_account(ns_tokens, cache_ns, 0, n_cached);
}

/// MEMRA_PREFIX_CACHE_MB (default 256): resident byte budget for the prefix cache. 0 = off.
fn prefix_cache_budget_bytes() -> usize {
    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *B.get_or_init(|| {
        let configured = std::env::var("MEMRA_PREFIX_CACHE_MB").ok()
            .and_then(|v| v.parse::<usize>().ok()).unwrap_or(256)
            .saturating_mul(1024 * 1024);
        if configured > 0 && memra_engine::pp::pp_host_bounce_active() {
            // Prefix snapshots/restores copy every stage-owned KV plane through the primary
            // Engine. That is a peer memcpy, not the explicit activation boundary `PpNRt`
            // bounces, so fail closed instead of caching corrupt bytes.
            0
        } else {
            configured
        }
    })
}

/// In-batch cold-prefix fanout. `=0` is the rollback/measurement seam.
fn prefix_dedup_enabled() -> bool {
    static D: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *D.get_or_init(|| std::env::var("MEMRA_PREFIX_DEDUP").as_deref() != Ok("0"))
}

/// Batched scheduling on? (read once — mirrors the run-loop static; the prefix cache only
/// engages in batched mode, the default.)
fn serve_batching() -> bool {
    static B: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *B.get_or_init(|| std::env::var("MEMRA_SERVE_BATCH").map(|v| v != "0").unwrap_or(true))
}

/// Can this process admit a spec session under the current placement policy?
///
/// The admission gate uses this only for the SPEC_SHRINK_RESERVE transient floor
/// (lane/admit-oom). A sharded PP-2 process at the placement-aware default has LOW=0, so no
/// request can take spec and the plain path must not pay that reserve. `MEMRA_SPEC_GATE=0`
/// remains always-spec and therefore still pays it.
fn serve_spec_enabled() -> bool {
    if memra_engine::pp::pp_host_bounce_active() {
        // Stream-mode spec exposes primary-device token/position buffers to stage 0 by UVA.
        // The engine also refuses the direct path; keep the serving policy on plain PP here.
        return false;
    }
    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let armed = *S.get_or_init(|| {
        std::env::var("MEMRA_SERVE_SPEC")
            .map(|v| v != "0")
            .unwrap_or(true)
    });
    if !armed {
        return false;
    }
    match spec_k_pin() {
        Some(k) => k > 0,
        None => !spec_gate_on() || spec_gate_low() > 0,
    }
}

/// ---- CONCURRENCY-GATED SPEC (lane/spec-gate, task #89, 2026-08-07) ----
///
/// THE SINGLE-CARD MEASUREMENT (research/specplace-20260808, N=3 interleaved on the
/// current train with q9 NVFP4+MTP + the production drafter, K=3, greedy):
///
/// | c | spec ON agg | spec OFF agg | S/N  |
/// |---|-------------|--------------|------|
/// | 1 | 374.8       | 224.5        | 1.67x WIN  |
/// | 2 | 374.5       | 347.5        | 1.08x WIN  |
/// | 4 | 377.3       | 617.1        | 0.61x LOSS |
///
/// Spec stays approximately flat because phase (a) steps each spec session's whole burst in a
/// serial host loop and phase (c) excludes spec sessions from batched decode. Single-card
/// therefore keeps the measured LOW=2/HIGH=4 crossover.
///
/// PP-2 IS A DIFFERENT POLICY CELL. The fixed q9 path measured 112.5/112.3/112.1 spec ON
/// against 223.3/340.3/593.4 spec OFF at c=1/2/4 (research/pp2spec-crash-20260807).
/// Re-checking the newly batched step35 core on the current train measured
/// 35.9/36.2/36.7 against 85.7/101.6/121.7, N=3 with no run-range overlap
/// (research/specplace-20260808). Spec loses every PP-2 cell, including c=1, so the
/// placement-aware default is LOW=0/HIGH=1: never admit spec.
///
/// Defaults:
///
///   single card / non-PP-2: LOW=2, HIGH=4
///   sharded cross-device PP-2: LOW=0, HIGH=1 (spec admission OFF)
///
/// `MEMRA_SPEC_GATE_LOW` / `_HIGH` explicitly override the placement defaults.
/// `MEMRA_SPEC_GATE=0` is the rollback seam and restores always-spec on every placement.
fn spec_gate_on() -> bool {
    static G: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *G.get_or_init(|| std::env::var("MEMRA_SPEC_GATE").as_deref() != Ok("0"))
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SpecGateThresholds {
    low: usize,
    high: usize,
    raw_high: usize,
    pp2_default: bool,
    low_overridden: bool,
    high_overridden: bool,
    high_clamped: bool,
}

fn spec_gate_defaults(pp2: bool) -> (usize, usize) {
    if pp2 { (0, 1) } else { (2, 4) }
}

fn resolve_spec_gate_thresholds(
    pp2: bool,
    low_override: Option<usize>,
    high_override: Option<usize>,
) -> SpecGateThresholds {
    let (default_low, default_high) = spec_gate_defaults(pp2);
    let low = low_override.unwrap_or(default_low);
    let raw_high = high_override.unwrap_or(default_high);
    let high_clamped = raw_high <= low;
    let high = if high_clamped {
        low.saturating_add(1)
    } else {
        raw_high
    };
    SpecGateThresholds {
        low,
        high,
        raw_high,
        pp2_default: pp2,
        low_overridden: low_override.is_some(),
        high_overridden: high_override.is_some(),
        high_clamped,
    }
}

/// This lane measured the cross-device, stage-split PP-2 placement. Do not silently apply its
/// default to PP-N or to the same-device/door-rollback configurations, whose execution shape is
/// different and unmeasured here.
fn spec_gate_pp2_placement() -> bool {
    let exactly_two_stages = std::env::var("MEMRA_PP_STAGES")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .is_some_and(|n| n == 2);
    exactly_two_stages && memra_engine::pp::pp_sharded_cross_device()
}

fn spec_gate_thresholds() -> &'static SpecGateThresholds {
    static T: std::sync::OnceLock<SpecGateThresholds> = std::sync::OnceLock::new();
    T.get_or_init(|| {
        let low_override = std::env::var("MEMRA_SPEC_GATE_LOW")
            .ok()
            .and_then(|v| v.parse().ok());
        let high_override = std::env::var("MEMRA_SPEC_GATE_HIGH")
            .ok()
            .and_then(|v| v.parse().ok());
        let thresholds =
            resolve_spec_gate_thresholds(spec_gate_pp2_placement(), low_override, high_override);
        if thresholds.high_clamped {
            eprintln!(
                "[spec-gate] WARN: MEMRA_SPEC_GATE_HIGH={} <= LOW={} leaves no hysteresis \
                 band (mode thrash); clamped to {}",
                thresholds.raw_high, thresholds.low, thresholds.high
            );
        }
        thresholds
    })
}

const SPEC_K_LONG_PROMPT_MIN: usize = 1024;
const SPEC_K_LONG_CACHE_MIN: usize = 1024;
const SPEC_K_COLD_SHORT: usize = 3;
const SPEC_K_COLD_LONG: usize = 3;
const SPEC_K_CACHED_LONG: usize = 2;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SpecKReason {
    OperatorPin,
    Replay,
    Placement,
    Concurrency,
    CachedLong,
    ColdShort,
    ColdLong,
}

impl SpecKReason {
    fn as_str(self) -> &'static str {
        match self {
            Self::OperatorPin => "operator-pin",
            Self::Replay => "oom-replay",
            Self::Placement => "pp2-placement",
            Self::Concurrency => "concurrency",
            Self::CachedLong => "cached-long",
            Self::ColdShort => "cold-short",
            Self::ColdLong => "cold-long",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SpecKDecision {
    k: usize,
    reason: SpecKReason,
}

fn parse_spec_k_pin(raw: Option<&str>) -> Result<Option<usize>, String> {
    raw.map(|value| {
        value.parse::<usize>().map_err(|_| {
            format!("MEMRA_SPEC_K={value:?} is not a non-negative integer")
        })
    }).transpose()
}

/// An explicit K is an operator pin, including K=0 for plain serving. Invalid values keep
/// serving on the automatic policy but warn once instead of silently becoming a different K.
fn spec_k_pin() -> Option<usize> {
    static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
    *K.get_or_init(|| {
        match parse_spec_k_pin(std::env::var("MEMRA_SPEC_K").ok().as_deref()) {
            Ok(k) => k,
            Err(err) => {
                eprintln!("[spec-k] WARN: {err}; using automatic policy");
                None
            }
        }
    })
}

fn choose_spec_k(
    pin: Option<usize>,
    gate_on: bool,
    thresholds: SpecGateThresholds,
    projected_active: usize,
    prompt_tokens: usize,
    cached_tokens: usize,
) -> SpecKDecision {
    if let Some(k) = pin {
        return SpecKDecision { k, reason: SpecKReason::OperatorPin };
    }
    if gate_on && projected_active > thresholds.low {
        let reason = if thresholds.pp2_default
            && !thresholds.low_overridden
            && thresholds.low == 0
        {
            SpecKReason::Placement
        } else {
            SpecKReason::Concurrency
        };
        return SpecKDecision { k: 0, reason };
    }
    if prompt_tokens >= SPEC_K_LONG_PROMPT_MIN
        && cached_tokens >= SPEC_K_LONG_CACHE_MIN
    {
        return SpecKDecision { k: SPEC_K_CACHED_LONG, reason: SpecKReason::CachedLong };
    }
    if prompt_tokens < SPEC_K_LONG_PROMPT_MIN {
        SpecKDecision { k: SPEC_K_COLD_SHORT, reason: SpecKReason::ColdShort }
    } else {
        SpecKDecision { k: SPEC_K_COLD_LONG, reason: SpecKReason::ColdLong }
    }
}

fn log_spec_gate_policy() {
    if let Some(k) = spec_k_pin() {
        eprintln!(
            "[spec-k] operator pin K={k}: automatic placement/concurrency/prompt policy \
             and automatic demotion disabled"
        );
        return;
    }
    if !spec_gate_on() {
        eprintln!("[spec-gate] policy disabled by MEMRA_SPEC_GATE=0: always-spec");
    } else {
        let thresholds = spec_gate_thresholds();
        let placement = if thresholds.pp2_default {
            "pp2-cross-device"
        } else {
            "single-or-non-pp2"
        };
        let source = if thresholds.low_overridden || thresholds.high_overridden {
            "env-resolved"
        } else {
            "placement-default"
        };
        let admission = if thresholds.low == 0 { "off" } else { "on" };
        eprintln!(
            "[spec-gate] policy placement={placement} LOW={} HIGH={} source={source} \
             spec-admission={admission}",
            thresholds.low, thresholds.high
        );
    }
    eprintln!(
        "[spec-k] automatic table: prompt<{} -> K={}; cold-long -> K={}; \
         prompt>= {} and cached>= {} -> K={}",
        SPEC_K_LONG_PROMPT_MIN, SPEC_K_COLD_SHORT, SPEC_K_COLD_LONG,
        SPEC_K_LONG_PROMPT_MIN, SPEC_K_LONG_CACHE_MIN, SPEC_K_CACHED_LONG
    );
}

fn spec_gate_low() -> usize {
    spec_gate_thresholds().low
}

fn spec_gate_high() -> usize {
    spec_gate_thresholds().high
}

/// What the load path must SAY (and whether it must refuse) about one model's drafter
/// attachment. Pure data so the decision is unit-testable without a GPU or a 105 GB artifact —
/// the whole point of this seam is that the silent-degradation class it removes was invisible
/// to every gate in the repo (see `research/step-draft-20260807/`).
#[derive(Debug, PartialEq, Eq)]
pub enum DraftVerdict {
    /// A drafter is attached (embedded NextN head or an external `+draft` file). Spec is live
    /// as far as the load path is concerned; `spec_eligible` still arbitrates per request.
    Attached,
    /// No drafter and none was asked for, on an arch whose published artifact ships its MTP
    /// head as a SEPARATE file. Serving works — it just silently forgoes spec, which is the
    /// exact defect this lane exists to make audible. WARN, do not refuse.
    NoDrafterExternalMtpArch,
    /// No drafter, on an arch whose head (if any) rides in the trunk file. Nothing to say
    /// beyond the existing load line: an artifact with `nextn=0` here genuinely has no head.
    NoDrafterQuiet,
}

/// The drafter-attachment verdict for one loaded model — pure over the four inputs that
/// decide it, so the refusal and the warning are both pinned by GPU-free tests.
///
/// `external_mtp_arch` = "this arch's published artifact ships its MTP head in a separate
/// GGUF, so `nextn=0` on the trunk does NOT mean the model has no drafter available." Today
/// that is step35 (Step-3.7-Flash: trunk declares `nextn_predict_layers=0`, the three chained
/// NextN blocks ship in `Step3.7-flash-mtp-Q8_0.gguf`). It is a property of the ARCH, not of
/// the file in hand, which is why it cannot be read off the trunk config.
pub fn draft_verdict(
    has_drafter: bool,
    external_mtp_arch: bool,
) -> DraftVerdict {
    // (#87 CLOSED, lane/pp2spec-crash 2026-08-08: this fn used to refuse spec + drafter over
    // a sharded cross-device PP placement — the sticky CUDA_ERROR_ILLEGAL_ADDRESS regime.
    // Root cause was the ppN reverse-publication hole: stage-stream pool blocks freed while
    // the primary stream held queued reads, reused by the next burst's stage allocations.
    // Fixed by `PpNRt::fence_stages_behind` at all three ppN bodies + stage-cache admission;
    // crash gate 212/212 at c=2..8 on the placement that lost 48/48, run-spec K=1..8 PASS
    // with acceptance identical to door-shut. research/pp2spec-crash-20260807/.)
    if has_drafter {
        return DraftVerdict::Attached;
    }
    if external_mtp_arch {
        DraftVerdict::NoDrafterExternalMtpArch
    } else {
        DraftVerdict::NoDrafterQuiet
    }
}

/// The one-line operator message for a verdict, or `None` when there is nothing to say.
/// Separated from `draft_verdict` so the TEXT is testable too — a warning nobody can act on
/// is the same defect as no warning (the attach spelling has to be IN the line).
pub fn draft_verdict_message(v: &DraftVerdict, name: &str, path: &str) -> Option<String> {
    match v {
        DraftVerdict::Attached | DraftVerdict::NoDrafterQuiet => None,
        DraftVerdict::NoDrafterExternalMtpArch => Some(format!(
            "[worker] WARN: {name}: step35: no MTP drafter attached — serving plain decode, \
             no speculative decoding. This arch ships its MTP/NextN head in a SEPARATE GGUF, \
             so the trunk's nextn_predict_layers=0 is expected and does NOT mean the model \
             has no drafter. Attach with MEMRA_MODELS=\"{name}={path}+/path/to/\
             Step3.7-flash-mtp-Q8_0.gguf\" (the same '+draft' convention every regime drafter \
             uses; docs/DRAFT-REGIME.md)."
        )),
    }
}

/// Admission transient-reserve override in BYTES (lane/admit-oom, 2026-08-06). This exists for
/// exactly one reason: the c=64 stress gate's TEETH arm. A gate that can only be observed
/// passing proves nothing, so `tools/serve-stress-gate.sh --teeth` forces the reserve tiny
/// (MEMRA_ADMIT_RESERVE_MB=16) and asserts the RED comes back — if the deliberately-broken
/// setting still passes, the gate is not measuring what it claims to measure. It is a
/// diagnostics/teeth door under the flags doctrine, never a tuning knob: the winning value is
/// the default and needs no flag.
fn admit_reserve_override() -> Option<usize> {
    static O: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
    *O.get_or_init(|| {
        std::env::var("MEMRA_ADMIT_RESERVE_MB").ok()
            .and_then(|v| v.parse::<usize>().ok())
            .map(|mb| {
                eprintln!("[admit-oom] WARN: MEMRA_ADMIT_RESERVE_MB={mb} overrides the \
                           {}MB transient reserve (teeth/diagnostics door — NOT a tuning knob)",
                          SPEC_SHRINK_RESERVE / (1 << 20));
                mb * (1 << 20)
            })
    })
}

/// Admission headroom charged ON TOP of the request's own cost (lane/kv256-capacity,
/// 2026-08-09). Spec-capable paths pay the full measured transient floor
/// (SPEC_SHRINK_RESERVE — capture arenas + verify activations, the admit-oom control fit).
/// Plain paths pay `min(cost, floor)`: the plain transient class (prime chunk slabs, batched
/// step scratch) is CHUNK-bounded, not ctx-scaled, so a 262,144-token request must not
/// reserve a whole second 21,894 MB session for it. For any cost at or below the floor this
/// is byte-identical to the previous `reserve = cost` contract (the c<=64 small-model regime
/// the admit-oom gate was calibrated on); it only unbinds where the old rule over-reserved.
/// The teeth/diagnostics override door applies to both branches — a forced-tiny reserve must
/// invert the verdict on whichever path the gate is exercising.
fn admission_reserve(spec_capable: bool, cost: usize, override_bytes: Option<usize>) -> usize {
    let floor = override_bytes.unwrap_or(SPEC_SHRINK_RESERVE);
    if spec_capable { floor } else { cost.min(floor) }
}

/// STEP-OOM PARK budget (lane/admit-oom, 2026-08-06): how many times a session may be parked
/// back to the queue after a step-time CUDA OOM before the failure is reported honestly.
/// A transient collision (a peer's capture arena landing in the same tick) clears as soon as
/// ONE session retires, so a small budget covers the real case; an unbounded retry would turn
/// a genuine capacity failure into a silent hang, which is strictly worse than the error it
/// replaces. MEMRA_STEP_OOM_RETRIES overrides (0 = restore the pre-fix kill-on-OOM behavior —
/// the rollback seam).
const STEP_OOM_MAX_RETRIES: u32 = 3;

fn step_oom_retries() -> u32 {
    static R: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
    *R.get_or_init(|| {
        std::env::var("MEMRA_STEP_OOM_RETRIES").ok().and_then(|v| v.parse().ok())
            .unwrap_or(STEP_OOM_MAX_RETRIES)
    })
}

/// Is this error a CUDA out-of-memory? Quoted, never inferred (the evidence-discipline law):
/// the match is on the driver's own error text, so a non-OOM step failure can never be
/// silently retried as if it were a capacity blip.
fn is_cuda_oom(err: &str) -> bool {
    err.contains("CUDA_ERROR_OUT_OF_MEMORY") || err.contains("out of memory")
}

/// Run one allocation retry only when the first failure released reclaimable state. The caller
/// owns the reclaim policy; keeping the retry here makes the one-retry bound unit-testable.
fn alloc_with_single_reclaim_retry<T, E>(
    mut alloc: impl FnMut() -> Result<T, E>,
    mut reclaim: impl FnMut(&E) -> bool,
) -> Result<T, E> {
    match alloc() {
        Ok(value) => Ok(value),
        Err(first_err) if reclaim(&first_err) => alloc(),
        Err(err) => Err(err),
    }
}

/// One full-attn layer's cached prefix bytes: exactly `len` tokens of quantized K/V.
struct PrefixPlane {
    k: CudaSlice<u8>,
    v: CudaSlice<u8>,
    len: usize,
}

/// A cached token-prefix: per-layer KV byte copies + recurrent conv/ssm copies + the logits
/// row AT the boundary (empty-suffix resumes sample from it, same as the continuation pool).
struct PrefixEntry {
    toks: Vec<u32>,
    kv: Vec<Option<PrefixPlane>>,
    conv: Vec<Option<CudaSlice<f32>>>,
    ssm: Vec<Option<CudaSlice<f32>>>,
    pos: usize,
    last_logits: Vec<f32>,
    bytes: usize,
    last_use: Instant,
    /// Recency-index identity (Q3, audit 2026-08-05): unique per insert (monotonic counter,
    /// assigned by `insert`), disambiguating equal `last_use` Instants in the LRU BTreeMap key.
    id: u64,
    /// In-flight fanout/cache-hit leases. A pinned entry is absent from the evictable LRU
    /// index until the last participating session retires.
    pins: usize,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct PrefixPin {
    key: PoolKey,
    id: u64,
}

#[derive(Default)]
struct PrefixCache {
    /// per-(model, namespace) entry pools (KV geometry/format is per model; the namespace
    /// is the PC-ISO trust boundary — the equality check is part of the map key, so the
    /// default path pays nothing beyond hashing "" alongside the model id).
    entries: HashMap<PoolKey, Vec<PrefixEntry>>,
    /// EVICTION INDEX (Q3, audit 2026-08-05 — the vLLM #50992 rescan-from-head shape):
    /// recency-ordered view of every entry, so victim selection is `first_key_value()`
    /// O(log E) instead of the old per-victim full rescan (O(E) per victim, O(k·E) per
    /// insert, O(E²) on a flush — unbounded via MEMRA_PREFIX_CACHE_MB). POLICY UNCHANGED:
    /// the old scan chose the global strict-< `last_use` minimum, i.e. timestamp-LRU —
    /// the BTreeMap's first key is that same minimum. Ties on equal Instants: the old
    /// scan broke them by HashMap-iteration order (nondeterministic across pools,
    /// insertion order within one pool); the `id` component breaks them by insertion
    /// order globally — a strict determinization, never a different policy.
    /// PINNING (lane/cx-prefix-dedup): pinned entries are deliberately ABSENT from this
    /// map. The last lease release returns the entry at current recency. Value = (pool
    /// key, index into that pool's Vec), kept exact on removal by swap_remove +
    /// moved-entry index fixup. Every `last_use` write goes through touch/pin/unpin/insert
    /// so index and entries never drift.
    lru: std::collections::BTreeMap<(Instant, u64), (PoolKey, usize)>,
    next_id: u64,
    total_bytes: usize,
    hits: u64,
    misses: u64,
    inserts: u64,
    evictions: u64,
    hit_tokens: u64,
    /// LCP histogram (lane/cache-metering): one sample per probe — the served entry's
    /// token length on a hit, `best_lcp` on a miss (both already computed; no new scan).
    /// Lower-edge buckets `LCP_HIST_EDGES` (see `lcp_bucket`).
    lcp_hist: [u64; 11],
}

/// Lower edges of the LCP histogram buckets: bucket i counts samples in
/// [EDGES[i], EDGES[i+1]), the last bucket [4096, inf). [64,512) — the tick-seg
/// segmentation window — is exactly buckets 4+5+6.
pub const LCP_HIST_EDGES: [usize; 11] = [0, 1, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];

#[derive(Debug, PartialEq, Eq)]
struct PrefixFanoutCandidate {
    active_idx: usize,
    key: PoolKey,
    prompt: Vec<u32>,
}

#[derive(Debug, PartialEq, Eq)]
struct PrefixFanoutGroup {
    members: Vec<usize>,
    prefix_len: usize,
}

/// Partition one admission window by the PC-ISO key and exact token prefix. Hashes are
/// deliberately absent from membership: equality of `(model, cache_ns)` is checked before
/// any token comparison, then the first 64 token ids and the full group LCP are exact.
fn prefix_fanout_groups(
    candidates: &[PrefixFanoutCandidate],
    prefix_cap: usize,
) -> Vec<PrefixFanoutGroup> {
    if prefix_cap < PREFIX_CACHE_MIN_TOKENS {
        return Vec::new();
    }
    let mut used = vec![false; candidates.len()];
    let mut out = Vec::new();
    for i in 0..candidates.len() {
        if used[i] || candidates[i].prompt.len() < PREFIX_CACHE_MIN_TOKENS {
            continue;
        }
        let mut group = vec![i];
        for j in i + 1..candidates.len() {
            if used[j]
                || candidates[j].key != candidates[i].key
                || candidates[j].prompt.len() < PREFIX_CACHE_MIN_TOKENS
                || candidates[j].prompt[..PREFIX_CACHE_MIN_TOKENS]
                    != candidates[i].prompt[..PREFIX_CACHE_MIN_TOKENS]
            {
                continue;
            }
            group.push(j);
        }
        if group.len() < 2 {
            continue;
        }
        let mut lcp = group.iter()
            .map(|&j| candidates[j].prompt.len())
            .min()
            .unwrap_or(0);
        for &j in group.iter().skip(1) {
            lcp = PrefixCache::lcp(
                &candidates[i].prompt[..lcp],
                &candidates[j].prompt[..lcp],
            );
        }
        let prefix_len = lcp.min(prefix_cap);
        if prefix_len < PREFIX_CACHE_MIN_TOKENS {
            continue;
        }
        for &j in &group {
            used[j] = true;
        }
        out.push(PrefixFanoutGroup {
            members: group.iter().map(|&j| candidates[j].active_idx).collect(),
            prefix_len,
        });
    }
    out
}

impl PrefixCache {
    fn lcp(a: &[u32], b: &[u32]) -> usize {
        a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count()
    }

    /// Histogram bucket index for an LCP sample (see `LCP_HIST_EDGES`).
    fn lcp_bucket(n: usize) -> usize {
        LCP_HIST_EDGES.iter().rposition(|&e| n >= e).unwrap_or(0)
    }

    /// Record one probe outcome into the LCP histogram (hit: entry length; miss: best_lcp).
    fn record_lcp(&mut self, n: usize) {
        self.lcp_hist[Self::lcp_bucket(n)] += 1;
    }

    /// Admission observed a miss before a same-window sibling produced the shared prefix.
    /// Rewrite that provisional probe into the final served-path hit so cache-meter receipts
    /// count requests, tokens, and LCP depth exactly once.
    fn promote_miss_to_hit(&mut self, miss_lcp: usize, hit_len: usize) {
        // 2.5 (code-audit-20260809): a telemetry bookkeeping slip must NEVER panic the worker
        // and take every concurrent stream with it. These were release `checked_sub().expect()`;
        // this lane adds new admission routes that set the same counters, so demote them to a
        // saturating decrement + a one-line receipt. Under-counting a metric is honest; a crash
        // is not.
        self.misses = self.misses.checked_sub(1).unwrap_or_else(|| {
            eprintln!("[prefix-cache] WARN: fanout promoted a miss that was never recorded \
                       (misses underflow) — metric slip, not fatal");
            0
        });
        let bucket = Self::lcp_bucket(miss_lcp);
        self.lcp_hist[bucket] = self.lcp_hist[bucket].saturating_sub(1);
        self.hits += 1;
        self.hit_tokens += hit_len as u64;
        self.record_lcp(hit_len);
    }

    fn n_entries(&self) -> usize {
        self.entries.values().map(|p| p.len()).sum()
    }

    /// Longest entry whose token key exactly prefixes `prompt` (floor PREFIX_CACHE_MIN_TOKENS).
    /// Only the caller's own (model, namespace) pool is scanned — cross-namespace entries
    /// are structurally unreachable (PC-ISO).
    fn lookup(&self, key: &PoolKey, prompt: &[u32]) -> Option<usize> {
        let pool = self.entries.get(key)?;
        let mut best: Option<(usize, usize)> = None;
        for (i, e) in pool.iter().enumerate() {
            let n = e.toks.len();
            if n >= PREFIX_CACHE_MIN_TOKENS && n <= prompt.len() && prompt[..n] == e.toks[..]
                && best.is_none_or(|(_, bn)| n > bn)
            {
                best = Some((i, n));
            }
        }
        best.map(|(i, _)| i)
    }

    /// Longest common prefix of `prompt` with ANY entry (the LCP-split learning signal).
    fn best_lcp(&self, key: &PoolKey, prompt: &[u32]) -> usize {
        self.entries.get(key)
            .map(|pool| pool.iter().map(|e| Self::lcp(&e.toks, prompt)).max().unwrap_or(0))
            .unwrap_or(0)
    }

    /// Is any entry (>= min tokens) already a full prefix of `prompt`? (seed dedupe)
    fn has_covering(&self, key: &PoolKey, prompt: &[u32]) -> bool {
        self.entries.get(key).is_some_and(|pool| pool.iter().any(|e| {
            let n = e.toks.len();
            n >= PREFIX_CACHE_MIN_TOKENS && n <= prompt.len() && prompt[..n] == e.toks[..]
        }))
    }

    fn has_key(&self, key: &PoolKey, toks: &[u32]) -> bool {
        self.entries.get(key).is_some_and(|pool| pool.iter().any(|e| e.toks[..] == *toks))
    }

    fn key_index(&self, key: &PoolKey, toks: &[u32]) -> Option<usize> {
        self.entries.get(key)?.iter().position(|e| e.toks[..] == *toks)
    }

    fn id_index(&self, pin: &PrefixPin) -> Option<usize> {
        self.entries.get(&pin.key)?.iter().position(|e| e.id == pin.id)
    }

    fn lru_key(e: &PrefixEntry) -> (Instant, u64) {
        (e.last_use, e.id)
    }

    /// Refresh recency for pool[i] (a lookup hit) — the ONLY legal `last_use` write after
    /// insert, so the recency index never drifts from the entries.
    #[cfg_attr(not(test), allow(dead_code))]
    fn touch(&mut self, key: &PoolKey, i: usize) {
        let Some((old_lru, pinned)) = self.entries.get(key).and_then(|p| p.get(i))
            .map(|e| (Self::lru_key(e), e.pins > 0)) else { return };
        if !pinned {
            self.lru.remove(&old_lru);
        }
        let e = &mut self.entries.get_mut(key).unwrap()[i];
        e.last_use = Instant::now();
        if e.pins == 0 {
            self.lru.insert(Self::lru_key(e), (key.clone(), i));
        }
    }

    /// Acquire `n` in-flight leases on one entry. The first lease removes it from the
    /// evictable LRU; all leases share the stable (pool key, entry id) handle.
    fn pin_n(&mut self, key: &PoolKey, i: usize, n: usize) -> Option<PrefixPin> {
        if n == 0 {
            return None;
        }
        let (old_lru, id, was_unpinned) = {
            let e = self.entries.get(key)?.get(i)?;
            (Self::lru_key(e), e.id, e.pins == 0)
        };
        if was_unpinned {
            self.lru.remove(&old_lru);
        }
        let e = &mut self.entries.get_mut(key)?[i];
        e.pins = e.pins.checked_add(n).expect("prefix pin refcount overflow");
        e.last_use = Instant::now();
        Some(PrefixPin { key: key.clone(), id })
    }

    fn pin(&mut self, key: &PoolKey, i: usize) -> Option<PrefixPin> {
        self.pin_n(key, i, 1)
    }

    /// Release one session lease. The last release makes the entry evictable again and
    /// treats the protected fanout interval as recent use.
    fn unpin(&mut self, pin: &PrefixPin) -> bool {
        let Some(i) = self.id_index(pin) else { return false };
        let e = &mut self.entries.get_mut(&pin.key).unwrap()[i];
        if e.pins == 0 {
            return false;
        }
        e.pins -= 1;
        if e.pins == 0 {
            e.last_use = Instant::now();
            self.lru.insert(Self::lru_key(e), (pin.key.clone(), i));
        }
        true
    }

    fn pinned_bytes(&self) -> usize {
        self.entries.values().flatten().filter(|e| e.pins > 0).map(|e| e.bytes).sum()
    }

    /// Remove pool[i] under `key`, keeping the recency index exact: swap_remove moves the
    /// pool's LAST entry into slot i, so exactly one surviving entry needs its index
    /// re-pointed (pool order is free — every probe is order-independent: lookup's
    /// longest-match tie is impossible under exact-key dedupe, best_lcp is a max,
    /// has_covering/has_key are `any`).
    fn remove_at(&mut self, key: &PoolKey, i: usize) -> Option<PrefixEntry> {
        let pool = self.entries.get_mut(key)?;
        if i >= pool.len() || pool[i].pins > 0 {
            return None;
        }
        let dead = pool.swap_remove(i);
        self.lru.remove(&Self::lru_key(&dead));
        if let Some(moved) = pool.get(i) {
            if moved.pins == 0 {
                self.lru.insert(Self::lru_key(moved), (key.clone(), i));
            }
        }
        if pool.is_empty() {
            self.entries.remove(key);
        }
        Some(dead)
    }

    /// Insert (exact-key deduped per namespace) + LRU-evict back under MEMRA_PREFIX_CACHE_MB.
    /// The LRU budget stays GLOBAL across namespaces (VRAM is one resource); only visibility
    /// is namespaced.
    ///
    /// EVICTION (Q3, audit 2026-08-05): victims pop off the recency index — O(log E)
    /// amortized per victim. The OLD loop re-scanned every entry in every pool per victim
    /// (O(E) per victim, O(E²) flushing a pool of small entries — the vLLM #50992 shape).
    /// POLICY IDENTICAL: both pick the global minimum `last_use` (timestamp-LRU); see the
    /// `lru` field doc for the tie determinization.
    fn insert(&mut self, key: &PoolKey, e: PrefixEntry, why: &str) {
        self.insert_with_budget(key, e, why, prefix_cache_budget_bytes());
    }

    /// Insert a prefix already serving `pins` in-flight sessions. Returns one stable
    /// handle which each participating Session clones and releases once.
    fn insert_pinned(
        &mut self,
        key: &PoolKey,
        e: PrefixEntry,
        why: &str,
        pins: usize,
    ) -> Option<PrefixPin> {
        let id = self.insert_with_budget_pins(
            key, e, why, prefix_cache_budget_bytes(), pins)?;
        Some(PrefixPin { key: key.clone(), id })
    }

    /// `insert` with the budget as a parameter (the env-independent seam the eviction
    /// unit tests drive; production always passes `prefix_cache_budget_bytes()`).
    fn insert_with_budget(&mut self, key: &PoolKey, e: PrefixEntry, why: &str, budget: usize) {
        let _ = self.insert_with_budget_pins(key, e, why, budget, 0);
    }

    fn insert_with_budget_pins(
        &mut self,
        key: &PoolKey,
        mut e: PrefixEntry,
        why: &str,
        budget: usize,
        initial_pins: usize,
    ) -> Option<u64> {
        if let Some(i) = self.key_index(key, &e.toks) {
            return if initial_pins > 0 {
                self.pin_n(key, i, initial_pins).map(|pin| pin.id)
            } else {
                None
            };
        }
        if e.bytes > budget {
            eprintln!("[prefix-cache] skip {why} insert: entry {:.1}MB > budget {:.0}MB",
                      e.bytes as f64 / 1e6, budget as f64 / 1e6);
            return None;
        }
        if initial_pins > 0 && e.bytes > budget.saturating_sub(self.pinned_bytes()) {
            eprintln!("[prefix-cache] skip pinned {why} insert: entry {:.1}MB cannot fit \
                       beside {:.1}MB already pinned (budget {:.0}MB)",
                      e.bytes as f64 / 1e6, self.pinned_bytes() as f64 / 1e6,
                      budget as f64 / 1e6);
            return None;
        }
        self.total_bytes += e.bytes;
        self.inserts += 1;
        eprintln!("[prefix-cache] insert ({why}): {} tokens, {:.1}MB (resident {:.1}MB / {:.0}MB, model {}{})",
                  e.toks.len(), e.bytes as f64 / 1e6,
                  self.total_bytes as f64 / 1e6, budget as f64 / 1e6,
                  key.0, ns_suffix(&key.1));
        e.id = self.next_id;
        self.next_id += 1;
        e.pins = initial_pins;
        let inserted_id = e.id;
        let lk = Self::lru_key(&e);
        let idx = {
            let pool = self.entries.entry(key.clone()).or_default();
            pool.push(e);
            pool.len() - 1
        };
        if initial_pins == 0 {
            self.lru.insert(lk, (key.clone(), idx));
        }
        while self.total_bytes > budget {
            let Some((k, i)) = self.lru.values().next().cloned() else { break };
            let Some(dead) = self.remove_at(&k, i) else { break };
            self.total_bytes = self.total_bytes.saturating_sub(dead.bytes);
            self.evictions += 1;
            eprintln!("[prefix-cache] evict (LRU): {} tokens, {:.1}MB (model {}{})",
                      dead.toks.len(), dead.bytes as f64 / 1e6, k.0, ns_suffix(&k.1));
        }
        self.entries.get(key)
            .and_then(|pool| pool.iter().find(|entry| entry.id == inserted_id))
            .map(|_| inserted_id)
    }

    /// Drop every EVICTABLE entry (session cache alloc failed — sessions win over
    /// ordinary cache residency, while in-flight fanout leases remain authoritative).
    fn evict_all(&mut self) -> usize {
        let mut n = 0usize;
        while let Some((key, i)) = self.lru.values().next().cloned() {
            let Some(dead) = self.remove_at(&key, i) else { break };
            self.total_bytes = self.total_bytes.saturating_sub(dead.bytes);
            n += 1;
        }
        self.evictions += n as u64;
        n
    }
}

fn retire_prefix_pin(px: &mut PrefixCache, prefix_pin: &mut Option<PrefixPin>) {
    if let Some(pin) = prefix_pin.take() {
        if !px.unpin(&pin) {
            eprintln!("[prefix-cache] warning: retired session held a missing prefix pin");
        }
    }
}

/// Deep-copy the primed prefix state OUT of a live session cache into a compact entry.
/// All copies are stream-ordered on the engine worker stream (the CUDA owner thread), so no
/// sync is needed against the prime that produced the bytes or the decode that follows.
fn prefix_snapshot(
    engine: &Engine,
    cache: &Cache,
    toks: &[u32],
    last_logits: &[f32],
) -> Result<PrefixEntry, Box<dyn std::error::Error>> {
    if cache.has_swa_ring() {
        return Err("SWA ring sessions do not support flat-history prefix snapshots".into());
    }
    let n = cache.kv.len();
    let mut kv = Vec::with_capacity(n);
    let mut conv = Vec::with_capacity(n);
    let mut ssm = Vec::with_capacity(n);
    let mut bytes = 0usize;
    for il in 0..n {
        match &cache.kv[il] {
            Some(l) => {
                let kb = l.len * l.k_tok_bytes;
                let vb = l.len * l.v_tok_bytes;
                let mut k = engine.alloc_u8(kb.max(1))?;
                let mut v = engine.alloc_u8(vb.max(1))?;
                if kb > 0 { engine.copy_u8_into(&mut k, 0, &l.k, kb)?; }
                if vb > 0 { engine.copy_u8_into(&mut v, 0, &l.v, vb)?; }
                bytes += kb + vb;
                kv.push(Some(PrefixPlane { k, v, len: l.len }));
            }
            None => kv.push(None),
        }
        match &cache.recur[il] {
            Some(r) => {
                conv.push(Some(engine.clone_dtod(&r.conv_state)?));
                ssm.push(Some(engine.clone_dtod(&r.ssm_state)?));
                bytes += (r.conv_state.len() + r.ssm_state.len()) * 4;
            }
            None => {
                conv.push(None);
                ssm.push(None);
            }
        }
    }
    Ok(PrefixEntry {
        toks: toks.to_vec(),
        kv,
        conv,
        ssm,
        pos: cache.pos,
        last_logits: last_logits.to_vec(),
        bytes,
        last_use: Instant::now(),
        id: 0, // recency identity assigned by PrefixCache::insert
        pins: 0,
    })
}

/// Deep-copy an entry INTO a freshly allocated session cache: KV bytes at [0..len), per-layer
/// len + device len mirror, recurrent conv/ssm state, pos. The ssm ping-pong spare and
/// last_logits_dev stay as allocated (scratch — overwritten before any read).
fn prefix_restore(
    engine: &Engine,
    cache: &mut Cache,
    e: &PrefixEntry,
) -> Result<(), Box<dyn std::error::Error>> {
    if cache.has_swa_ring() {
        return Err("SWA ring sessions do not support flat-history prefix restores".into());
    }
    if cache.kv.len() != e.kv.len() {
        return Err(format!("prefix entry layer count {} != cache {}", e.kv.len(), cache.kv.len()).into());
    }
    // H6 (code-audit-20260809 §2.6): copy_u8_into -> slice_mut PANICS on an out-of-range range,
    // so an entry with more rows than the destination cache holds would take the worker down
    // instead of returning the `Err` the `?` suggests. Unreachable today (lookup bounds the entry
    // to <= the destination ctx), but this lane is a right-sizing change and one wrong sizing
    // decision here must be a clean error, not a crash. Precondition it once, up front.
    let cache_cap = cache.max_ctx;
    for il in 0..cache.kv.len() {
        match (cache.kv[il].as_mut(), &e.kv[il]) {
            (Some(dst), Some(src)) => {
                if src.len > cache_cap {
                    return Err(format!(
                        "prefix entry layer {il} len {} exceeds cache capacity {cache_cap}",
                        src.len).into());
                }
                let kb = src.len * dst.k_tok_bytes;
                let vb = src.len * dst.v_tok_bytes;
                if kb > 0 { engine.copy_u8_into(&mut dst.k, 0, &src.k, kb)?; }
                if vb > 0 { engine.copy_u8_into(&mut dst.v, 0, &src.v, vb)?; }
                dst.len = src.len;
                engine.set_i32_one(&mut dst.len_d, src.len as i32)?;
            }
            (None, None) => {}
            _ => return Err(format!("prefix entry layer {il} kind mismatch").into()),
        }
        match (cache.recur[il].as_mut(), &e.conv[il], &e.ssm[il]) {
            (Some(dst), Some(c), Some(s)) => {
                engine.copy_into(&mut dst.conv_state, 0, c, c.len())?;
                engine.copy_into(&mut dst.ssm_state, 0, s, s.len())?;
            }
            (None, None, None) => {}
            _ => return Err(format!("prefix entry recur {il} mismatch").into()),
        }
    }
    cache.pos = e.pos;
    Ok(())
}

/// Snapshot + insert the session's CURRENT primed state (fed tokens, boundary logits).
/// No-op when the session cannot serve an empty-suffix resume (no host logits yet).
fn prefix_insert_from_session(engine: &Engine, px: &mut PrefixCache, s: &Session, why: &str) {
    let Some(cache) = s.cache.as_ref() else { return };
    if s.last_logits.is_empty() {
        return;
    }
    match prefix_snapshot(engine, cache, &s.fed, &s.last_logits) {
        Ok(e) => px.insert(&s.pool_key(), e, why),
        Err(err) => eprintln!("[prefix-cache] snapshot failed ({err}); prefix not cached"),
    }
}

/// PLAIN-SESSION AFFINITY capture (lane/plain-affinity, 2026-08-09): snapshot the session's
/// cache at the stable pre-generation boundary `s.ckpt_at`, called by the prefill tick the
/// instant `s.fed.len()` reaches that boundary. Stores the result in `s.ckpt_snap` for the
/// retire sweep to move into the parked `ReuseEntry`.
///
/// Cost: ONE `Cache::snapshot` — a device COPY of only the GDN conv/ssm recurrent state (KB-MB
/// class; full-attn KV is recorded as `len` values, no copy). A pure full-attn model (step35,
/// M3, Hy3: no recurrent layers) copies nothing. This is the plain twin of the spec checkpoint's
/// single per-turn snapshot.
///
/// FAILURE IS SILENT BY DESIGN (matching the spec checkpoint): on a rig too tight for the copy
/// the capture is dropped, the session serves normally, and the NEXT turn re-primes in full —
/// today's behavior. It must never fail the prime that is running.
fn maybe_plain_checkpoint(engine: &Engine, s: &mut Session) {
    let Some(at) = s.ckpt_at else { return };
    if s.fed.len() != at {
        return;
    }
    s.ckpt_at = None; // one capture per session, at the boundary
    let Some(cache) = s.cache.as_ref() else { return };
    debug_assert_eq!(cache.pos, at, "plain checkpoint must sit at the fed boundary");
    match cache.snapshot(engine) {
        Ok(snap) => {
            s.ckpt_snap = Some(PlainCheckpoint {
                snap,
                pos: at,
                last_logits: s.last_logits.clone(),
            });
        }
        Err(err) => {
            if std::env::var("MEMRA_DEBUG_AFFINITY").is_ok() {
                eprintln!("[plain-affinity] checkpoint capture skipped ({err}); \
                           next turn re-primes in full");
            }
        }
    }
}

/// SEED insert at prefill-done: a cold session (nothing resumed) whose full prompt is long
/// enough and not already covered by an entry parks its primed prompt state for future
/// same-prefix traffic. `s.fed` == the prompt exactly at this point (no generation yet).
fn maybe_prefix_seed(engine: &Engine, px: &mut PrefixCache, s: &mut Session) {
    if !s.seed_prefix {
        return;
    }
    s.seed_prefix = false;
    if s.n_cached > 0 || s.cache.is_none() || s.fed.len() < PREFIX_CACHE_MIN_TOKENS {
        return;
    }
    if px.has_covering(&s.pool_key(), &s.fed) {
        return; // an entry already serves this prefix class
    }
    prefix_insert_from_session(engine, px, s, "seed");
}

/// STEP-OOM PARK replay plan (lane/admit-oom, 2026-08-06): the request-shaped inputs a
/// session needs to be re-admitted after a step-time CUDA OOM parks it. These are exactly the
/// `Request` fields `admit` consumes to render and tokenize the prompt — the Session itself
/// keeps only the tokenized result, so a faithful retry has to replay from the source.
/// Cloned once per admitted session (a Vec of turns + a few strings; no device state).
struct ReplayPlan {
    prompt_ids: Vec<u32>,
    prompt_text: String,
    chat: bool,
    chat_turns: Vec<memra_tokenizer::chat::Turn>,
    tools_json: Vec<String>,
    think: memra_tokenizer::chat::ThinkMode,
    reasoning_effort: Option<String>,
    params: GenParams,
    sampler_cfg: SamplerConfig,
    grammar: Option<crate::constrained::GrammarSpec>,
}

struct Session {
    model: String,
    /// Request-owned speculative depth. Zero means this session is on the plain path.
    /// Positive values are fixed for the request and consumed by every spec round.
    spec_k: usize,
    /// PC-ISO cache namespace this session admits, hits, and parks under (see PoolKey).
    cache_ns: String,
    /// SESSION AFFINITY explicit tier: the conversation id the admitting request declared
    /// (`Request::affinity`), carried so park-at-retire can label the parked session with it.
    affinity: Option<String>,
    /// yield lane — admission class + prefill budget bucket + batch priority.
    lane: crate::lanes::Lane,
    /// legacy tokenwise cache — None on the spec path (SpecSession owns its own caches; the
    /// double-alloc cost 2GB/128k-session and OOM'd the 27B serve — fixed 2026-07-05).
    cache: Option<Cache>,
    /// SPEC-DECODE serving (2026-07-05): sessions on MTP models decode in
    /// generate_spec_session BURSTS (K-token draft chains + batched verify) instead of one
    /// decode_step per tick — the CLI-measured spec win (27B p3: 79 vs 40 tok/s) brought to the
    /// serve path. `Some` when: model has an MTP head + MEMRA_SERVE_SPEC!=0 + the sampler is
    /// EITHER greedy (argmax verify) OR sampled (temperature>0 -> the rejection-sampling
    /// verify, filters and penalties applied symmetrically to draft q and target p; landed
    /// 2026-07-09/10, feat/sampled-graph-draft + feat/filtered-spec). Greedy-with-penalties
    /// is the one excluded class (`greedy_penalized`) — the argmax verify would ignore them.
    /// See `spec_eligible` in step_admit for the authoritative predicate.
    /// The SpecSession owns its OWN cache/scratch; `cache` above stays as the (unused) admit
    /// allocation on this path (kept to avoid restructuring admit; ~small VRAM overhead until
    /// a follow-up drops it). committed == every token whose state the spec caches hold.
    spec: Option<memra_engine::spec::SpecSession>,
    /// SINGLE-SESSION CUDA-GRAPH serving (2026-07-26, +34% measured at B=1): a greedy
    /// interactive session admitted ALONE rides GraphSession replay (one step/tick, 4B
    /// D2H). Degrades to the batched-eager path the moment a second session admits —
    /// legal because dc==eager is bit-identical, so the graph cache continues seamlessly.
    graph: Option<memra_engine::decode::GraphSession>,
    /// The token produced by the last graph step (next INPUT; emitted on the next tick).
    graph_pending: Option<u32>,
    /// STEP-OOM PARK (lane/admit-oom): how many times this session has been parked back to
    /// the queue after a step-time CUDA OOM. Bounded by STEP_OOM_MAX_RETRIES before the
    /// honest error — a session that cannot make progress must not retry forever.
    oom_retries: u32,
    /// STEP-OOM PARK replay plan (lane/admit-oom): everything needed to rebuild this
    /// session's `Request` if a step-time OOM parks it back to the admission queue. Held
    /// because `admit` consumes the Request and the Session keeps only derived state (the
    /// TOKENIZED prompt, not the turns/tools/think that rendered it). Re-admitting from
    /// these fields re-runs the identical render+tokenize, so the retried session is the
    /// one a cold arrival would have produced.
    replay: Box<ReplayPlan>,
    /// Live acceptance telemetry (hqmtp axis-D): cumulative drafted/accepted across the
    /// session's bursts, logged per burst so serve-regime acceptance-vs-context is measurable.
    /// THIS REQUEST's counts (0 at admit even on a pool resume) — the `usage.spec` source.
    spec_drafted: usize,
    spec_accepted: usize,
    /// verify rounds this request ran (lane/accept-telemetry; same per-request semantics).
    spec_rounds: u64,
    sampler: Sampler,
    last_logits: Vec<f32>,
    /// Token pre-sampled ON DEVICE by the last batched tick (decode_step_batch_sampled) —
    /// consumed by the next advance_sample_emit instead of the O(n_vocab) host sample
    /// (measured 1.36 ms/row at 248k vocab). None = host-sample from last_logits (fallback
    /// rows: penalties/top-k/top-p/min-p configs; non-batched paths). Dropped un-consumed
    /// when a session finishes — same semantics as an unsampled last_logits.
    device_next: Option<u32>,
    /// Constrained decoding (`response_format`): per-session llguidance grammar state.
    /// `Some` masks the logits BEFORE every sample and advances with each accepted token.
    /// FULL path (2026-08-03): the packed mask uploads to `mask_dev` each step and
    /// mask_logits_f32 bans on DEVICE before the device sampler — constrained rows ride
    /// the same device-sample/lean-logits tick as everyone else. Fallback sampler configs
    /// (penalties/top-k/top-p/min-p) and MEMRA_CONSTRAIN_HOST=1 keep the v1 host-side
    /// masked-copy sample.
    constraint: Option<crate::constrained::SessionConstraint>,
    /// Device grammar-mask buffer (packed SimpleVob words). Allocated once at first use,
    /// STABLE POINTER thereafter — contents re-uploaded per step (~n_vocab/8 bytes), the
    /// graph-capture contract for the in-graph mask read.
    mask_dev: Option<CudaSlice<u32>>,
    /// Words uploaded this step (0 = no mask staged for the pending batch step).
    mask_words: usize,
    /// Every token actually FED to decode_step, in order (prompt prime + generated feedback).
    /// This is exactly the sequence whose KV + recurrent state live in `cache` — the resume
    /// point for KV PREFIX REUSE on retire (see ReusePool).
    fed: Vec<u32>,
    /// prompt tokens still to be primed (consumed one per scheduler tick during prefill).
    prefill_queue: std::collections::VecDeque<u32>,
    prefill_done: bool,
    generated: Vec<u32>,
    /// Successfully published `Event::Token` count. `finish` requires this to equal
    /// `generated.len()` before publishing the terminal usage/token snapshot receipt.
    tokens_emitted: usize,
    params: GenParams,
    stop_strings: Vec<String>,
    trace_id: Option<String>,
    /// detokenized text already emitted (to compute incremental deltas + stop-string matching).
    emitted_bytes: usize,
    budget: usize,        // max tokens we may still generate
    /// usage accounting (worker-truth): total prompt tokens this session feeds/resumes, and
    /// how many came from a cache (continuation pool / spec resume / prefix cache).
    n_prompt: usize,
    n_cached: usize,
    /// PREFIX-CACHE LCP SPLIT: prime exactly up to this fed-length, snapshot the cache into
    /// the prefix cache there, then continue with the rest of the prompt (the learning step).
    snapshot_at: Option<usize>,
    /// PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09): the STABLE PRE-GENERATION
    /// boundary this session captures a rewind checkpoint at, in `fed`-length. Derived at admit
    /// (`plain_checkpoint_boundary`) from the prompt's last turn-marker run so the checkpoint
    /// sits before the template's live assistant-generation suffix. `Some(b)` makes the prefill
    /// tick stop a prime exactly at `b` and snapshot the cache into `ckpt_snap`; it is a
    /// COLD-only signal (a resumed session already carries the earlier turn's checkpoint and does
    /// not re-capture). `None` = no capture (resume, too-short prompt, or an unlocatable boundary).
    ckpt_at: Option<usize>,
    /// The captured plain checkpoint, taken when prefill crosses `ckpt_at`. Moved into the parked
    /// `ReuseEntry` at retire. `None` until the boundary is crossed (or if capture failed silently).
    ckpt_snap: Option<PlainCheckpoint>,
    /// The LCP sample recorded for a cold prefix-cache miss at admission. Same-window
    /// fanout siblings rewrite this provisional miss into a hit after the leader primes.
    prefix_miss_lcp: Option<usize>,
    /// PREFIX-CACHE SEED: park the full primed prompt at prefill-done (cold sessions only).
    seed_prefix: bool,
    /// Refcounted lease on the prefix entry this request resumed from (or helped create
    /// through in-batch fanout). Released by the centralized retire sweep on every exit.
    prefix_pin: Option<PrefixPin>,
    tx: tokio::sync::mpsc::UnboundedSender<Event>,
    ttft: Option<Arc<crate::ttft::Trace>>,
    t0: Instant,
}

impl Session {
    /// The (model, namespace) reuse-pool key this session hits and parks under (PC-ISO).
    fn pool_key(&self) -> PoolKey {
        (self.model.clone(), self.cache_ns.clone())
    }
}

/// Primary CUDA ordinal for the serving worker. CUDA_VISIBLE_DEVICES already remaps physical GPUs
/// into a process-local ordinal space, so the non-PP default remains logical device 0. Under PP,
/// the worker primary follows the LAST device in MEMRA_PP_DEVICES — the HEAD stage's device.
///
/// WHY THE LAST, NOT THE FIRST (v0.72 tag-blocker 2, research/v072-fix2-20260808): the sharded
/// loader puts `output_norm` + the lm head on the LAST stage's engine (`hybrid.rs`:
/// `e_head = layer_engine(e, n_trunk, n_trunk-1)`), and the spec-serving round loop runs its
/// whole draft chain on the PRIMARY engine — `mtp_head_forward_dev` op 12 falls back to
/// `&self.output` for every qwen35-family drafter, so EVERY draft token's head matmul reads the
/// last stage's biggest tensor. The round's verify-logit consumers (device argmax, accept
/// kernels, seed gather) read last-stage buffers through the primary context by UVA too. Pinning
/// the primary to stage 0 (the 5f27c55c shape, MEMRA_PP_DEVICES[0]) therefore made every spec
/// round pay cross-device head reads on BOTH placement orders: spec+PP-2 serving collapsed
/// 112.5 -> 17.5 agg tok/s while spec-off (head matmul runs ON the last stage) and engine
/// run-spec (primary=0 = the last stage on the dev10 placement) stayed fast. Following the head
/// stage restores the exact topology every 212/212 crash-gate + 112.5 perf receipt validated
/// (research/pp2spec-crash-20260807), keeps the cx-503b correctness win (the primary is still a
/// placement device, never an unconditional 0), and fixes the pre-merge dev01 ~20x note — the
/// same mismatch, from the other end. Gate/bench binaries keep primary=devices[0]: they
/// deliberately exercise the shared-engine stage-0 case and don't run the serving spec round.
fn worker_device(pp_devices: Option<&str>) -> Result<usize, String> {
    let Some(devices) = pp_devices.filter(|v| !v.trim().is_empty()) else {
        return Ok(0);
    };
    let mut last = 0usize;
    for part in devices.split(',') {
        let part = part.trim();
        last = part.parse::<usize>().map_err(|_| {
            format!(
                "MEMRA_PP_DEVICES={devices} has invalid device {part:?} \
                 (want <d0>,..,<dN-1> e.g. 0,1)"
            )
        })?;
    }
    Ok(last)
}

/// Increment-2 research door. Absent means byte-for-byte pre-lane scheduling; present arms the
/// engine's default-off controller globally for this fresh worker process. Admission inside the
/// engine still refuses every unsupported shape before allocating fork state.
fn optipipe_controller_threshold(raw: Option<&str>) -> Result<Option<f32>, String> {
    let Some(raw) = raw else { return Ok(None); };
    let threshold = raw.parse::<f32>().map_err(|err| {
        format!("MEMRA_OPTI_CONTROLLER_Q={raw:?} is not a float: {err}")
    })?;
    if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {
        return Err(format!(
            "MEMRA_OPTI_CONTROLLER_Q={raw:?} is outside the inclusive [0,1] range"
        ));
    }
    Ok(Some(threshold))
}

/// The worker entry point. Runs on its OWN std::thread. Builds the Engine + loads every model on
/// THIS thread (CUDA-context affinity), then runs the scheduler loop until the command channel
/// closes. `models` = (name, gguf_path) pairs. Sends `ready_tx` once load completes (or the error).
///
/// `rx` is BORROWED, not owned: the supervisor in `spawn()` keeps the Receiver alive across a
/// respawn, because dropping it would close the command channel and make every subsequent HTTP
/// handler's `send` fail permanently — the exact invisible-death this lane exists to remove.
pub fn run(
    models: Vec<(String, String, Option<String>)>,
    rx: &Receiver<Cmd>,
    ready_tx: Sender<Result<(Vec<String>, HashMap<String, ModelCaps>), String>>,
    metrics: SharedMetrics,
    health: crate::health::SharedHealth,
) {
    // ---- one-time init on the worker thread: Engine + all models resident ----
    let pp_devices = std::env::var("MEMRA_PP_DEVICES").ok();
    let device = match worker_device(pp_devices.as_deref()) {
        Ok(device) => device,
        Err(err) => { let _ = ready_tx.send(Err(err)); return; }
    };
    let engine = match Engine::new(device) {
        Ok(e) => e,
        Err(err) => { let _ = ready_tx.send(Err(format!("Engine::new failed: {err}"))); return; }
    };
    // MEMRA_FAST is read ONCE here (same handling as run_gen): the matmul path consults the env var
    // per-call, but logging it once keeps the worker's behavior explicit and stable for the run.
    let fast = std::env::var("MEMRA_FAST").as_deref() != Ok("0");
    eprintln!("[worker] Engine ready (device={device}, MEMRA_FAST={})", fast);
    match optipipe_controller_threshold(
        std::env::var("MEMRA_OPTI_CONTROLLER_Q").ok().as_deref(),
    ) {
        Ok(Some(threshold)) => {
            memra_engine::spec::set_optipipe_controller_threshold(threshold);
            eprintln!(
                "[worker] OPTIPIPE increment-2 diagnostic controller armed q_threshold={threshold:.3}"
            );
        }
        Ok(None) => {}
        Err(err) => { let _ = ready_tx.send(Err(err)); return; }
    }
    log_spec_gate_policy();

    let mut loaded: HashMap<String, LoadedModel> = HashMap::new();
    let mut order: Vec<String> = Vec::new();
    for (name, path, draft) in &models {
        eprintln!("[worker] loading model {name:?} <- {path}");
        // DIRECTORY path = safetensors HF checkpoint or a manifest-backed memra repack/overlay;
        // file = GGUF. Repack tokenizers live in the manifest's source_dir.
        let from_dir = std::path::Path::new(path).is_dir();
        let (model, tok) = if from_dir {
            let dir = std::path::Path::new(path);
            let (src, tok_dir): (Box<dyn memra_gguf::source::TensorSource>, std::path::PathBuf) =
                if dir.join("manifest.json").exists() {
                    let repack = match memra_gguf::source::Hy3RepackSource::open(dir) {
                        Ok(source) => source,
                        Err(err) => { let _ = ready_tx.send(Err(format!("open {path}: {err}"))); return; }
                    };
                    let tok_dir = repack.source_dir()
                        .filter(|source| source.join("tokenizer.json").exists())
                        .unwrap_or(dir).to_path_buf();
                    (Box::new(repack), tok_dir)
                } else {
                    let st = match memra_gguf::source::SafetensorsSource::open(dir) {
                        Ok(source) => source,
                        Err(err) => { let _ = ready_tx.send(Err(format!("open {path}: {err}"))); return; }
                    };
                    (Box::new(st), dir.to_path_buf())
                };
            let model = match HybridModel::load_from_source(&engine, src.as_ref()) {
                Ok(m) => m,
                Err(err) => { let _ = ready_tx.send(Err(format!("load {name}: {err}"))); return; }
            };
            let tok = match Tokenizer::from_hf_dir(&tok_dir) {
                Ok(t) => t,
                Err(err) => { let _ = ready_tx.send(Err(format!("tokenizer {name}: {err}"))); return; }
            };
            (model, tok)
        } else {
            let g = match GgufFile::open(path) {
                Ok(g) => g,
                Err(err) => { let _ = ready_tx.send(Err(format!("open {path}: {err}"))); return; }
            };
            let model = match HybridModel::load(&engine, &g) {
                Ok(m) => m,
                Err(err) => { let _ = ready_tx.send(Err(format!("load {name}: {err}"))); return; }
            };
            let tok = match Tokenizer::from_gguf(&g) {
                Ok(t) => t,
                Err(err) => { let _ = ready_tx.send(Err(format!("tokenizer {name}: {err}"))); return; }
            };
            (model, tok)
        };
        // Per-model regime draft (MEMRA_MODELS "+<draft.gguf>" syntax): replace the embedded
        // MTP head with the standalone regime draft — same load path as MEMRA_MTP_DRAFT but
        // scoped to THIS model, so a multi-model server drafts each model with its own file.
        //
        // THIS IS ALSO THE step35 EXTERNAL-MTP ATTACH (lane/step-draft, 2026-08-07). Step-3.7-
        // Flash ships its three chained NextN blocks in a SEPARATE GGUF, so the trunk parses
        // `nextn_predict_layers=0` and loads with `mtp == None`. No new spelling was added:
        // `+draft` already means "replace this model's MTP head with the head in that file",
        // and `MtpHead::load_draft` already resolves step35's per-layer draft geometry from the
        // drafter file's own arrays (d316162c). The gap was never the attach syntax — it was
        // that a step35 model loaded WITHOUT one said nothing. See the verdict below.
        let model = {
            let mut model = model;
            if let Some(dpath) = draft {
                let dg = match GgufFile::open(dpath) {
                    Ok(g) => g,
                    // REFUSE, don't degrade: a drafter path was GIVEN, so booting without it
                    // would serve plain decode under a config that explicitly asked for spec.
                    // The error text is the driver's/loader's own, quoted, never inferred.
                    Err(err) => {
                        let _ = ready_tx.send(Err(format!(
                            "draft {name}: {err} (drafter path {dpath:?} was requested via the \
                             MEMRA_MODELS '+draft' attach — refusing to start rather than \
                             silently serving plain decode)")));
                        return;
                    }
                };
                match memra_engine::hybrid::MtpHead::load_draft(&engine, &dg, &model.cfg) {
                    Ok(head) => {
                        eprintln!("[worker] {name}: regime draft attached ({dpath})");
                        model.mtp = Some(head);
                    }
                    Err(err) => {
                        let _ = ready_tx.send(Err(format!(
                            "draft {name}: {err} (drafter path {dpath:?} was requested via the \
                             MEMRA_MODELS '+draft' attach — refusing to start rather than \
                             silently serving plain decode)")));
                        return;
                    }
                }
            }
            model
        };

        // LOUD DRAFTER SEMANTICS (lane/step-draft, 2026-08-07). The silent-degradation class
        // this closes: `spec_eligible` requires `lm.model.mtp.is_some()`, so a step35 trunk
        // served without a drafter took plain decode on every request with NO log line saying
        // so — named as defect (A) in `research/step37-p2-20260806/PROGRESS.md`. A server that
        // forgoes its whole felt-latency story must say it out loud.
        //
        // The verdict is computed from a PURE function (`draft_verdict`) so both branches are
        // pinned by GPU-free tests. (#87's spec-over-PP-2 refusal used to live here too —
        // CLOSED 2026-08-08, see `draft_verdict`; spec+PP-2 now serves, gates in
        // research/pp2spec-crash-20260807/.)
        let verdict = draft_verdict(model.mtp.is_some(), model.cfg.arch.is_step35());
        if let Some(msg) = draft_verdict_message(&verdict, name, path) {
            eprintln!("{msg}");
        }

        let eos_id = tok.eos_id();
        eprintln!("[worker]   loaded {name:?}: {} layers, eos={eos_id}", model.cfg.n_layer);
        // (#68 closed 2026-08-04: the former ST-spec quarantine notice lived here — dir
        // checkpoints are spec-eligible again, research/fp8ship-20260804/RESULTS.md.)
        loaded.insert(name.clone(), LoadedModel {
            model, tok, eos_id, from_dir, constraints: std::cell::OnceCell::new(),
        });
        order.push(name.clone());
    }
    // Template capability probe (serve-tools lane): same substring laws the renderer uses.
    // + /v1/models metadata (serve-tail lane): context length from the model config,
    // tokenizer family from the pre-tokenizer name, instruct family from the template's
    // turn markers. Unknown stays 0/""/None — the route reports honest nulls.
    let caps: HashMap<String, ModelCaps> = loaded.iter().map(|(n, lm)| {
        let t = lm.tok.chat_template();
        let caps = ModelCaps {
            tools_branch: t.is_some_and(|t| t.contains("<tools>")
                && !t.contains("hy_User") && !t.contains("<|turn>")),
            qwen_think: t.is_some_and(|t| t.contains("<think>") && t.contains("add_generation_prompt")),
            think_switch: t.is_some_and(|t| t.contains("enable_thinking")),
            // GGUF keeps the historical ChatML fallback for template-less models; a dir
            // checkpoint (safetensors/repack) must CARRY its template (tokenizer_config
            // chat_template or chat_template.jinja) or chat requests 400 (serve-st v1).
            chat_ok: t.is_some() || !lm.from_dir,
            context_length: lm.model.cfg.context_length as usize,
            tokenizer: lm.tok.pre().to_string(),
            instruct_type: t.and_then(|t| {
                if t.contains("<|im_start|>") { Some("chatml".to_string()) }
                else if t.contains("<start_of_turn>") { Some("gemma".to_string()) }
                else { None }
            }),
            // Templates that CONSUME a `reasoning_effort` input, keyed on the jinja input
            // test itself (`reasoning_effort is defined`) — true for step35 (renders
            // `Reasoning: {level}` into the system turn) and hy3 (renders
            // `reasoning_effort:{no_think|low|high}` into its header), false for the
            // qwen/gemma4 classes (binary `enable_thinking`, carried by ThinkMode instead).
            effort_levels: t.is_some_and(|t| t.contains("reasoning_effort is defined")),
            // keyed on the dialect's own thought-channel marker in the shipped template
            // (research/step-sku-20260807/templates/gemma4-12b-qat.chat_template.jinja:
            // strip_thinking splits on `<|channel>`). Template-keyed like every other cap —
            // a gemma4 GGUF without its template falls back to ChatML rendering, where
            // arming a channel splitter would be guessing.
            gemma_think: t.is_some_and(|t| t.contains("<|channel>")),
            chat_temperature_default: lm.model.cfg.arch.is_step35().then_some(0.5),
            chat_top_p_default: lm.model.cfg.arch.is_step35().then_some(0.9),
        };
        eprintln!("[worker] {n}: template caps tools={} think={} think_switch={} chat_ok={} \
                   effort_levels={} gemma_think={} ctx={} tok={:?} instruct={:?} \
                   chat_defaults={:?}/{:?}",
                  caps.tools_branch, caps.qwen_think, caps.think_switch, caps.chat_ok,
                  caps.effort_levels, caps.gemma_think, caps.context_length, caps.tokenizer,
                  caps.instruct_type, caps.chat_temperature_default, caps.chat_top_p_default);
        (n.clone(), caps)
    }).collect();
    let _ = ready_tx.send(Ok((order.clone(), caps)));
    // INFERENCE LIVENESS (G5): weights are resident and the scheduler loop is about to run —
    // /health and /readyz go green HERE, not when the HTTP listener binds. Also clears the
    // fault latch, which is what makes a respawn's success observable.
    health.mark_ready();

    // Per-model decode chunk width (inc3 3a): computed once — model tensors and mirrors
    // are fixed after load.
    let chunk_caps: HashMap<String, usize> =
        loaded.iter().map(|(n, lm)| (n.clone(), chunk_cap_for(lm))).collect();
    for (n, c) in &chunk_caps {
        eprintln!("[worker] {n}: decode chunk cap {c}{}",
                  if *c > 8 { " (exact-16 tier)" } else { "" });
    }
    // EAGER-ONLY models (lane/gemma4-serve-gaps, 2026-08-07): no batched decode arm, no
    // batched prime core, no step-wise graph capture — every batched-scheduler entry point
    // below routes around them (per-session eager decode, monolithic prefill, no graph
    // promotion, no prime batching). Before this route existed, ONE request to a gemma4
    // model on the default scheduler panicked the worker on decode_step_batch's gemma4
    // assert, the respawn re-panicked on the queued request, and the process FATALed
    // (research/gemma4-serve-20260807/raw/repro-panic-server-*.log).
    let eager_only: std::collections::HashSet<String> = loaded.iter()
        .filter(|(_, lm)| eager_only_model(lm))
        .map(|(n, _)| n.clone()).collect();
    for n in &eager_only {
        eprintln!("[worker] {n}: EAGER-ONLY serving (gemma4 class — no batched decode arm): \
                   per-session eager decode, monolithic prefill, no graph promotion, \
                   no prime batching");
    }

    // ---- scheduler loop ----
    let mut active: Vec<Session> = Vec::new();
    let mut queue: std::collections::VecDeque<Box<Request>> = std::collections::VecDeque::new();
    // KV prefix-reuse pool (append-only continuation; see ReuseEntry doc). Keyed by
    // (model, namespace) — cross-request continuation state is tenant-scoped too (PC-ISO).
    let mut reuse: HashMap<PoolKey, Vec<ReuseEntry>> = HashMap::new();
    let mut spec_reuse: HashMap<PoolKey, Vec<SpecReuseEntry>> = HashMap::new();
    // F5: learned spec-session sizing (evict-first models + right-sized ctx asks).
    let mut spec_sizing = SpecSizing::default();
    let mut reuse_metrics = ReuseMetrics::default();
    // Cross-request prefix cache (token-prefix keyed, budget-bound; see the module doc above).
    let mut px = PrefixCache::default();
    if memra_engine::pp::pp_host_bounce_active() {
        eprintln!(
            "[pp] MEMRA_PP_HOST_BOUNCE=1 safety doors: speculative PP, cross-device prefix \
             snapshots, and plain-affinity checkpoints disabled (they retain peer reads/copies)"
        );
    }
    if prefix_cache_budget_bytes() > 0 && serve_batching() {
        eprintln!("[prefix-cache] on: budget {:.0}MB (MEMRA_PREFIX_CACHE_MB), min prefix {} tokens",
                  prefix_cache_budget_bytes() as f64 / 1e6, PREFIX_CACHE_MIN_TOKENS);
    }
    // Request-shaped session cost: exact context-linear cache/scratch geometry plus a measured
    // fixed high-water residual. Unlike the old first-admit scalar, this is armed before request 1
    // and every estimate uses that request's own effective context cap.
    let mut admission_costs: HashMap<String, AdmissionCostModel> = loaded
        .iter()
        .map(|(name, lm)| (name.clone(), AdmissionCostModel::new(&lm.model)))
        .collect();
    for (name, cost) in &admission_costs {
        if cost.ring_rows > 0 {
            eprintln!(
                "[admission] {name:?}: plain {} B/token ({} capped at {} rows), spec {} \
                 B/token ({} capped); fixed residual learns from effective-free deltas",
                cost.plain_bytes_per_token,
                cost.plain_ring_bytes_per_token,
                cost.ring_rows,
                cost.spec_bytes_per_token,
                cost.spec_ring_bytes_per_token,
            );
        } else {
            eprintln!(
                "[admission] {name:?}: plain {} B/token, spec {} B/token; fixed residual learns \
                 from effective-free deltas",
                cost.plain_bytes_per_token,
                cost.spec_bytes_per_token,
            );
        }
    }

    // ---- serving counters + engine-truth step stats (30s percentile window) ----
    // Lane machinery (x-lane QoS gate, lane/dl-metering port): policy from env; step_stats
    // is the INTERACTIVE SLO sensor (records only ticks that advanced an interactive
    // session — on naked traffic every session is interactive, so /metrics is unchanged).
    let policy = crate::lanes::LanePolicy::from_env();
    let prefill_tick_explicit = std::env::var_os("MEMRA_PREFILL_TICK").is_some();
    let mut step_stats = StepStats::new(
        std::env::var("MEMRA_LANE_WINDOW_S").ok().and_then(|v| v.parse().ok()).unwrap_or(30.0));
    let mut n_admitted = 0u64;
    let mut n_completed = 0u64;
    let mut n_tokens_out = 0u64;
    let mut n_prompt_in = 0u64;
    let mut n_cached_in = 0u64;
    let mut n_session_defers = 0u64;
    let mut n_vram_defers = 0u64;
    let mut n_step_oom_parks = 0u64;
    // Per-tenant prompt/cached split (lane/cache-metering): keyed by the tenant half of
    // the PC-ISO namespace (auth::meter_key). Bounded: past METER_TENANT_CAP distinct
    // keys, new traffic aggregates under "(other)" — a salt-spraying client cannot grow
    // worker memory. Updated once per ADMIT (request-frequency, never per-token).
    let mut ns_tokens: HashMap<String, [u64; 2]> = HashMap::new();
    let mut lane_admitted = [0u64; 3];
    let mut lane_shed = [0u64; 3];
    let mut lane_completed = [0u64; 3];
    let mut lane_tokens = [0u64; 3];
    let mut last_batch = 0usize;
    // Per-model spec acceptance telemetry (lane/accept-telemetry): worker-owned like every
    // counter above; published on the same 32nd-tick snapshot AND whenever a spec session
    // retires (so a one-shot request's counts are visible without waiting 32 ticks).
    let mut spec_telem: HashMap<String, memra_engine::spec::SpecTelemetry> = HashMap::new();
    let mut spec_telem_dirty = false;
    // Detection-only per-tenant acceptance divergence (ADSD). Samples arrive once per
    // retired spec request, so this adds no per-token work and shares the forced-retire
    // metrics publication above.
    let mut adsd_detector = AdsdDetector::default();
    // Starvation sentinel (estimator blind spot, 2026-07-26 native-judge battery): last
    // time an interactive session decoded. Interactive work waiting with no interactive
    // decode tick inside the SLO age IS an SLO breach the percentile window can't see.
    let mut last_interactive_decode = Instant::now();
    let mut tick_n: u64 = 0;
    // SPEC GATE (lane/spec-gate): how many live sessions this worker has handed from the spec
    // burst path to batched decode. The thrash observable — under a correct hysteresis band
    // this counts LOAD CROSSINGS, not ticks (a per-tick demotion count would mean the band is
    // too narrow or the handoff is failing and re-firing).
    let mut n_demoted = 0u64;

    loop {
        // 1. Drain pending commands. Block ONLY when there is no work at all (no active sessions),
        //    otherwise poll non-blocking so the decode loop keeps interleaving.
        if active.is_empty() && queue.is_empty() {
            // IDLE PHASE (G5): about to block indefinitely in recv() with zero work. An idle
            // worker legitimately stamps no heartbeat for hours, so the phase — not the beat
            // age — is what /health reads here. Stamped on BOTH sides of the block so the
            // beat is already fresh the instant work arrives (see health.rs).
            health.set_phase(crate::health::PHASE_IDLE);
            match rx.recv() {
                Ok(cmd) => {
                    health.set_phase(crate::health::PHASE_BUSY);
                    handle_cmd(cmd, &loaded, &order, &mut queue);
                }
                Err(_) => break, // all senders dropped -> shutdown
            }
        }
        // BUSY PHASE: work is in flight, so the beat MUST advance every iteration. The
        // stamp is a bare atomic store (no mutex, no syscall) — unlike the metrics publish
        // below it is NOT throttled, because a heartbeat sampled every 32nd tick would give
        // health a 32-tick blind spot at exactly the moment a tick stops returning.
        health.beat_busy();
        loop {
            match rx.try_recv() {
                Ok(cmd) => handle_cmd(cmd, &loaded, &order, &mut queue),
                Err(std::sync::mpsc::TryRecvError::Empty) => break,
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    if active.is_empty() { return; } else { break; }
                }
            }
        }

        // 2. ADMISSION + LANE GATE (x-lane yield gate, engine-side): interactive admits up
        //    to the cap and WAITS beyond it (FIFO, never rejected — its queue wait is the
        //    protected tenant's own backlog). Judge/harvest are gated on the measured
        //    interactive step p99 vs their SLO fraction and SHED with an immediate
        //    retryable error (HTTP 429 at the handler) — dark-lane work is NEVER queued
        //    inside the engine (the B2 lesson: the engine queue is where the tail dies).
        //    Interactive cap stays the legacy MEMRA_MAX_SESSIONS knob (naked-path
        //    preserving; policy.max_sessions[0] is the sidecar's knob, unused here);
        //    judge/harvest caps come from the lane policy.
        let max_active = if confidence_trace_enabled() { 1 } else { MAX_ACTIVE };
        let mut requeue: std::collections::VecDeque<Box<Request>> = Default::default();
        // Per-tick count of requests the VRAM gate deferred (logged once per tick).
        let mut vram_defers = 0usize;
        while let Some(mut req) = queue.pop_front() {
            // DISCONNECT ABORT (gap-scan F8): a queued request whose client already hung
            // up (receiver dropped) never reaches the GPU — dropped here, logged for the
            // metering record (0 generated; prompt never primed).
            if req.tx.is_closed() {
                eprintln!("[abort] client disconnected while queued (model {:?}); dropped",
                          req.model);
                continue;
            }
            let lane = req.lane;
            let batching_on = std::env::var("MEMRA_SERVE_BATCH").map(|v| v != "0").unwrap_or(true);
            let cap = if lane == crate::lanes::Lane::Interactive {
                if batching_on {
                    std::env::var("MEMRA_MAX_SESSIONS").ok()
                        .and_then(|v| v.parse().ok()).unwrap_or(64)
                } else {
                    max_active
                }
            } else {
                policy.max_sessions[lane.idx()]
            };
            let lane_count = active.iter().filter(|s| s.lane == lane).count();
            if lane_count >= cap {
                if lane == crate::lanes::Lane::Interactive {
                    n_session_defers += 1;
                    requeue.push_back(req);   // waits (FIFO), never shed
                } else {
                    lane_shed[lane.idx()] += 1;
                    let _ = req.tx.send(Event::Error(EngineError::rate_limit(format!(
                        "lane {} is at capacity, retry", lane.as_str()))));
                }
                continue;
            }
            // Starvation sentinel closes the estimator's blind spot (2026-07-26 native-judge
            // battery): interactive work EXISTS but no interactive decode tick ran within
            // the SLO age — starvation IS a breach even though the p99 window can't see it.
            let interactive_active_or_waiting = active.iter()
                .any(|s| s.lane == crate::lanes::Lane::Interactive);
            let starved = interactive_active_or_waiting
                && last_interactive_decode.elapsed().as_secs_f32() * 1000.0 > policy.slo_p99_ms;
            if !policy.admit(lane, &mut step_stats, starved) {
                lane_shed[lane.idx()] += 1;
                let _ = req.tx.send(Event::Error(EngineError::rate_limit(format!(
                    "lane {} shed: interactive p99 over budget, retry", lane.as_str()))));
                continue;
            }
            let shape = match prepare_request(&loaded, &mut req) {
                Ok(shape) => shape,
                Err(err) => {
                    let _ = req.tx.send(Event::Error(err));
                    continue;
                }
            };
            let model_key = req.model.clone();
            let prompt_len = req.prepared_prompt.as_ref().unwrap().len();
            let estimate_spec = admission_request_may_spec(
                &loaded[&model_key],
                &req,
                active.len() + 1,
                prompt_len,
            );
            let admission_cap = shape.admission_cap();
            let (cost, bytes_per_token, activation_bytes, log_estimate) = {
                let model = admission_costs.get_mut(&model_key)
                    .expect("loaded model missing admission cost model");
                let cost = model.estimate(admission_cap, estimate_spec);
                let key = (admission_cap, estimate_spec, cost);
                let log = model.last_logged != Some(key);
                if log {
                    model.last_logged = Some(key);
                }
                (cost, model.bytes_per_token(estimate_spec), model.activation_bytes, log)
            };
            if log_estimate {
                eprintln!(
                    "[admission] request cost: model={model_key:?} ctx={} path={} = {} \
                     B/token x ctx + {:.0}MB fixed = {:.0}MB",
                    admission_cap,
                    if estimate_spec { "spec" } else { "plain" },
                    bytes_per_token,
                    activation_bytes as f64 / 1e6,
                    cost as f64 / 1e6,
                );
            }

            // VRAM-AWARE ADMISSION (lane/fast-router, 2026-08-02). The original gate learned
            // one scalar from the first measurable admit. At mixed context that scalar was
            // guaranteed wrong in one direction: a short first request over-admitted a later
            // 256k cache, while a large first request over-gated later short work. The estimate
            // above instead mirrors the allocator's bytes/token geometry at THIS request's
            // effective ctx and adds only a measured fixed high-water residual. The first
            // session still passes because there is no peer to protect; a capacity failure with
            // no active sessions remains an honest allocation error.
            //
            // ADMIT-OOM FIX (lane/admit-oom, 2026-08-06 — research/admit-oom-20260806).
            // The `2x cost` model above is DISHONEST for spec sessions and c=64 on 24GB
            // proved it: 0/64 well-formed, every stream dead of a step-time
            // CUDA_ERROR_OUT_OF_MEMORY (research/serving-density-20260806/VERDICT.md §Q2).
            // Two independent errors, both measured against the three PASSING controls
            // (cap16/32/48 peaks 11400/15948/20528 MiB over 5540 MiB of weights):
            //
            //   1. The old scalar `cost` UNDERSTATED the live footprint it predicted. It was
            //      the free-VRAM delta of the FIRST ADMIT — a PARKED session (flat KV + draft
            //      scratch, 192 MiB here) — while a session that has actually BURST also
            //      holds its persistent draft-graph context, q slots, and round snapshots.
            //      The three controls fit peak = weights + N x 286 MiB + ~1.3 GiB, i.e. the
            //      live resident cost is 1.49x the parked delta. This term needs no new
            //      measurement: `free` from mem_get_info is GROUND TRUTH and already
            //      reflects every live session's real 286 MiB. The bug was never the
            //      subtrahend — it was sizing the HEADROOM against the wrong quantity.
            //   2. The headroom that matters is a CONSTANT, non-N-scaled transient (the
            //      same fit puts it at ~1.3 GiB): sampled draft-graph CAPTURE arenas,
            //      verify activations, prime chunk slabs. `2x cost` = 384 MiB cannot cover
            //      it, so the card ran to 23.98 of 24.46 GB during admission and the
            //      transient had nowhere to land. This is EXACTLY the class
            //      SPEC_SHRINK_RESERVE (1.5 GiB) already encodes for the F5 ladder's
            //      landing probe — and the control fit independently validates that
            //      constant to within 252 MiB. Charge it as an admission FLOOR.
            //
            // The gate is therefore `free >= cost + reserve`, where the reserve applies
            // only to models that can actually take the spec path (the plain batched path
            // survived c=64 unaided — spec-OFF cap64 PASSED — and must not pay a 1.5 GiB
            // toll it does not need). Consequence, by arithmetic on the measured fit:
            // admission stops at ~55 spec sessions on this card and the REST QUEUE (FIFO,
            // never rejected — completion is 64/64, just paced), instead of 64
            // admitted-then-killed. At the passing controls free-at-peak is 3.9-13.1 GB
            // against a 1.7 GB bar, so the new term CANNOT bind and c <= 48 is
            // behaviorally IDENTICAL (the no-regression contract: this math only bites
            // where the old gate over-admitted).
            if !active.is_empty() {
                if let Some((mut free, mut pool_cached)) = effective_free_bytes(&engine) {
                    // Reserve contract (lane/admit-oom, right-sized by lane/kv256-capacity
                    // 2026-08-09): spec-capable models pay the fixed transient floor. The
                    // plain path used to retain one FULL session-cost of headroom — correct
                    // when costs were small scalars, but at a request-shaped 262,144 charge
                    // (21,894 MB on Step-3.7-Flash) that "headroom" equals a whole second
                    // session for a transient class the admit-oom control fit measured at a
                    // CONSTANT ~1.3 GiB (capture arenas, prime chunk slabs — chunk-bounded,
                    // never ctx-scaled). Cap the plain reserve at the same measured floor:
                    // requests whose cost is below the floor keep the old (identical)
                    // behavior, large-context requests stop paying a session-sized toll for
                    // a transient that cannot reach it. The PP-2 plain-only pod shape
                    // (placement K=0 — serve_spec_enabled() false) is exactly where this
                    // bound: before, 262k session capacity on the 96GB pair was halved by
                    // reserve == cost. Step-OOM park + alloc-OOM reclaim-retry remain the
                    // backstops the floor was gated against.
                    let reserve = admission_reserve(
                        serve_spec_enabled()
                            && loaded.get(&req.model).is_some_and(|lm| lm.model.mtp.is_some()),
                        cost,
                        admit_reserve_override(),
                    );
                    // EFFECTIVE free, not driver `free`: `mem_get_info` cannot see blocks the
                    // async pool holds mapped-but-not-live (Engine::new pins RELEASE_THRESHOLD
                    // to u64::MAX), yet the next alloc is satisfied from exactly those bytes,
                    // so a `free`-only read can only ever UNDER-count headroom — the wrong
                    // direction for a gate that queues real work.
                    //
                    // This term is LOAD-BEARING, and its own diagnostic explains why it looks
                    // small. Without it (first fixed build) a c=64 burst deferred on 36 ticks
                    // and crawled at `1 active, free 902MB` through the back half of the run:
                    // each retire returned its session KV to the pool, driver `free` never
                    // moved, so the gate saw a full card while the pool sat on the space. With
                    // it: 5 defers, 59 active sustained, queue never deeper than 4.
                    // Measured pool-cached is then only 34-89 MB — precisely BECAUSE admission
                    // keeps refilling the slots, so nothing accumulates unclaimed. The term is
                    // small exactly when it is doing its job, and large when it is missing.
                    // (fix-run2-server.log vs fix-pool-run{1,2}-server.log.)
                    //
                    // The same diagnostic line independently confirms the cost fit this gate is
                    // built on: at 59 active the pool reports res 22783MB / used 22749MB
                    // (reserved ~= used, i.e. genuinely live, nothing hiding), which against
                    // 5540 MiB of weights is 292 MB per live session — the control fit said
                    // 286 MiB, from a completely different measurement.
                    let required = cost.saturating_add(reserve);
                    if free < required {
                        // Dormant sessions are reclaimable capacity, not a reason to queue live
                        // work. Evict globally oldest across both existing pool maps, re-reading
                        // effective headroom after each drop. This is deliberately only a hook:
                        // pool keys, vectors, identity, checkpoints, and resume selection remain
                        // owned by their respective lanes.
                        let free_before_reclaim = free;
                        let mut evicted_plain = 0usize;
                        let mut evicted_spec = 0usize;
                        while free < required {
                            match evict_oldest_parked(
                                &mut reuse,
                                &mut spec_reuse,
                                &mut reuse_metrics,
                            ) {
                                Some(ParkedPool::Plain) => evicted_plain += 1,
                                Some(ParkedPool::Spec) => evicted_spec += 1,
                                None => break,
                            }
                            let Some((next_free, next_cached)) = effective_free_bytes(&engine)
                            else { break };
                            free = next_free;
                            pool_cached = next_cached;
                        }
                        if evicted_plain + evicted_spec > 0 {
                            eprintln!(
                                "[admit-oom] reclaim-on-defer: evicted {} plain + {} spec \
                                 parked sessions (global LRU); effective free {:.0}MB -> {:.0}MB",
                                evicted_plain,
                                evicted_spec,
                                free_before_reclaim as f64 / 1e6,
                                free as f64 / 1e6,
                            );
                        }
                    }
                    if free < required {
                        // Pacing receipt: the defer path used to be SILENT, which is why the
                        // pre-fix red read as "all 64 admitted then all 64 died" with no
                        // visible back-pressure. One line per tick (not per deferred request)
                        // keeps a 64-client burst readable.
                        if vram_defers == 0 {
                            let (res, used) = engine.pool_reserved_used();
                            let parked: usize = spec_reuse.values().map(|v| v.len()).sum();
                            eprintln!("[admit-oom] VRAM defer: {} active, effective free \
                                       {:.0}MB (driver + {:.0}MB pool-cached) < cost {:.0}MB \
                                       + reserve {:.0}MB — queueing (FIFO) \
                                       [pool res {:.0}MB used {:.0}MB; parked spec sessions {}; \
                                       plain reuse {}; queue {}]",
                                      active.len(), free as f64 / 1e6,
                                      pool_cached as f64 / 1e6,
                                      cost as f64 / 1e6, reserve as f64 / 1e6,
                                      res as f64 / 1e6, used as f64 / 1e6, parked,
                                      reuse.values().map(|v| v.len()).sum::<usize>(),
                                      queue.len() + requeue.len());
                        }
                        vram_defers += 1;
                        n_vram_defers += 1;
                        requeue.push_back(req);   // waits (FIFO), never rejected
                        continue;
                    }
                }
            }
            let free_before = effective_free_bytes(&engine).map(|(free, _)| free);
            match admit(&engine, &loaded, &mut reuse, &mut spec_reuse, &mut spec_sizing,
                        &mut reuse_metrics, &mut px, active.len(), *req, shape) {
                Ok(s) => {
                    let actual_spec = s.spec.is_some();
                    let actual_ctx = s.spec.as_ref().map(|spec| spec.cache_max_ctx())
                        .or_else(|| s.cache.as_ref().map(|cache| cache.max_ctx))
                        .unwrap_or(shape.ctx_cap);
                    if let (Some(before), Some((after, _))) =
                        (free_before, effective_free_bytes(&engine))
                    {
                        let observed = before.saturating_sub(after);
                        let model = admission_costs.get_mut(&model_key)
                            .expect("loaded model missing admission cost model");
                        if let Some(residual) = model.observe(observed, actual_ctx, actual_spec) {
                            model.last_logged = None;
                            eprintln!(
                                "[admission] fixed residual high-water: model={model_key:?} \
                                 {:.0}MB (observed {:.0}MB at ctx {} path={})",
                                residual as f64 / 1e6,
                                observed as f64 / 1e6,
                                actual_ctx,
                                if actual_spec { "spec" } else { "plain" },
                            );
                        }
                    }
                    n_admitted += 1;
                    lane_admitted[lane.idx()] += 1;
                    n_prompt_in += s.n_prompt as u64;
                    n_cached_in += s.n_cached as u64;
                    // per-tenant split (lane/cache-metering): the tenant half of the
                    // PC-ISO namespace; bounded map, overflow lands in "(other)".
                    meter_account(&mut ns_tokens, &s.cache_ns,
                                  s.n_prompt as u64, s.n_cached as u64);
                    active.push(s);
                }
                Err((tx, msg)) => { let _ = tx.send(Event::Error(msg)); }
            }
        }
        queue = requeue;

        // 3. The tick. Three phases (MEMRA_SERVE_BATCH=0 restores legacy round-robin):
        //    (a) spec sessions burst solo (spec x batch composition is a later step);
        //    (b) prefilling sessions prime at the full tick chunk (PREFILL_TICK_T);
        //    (c) decoding sessions advance through BATCHED steps: sample+emit host-side, then
        //        decode_step_batch over survivors in chunks of <= 8.
        let batching = serve_batching();
        let mut finished: Vec<usize> = Vec::new();
        // STEP-OOM PARK (lane/admit-oom): requests parked out of a step-time CUDA OOM this
        // tick. Drained onto the FRONT of the admission queue after the retire sweep — the
        // retire is what frees the VRAM their re-admit needs, and front-insertion keeps them
        // ahead of later arrivals (they were admitted first; a park must not send a request
        // to the back of the line and starve it).
        let mut requeue_oom: std::collections::VecDeque<Box<Request>> = Default::default();
        // DISCONNECT ABORT (gap-scan F8): every send in the tick loop is `let _ =
        // s.tx.send(..)` — send errors ignored — so an aborted client used to burn GPU
        // until max_tokens/EOS and hold a slot against admission. The per-tick sweep
        // retires closed-channel sessions BEFORE any phase steps them; the log line is
        // the metering record (bill-to-abort-point: prompt/cached/generated so far).
        // Retire still parks reusable KV — the state is consistent at the abort point.
        for (i, s) in active.iter().enumerate() {
            if s.tx.is_closed() {
                abort_log(s);
                finished.push(i);
            }
        }
        if !batching {
            for i in 0..active.len() {
                if finished.contains(&i) { continue; }
                let generated_before = active[i].generated.len();
                let lane = active[i].lane;
                let step_started = Instant::now();
                let step_result = step_session(&engine, &loaded, &mut active[i], &mut spec_telem);
                record_output_progress(
                    generated_before,
                    active[i].generated.len(),
                    lane,
                    step_started.elapsed().as_secs_f32() * 1000.0,
                    &mut n_tokens_out,
                    &mut lane_tokens,
                    &mut step_stats,
                    &mut last_interactive_decode,
                );
                match step_result {
                    Ok(true) => {}
                    Ok(false) => finished.push(i),
                    Err(err) => {
                        let _ = active[i].tx.send(Event::Error(EngineError::engine(format!("step error: {err}"))));
                        finished.push(i);
                    }
                }
            }
        } else {
            // (a0) SINGLE-SESSION GRAPH PATH (MEMRA_SERVE_GS=0 disables). Promote a lone cold
            // greedy interactive session to GraphSession replay (+34% at B=1); degrade back
            // to batched-eager the moment concurrency arrives (dc==eager bit-identity makes
            // the cache handoff seamless).
            let gs_on = {
                static G: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
                *G.get_or_init(|| std::env::var("MEMRA_SERVE_GS").map(|v| v != "0").unwrap_or(true))
            };
            if gs_on && active.len() > 1 {
                for i in 0..active.len() {
                    if finished.contains(&i) || active[i].graph.is_none() { continue; }
                    let s = &mut active[i];
                    let g = s.graph.take().unwrap();
                    s.cache = Some(g.cache);
                    if let Some(pend) = s.graph_pending.take() {
                        let (cont, _) = advance_token_emit(&loaded, s, pend);
                        if !cont {
                            finished.push(i);
                        } else {
                            let lm = &loaded[&s.model];
                            match lm.model.decode_step(&engine, pend, s.cache.as_mut().unwrap()) {
                                Ok(l) => { s.last_logits = l; s.fed.push(pend); }
                                Err(err) => {
                                    let _ = s.tx.send(Event::Error(EngineError::engine(format!("degrade: {err}"))));
                                    finished.push(i);
                                }
                            }
                        }
                    }
                }
            }
            if gs_on && active.len() == 1 && !finished.contains(&0) {
                let s = &mut active[0];
                // Promote only generations long enough to amortize the one-time
                // capture+snapshot (~340ms measured = ~330-token break-even at the
                // 1.03ms/tok graph saving). Short requests stay eager-batched.
                let gs_min: usize = std::env::var("MEMRA_GS_MIN").ok()
                    .and_then(|v| v.parse().ok()).unwrap_or(384);
                // POST-PREFILL promotion (round 35): the old cold promotion re-primed the
                // prompt TOKEN-WISE inside graph_session_new — a live ~3x end-to-end LOSS
                // for solo long prompts (measured 871-tok/400-gen: 6.4s vs ~2.2s eager).
                // Now the normal chunked/batched prefill primes first; the graph session
                // captures OVER that cache (graph_session_from_cache). TTFT pays only the
                // one-time capture (~340ms), amortized by the gs_min budget gate.
                // CONSTRAINED sessions promote too (constrained-full, 2026-08-03): the
                // captured step bans the packed grammar mask on device before its argmax
                // (stable mask pointer, contents re-uploaded per step). Host-oracle and
                // fallback-sampler constrained sessions stay eager.
                // SAMPLED sessions do NOT graph-promote (`is_greedy()` below) — a separate,
                // untaken lever. It costs nothing today: this promotion only fires for
                // `s.spec.is_none()` solo sessions, and on an MTP model every sampled
                // session already rides the (faster) sampled spec burst path instead. It
                // would only matter for sampled sessions on a NON-MTP model; capturing the
                // seeded gumbel draw needs the in-graph RNG-counter bump the spec draft
                // chain already has (spec.rs sctr_inc), so it is wiring, not new math.
                let constr_graph_ok = s.constraint.is_none()
                    || (!constrain_host() && devsample_meta(s).is_some());
                // EAGER-ONLY models never graph-promote (lane/gemma4-serve-gaps): the
                // step-wise capture body (decode_step_dc_cap_masked) walks the GENERIC
                // qwen-class layer stack — over gemma4 weights that is silently wrong
                // logits (the round-45 g12 argmax-INIT class), not an error.
                // step35 never graph-promotes either (lane/step35-batched-decode): the
                // capture walks full_attn_decode_dc_inner, which REFUSES step35 by design
                // (the SWA offset KV view is inexpressible in the len_d-derived dc kernels,
                // plus per-layer n_head capture) — and a capture-time refusal lands on the
                // degrade-with-cache-consumed path, which kills the request. So a solo
                // greedy step35 session with budget >= gs_min died with "graph promote
                // failed" instead of decoding eagerly. Named exclusion; the dc gap itself
                // stays a named refusal in decode.rs.
                if s.graph.is_none() && s.spec.is_none() && s.sampler.is_greedy()
                    && !eager_only.contains(&s.model)
                    && loaded[&s.model].model.cfg.step35.is_none()
                    && constr_graph_ok
                    && s.lane == crate::lanes::Lane::Interactive
                    && s.budget >= gs_min
                    && s.prefill_done && s.generated.is_empty() && s.cache.is_some()
                    && !s.last_logits.is_empty()
                {
                    let lm = &loaded[&s.model];
                    // first generated token: MASKED argmax for constrained sessions (the
                    // grammar's initial state), plain argmax otherwise.
                    let (first, mask0) = match s.constraint.as_mut() {
                        Some(c) => match c.compute_mask() {
                            Ok(m) => {
                                let mut row = s.last_logits.clone();
                                crate::constrained::apply_mask(&m, &mut row);
                                (memra_engine::forward::argmax(&row) as u32, Some(m))
                            }
                            Err(err) => {
                                let _ = s.tx.send(Event::Error(EngineError::engine(format!("constraint mask: {err}"))));
                                finished.push(0);
                                (0, None)
                            }
                        },
                        None => (memra_engine::forward::argmax(&s.last_logits) as u32, None),
                    };
                    if !finished.contains(&0) {
                    let cache = s.cache.take().unwrap();
                    match lm.model.graph_session_from_cache_masked(
                        &engine, cache, first, s.budget + 2,
                        mask0.as_ref().map(|m| m.as_slice())) {
                        Ok((g, first)) => {
                            s.graph = Some(g);
                            s.graph_pending = Some(first);
                        }
                        Err(err) => {
                            // capture failed with the cache consumed — degrade the session
                            // via the graph-less error path (rare: capture-time errors only).
                            let _ = s.tx.send(Event::Error(EngineError::engine(format!("graph promote failed: {err}"))));
                            finished.push(0);
                        }
                    }
                    }
                }
                // step the (possibly just-promoted) graph session: one token per tick
                let s = &mut active[0];
                if let Some(pend) = s.graph_pending.take() {
                    let t_g = Instant::now();
                    let (cont, _) = advance_token_emit(&loaded, s, pend);
                    if !cont {
                        finished.push(0);
                    } else {
                        s.fed.push(pend);
                        // CONSTRAINED: fresh post-consume mask into the graph's stable
                        // buffer before the replay (the KV-pointer update pattern).
                        let mut mask_err = None;
                        if let Some(c) = s.constraint.as_mut() {
                            match c.compute_mask() {
                                Ok(m) => {
                                    if let Err(err) = s.graph.as_mut().unwrap()
                                        .upload_mask(&engine, m.as_slice()) {
                                        mask_err = Some(err.to_string());
                                    }
                                }
                                Err(err) => mask_err = Some(err),
                            }
                        }
                        if let Some(err) = mask_err {
                            let _ = s.tx.send(Event::Error(EngineError::engine(format!("constraint mask: {err}"))));
                            finished.push(0);
                        } else {
                        let lm = &loaded[&s.model];
                        // Q2 (audit 2026-08-05): step() errors for REAL causes (recapture
                        // OOM at a kernel-class boundary, fa exec-update failure) besides
                        // budget exhaustion — those must surface as errors, never as a
                        // clean MaxNew. Budget exhaustion (the one benign cause, checked
                        // here against the same bound step() uses) keeps the honest MaxNew.
                        let at_budget = s.graph.as_ref()
                            .is_some_and(|g| g.cache.pos + 1 >= g.bucket_max);
                        let g = s.graph.as_mut().unwrap();
                        match g.step(&engine, &lm.model) {
                            Ok(next) => { s.graph_pending = Some(next); }
                            Err(err) if at_budget => {
                                eprintln!("[worker] graph session capture budget reached \
                                           (model {}): {err}", s.model);
                                finish(s, StopReason::MaxNew);
                                finished.push(0);
                            }
                            Err(err) => {
                                eprintln!("[worker] graph session step FAILED \
                                           (model {}): {err}", s.model);
                                let _ = s.tx.send(Event::Error(
                                    EngineError::engine(format!("graph step failed: {err}"))));
                                finished.push(0);
                            }
                        }
                        n_tokens_out += 1;
                        lane_tokens[0] += 1;
                        step_stats.record(t_g.elapsed().as_secs_f32() * 1000.0);
                        last_interactive_decode = Instant::now();
                        }
                    }
                }
            }
            // (a-) SPEC DEMOTION (lane/spec-gate, task #89, 2026-08-07). The admit gate above
            // keeps NEW arrivals off the serial spec queue, but sessions admitted while the box
            // was quiet keep bursting after load arrives — and each one holds a whole burst of
            // the tick (~21 ms at B=32/K=3) that the batched rows wait behind. So a live spec
            // session hands its cache to the batched path once the active count reaches T_HIGH.
            //
            // EXACTNESS (the non-negotiable bar). At a burst boundary the session invariant is
            // `cache.pos == committed.len()` — every committed row's trunk KV/recurrent state is
            // exactly what a plain prime of that token sequence would have produced — and
            // `next_pred` is the argmax of the verify's logits for the last committed row, which
            // is bit-identical to plain decode's logits there (that identity IS the greedy accept
            // walk's basis). Handing (cache, next_pred) over therefore continues the stream from
            // a state the batched path cannot distinguish from one it produced itself:
            // `device_next` makes the next batched tick emit `next_pred` and feed it into this
            // same cache, exactly as `advance_sample_emit` does for any batched row. See
            // `SpecSession::into_demoted`.
            //
            // A carried pending (the default partial-accept tail) must COMMIT first — its bonus
            // row is emitted but deliberately absent from the cache, and handing over a cache
            // that is one row short of the emitted stream would silently drop a token.
            // `spec_flush_pending` is that commit, and it is byte-identical to the pre-carry
            // tail. It costs one T=1 trunk pass, once per demotion (never per burst).
            //
            // WHO IS EXCLUDED, and why (stated, not hidden):
            //   * SAMPLED sessions — `next_pred` on the sampled tail is the commit pass's ARGMAX,
            //     so handing it over would inject a greedy token into a sampled stream. The
            //     sampled tail keeps no logits row to draw from, and adding a per-burst
            //     [n_vocab] D2H (1.36 ms at the 9B's 248k vocab) to enable a rare handoff is the
            //     wrong trade. Sampled spec sessions stay on spec until they end.
            //   * CONSTRAINED sessions — `next_pred` is the UNMASKED verify argmax; emitting it
            //     could produce a grammar-illegal token.
            // Both residuals are BOUNDED by the admit gate: at most `spec_gate_low()` sessions
            // can be on the spec path at any time, so the worst case is that many serial bursts,
            // not a full concurrency ladder's worth.
            //
            // ONE-WAY BY DESIGN (v1). Demotion drops the MTP draft scratch and the persistent
            // draft-graph context; re-promoting on drain-down would mean an `mtp_kv_fill` over
            // the whole committed history plus a fresh graph capture, i.e. NOT the "symmetric and
            // cheap" handoff the re-promotion option was conditioned on. A demoted session stays
            // demoted until it ends. New arrivals get spec again the moment the count falls back
            // to T_LOW, so the policy still tracks a draining load — per REQUEST, not per session.
            //
            // TESTABILITY (`MEMRA_SPEC_DEMOTE_AT`, diagnostics-only). Load-triggered demotion can
            // never be a clean exactness test: the trigger needs concurrent sessions, and a loaded
            // batch is not bit-identical to a solo one (measured pre-existing property — batch-vs-
            // solo decode diverges on its own with spec OFF and this gate absent, because
            // `fa_decode_batch_seqs_v4` carries one `split_keys` for rows at different depths and
            // the batched-linear tier changes with B). Both the arrival timing and the batch
            // composition are then nondeterministic, so a diff cannot attribute a divergence to
            // the HANDOFF. This door forces the demotion at a fixed generated-token count with NO
            // load at all, holding B=1 across the boundary: the only difference from a plain
            // batched run is that the first N tokens came off the spec path. That isolates exactly
            // the property this lane must prove. Never set in production.
            let demote_at: Option<usize> = {
                static D: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
                *D.get_or_init(|| std::env::var("MEMRA_SPEC_DEMOTE_AT").ok()
                    .and_then(|v| v.parse().ok()))
            };
            let automatic_demote = spec_k_pin().is_none() && spec_gate_on();
            if automatic_demote || demote_at.is_some() {
                let n_live = active.len() - finished.len();
                let forced = demote_at.is_some_and(|n| {
                    active.iter().enumerate().any(|(i, s)| {
                        !finished.contains(&i) && s.spec.is_some() && s.generated.len() >= n
                    })
                });
                if n_live >= spec_gate_high() || forced {
                    for i in 0..active.len() {
                        if finished.contains(&i) { continue; }
                        let s = &mut active[i];
                        if s.spec.is_none() { continue; }
                        // exclusions above: sampled + constrained keep the spec path.
                        if !s.sampler.is_greedy() || s.constraint.is_some() { continue; }
                        // forced mode (test door): only the session past the pinned token count,
                        // and only it — a peer still short of N keeps bursting.
                        if let Some(n) = demote_at {
                            if s.generated.len() < n { continue; }
                        } else if n_live < spec_gate_high() {
                            continue;
                        }
                        // a session that has not bursted yet has no cache state to hand over
                        // (its prompt is still queued as the spec turn-1 suffix) — it stays on
                        // spec for this tick and demotes at its next boundary.
                        let sess = s.spec.as_ref().unwrap();
                        if sess.committed_len() == 0
                            || (!sess.demote_ready() && !sess.has_pending()) { continue; }
                        let mut sess = s.spec.take().unwrap();
                        let lm = &loaded[&s.model];
                        if sess.has_pending() {
                            if let Err(err) = lm.model.spec_flush_pending(&engine, &mut sess) {
                                // UNRECOVERABLE, and said so honestly: the flush consumed the
                                // pending before failing, so the session holds neither a pending
                                // nor a next_pred — its next continuation burst would trip the
                                // engine's primed-session assertion. Retire with the quoted cause
                                // rather than hand back a session that cannot burst.
                                eprintln!("[spec-gate] demote flush FAILED (model {}): {err}",
                                          s.model);
                                let _ = s.tx.send(Event::Error(EngineError::engine(format!(
                                    "spec demote flush failed: {err}"))));
                                finished.push(i);
                                continue;
                            }
                        }
                        // Re-check the handoff shape BEFORE consuming the session:
                        // `into_demoted` takes `self`, so a None there would drop the caches of
                        // a live request. Should be unreachable (flush clears pending and sets
                        // next_pred) — loud no-op, session handed straight back.
                        if !sess.demote_ready() {
                            eprintln!("[spec-gate] demote SKIPPED: session not in handoff shape \
                                       after flush (model {}); staying on spec", s.model);
                            s.spec = Some(sess);
                            continue;
                        }
                        let committed = sess.committed_len();
                        let Some((cache, next)) = sess.into_demoted() else { continue };
                        debug_assert_eq!(cache.pos, s.fed.len(),
                            "demote handoff: cache rows != fed tokens");
                        s.cache = Some(cache);
                        s.device_next = Some(next);
                        s.spec_k = 0;
                        s.prefill_done = true;
                        s.last_logits.clear();
                        n_demoted += 1;
                        let why = match demote_at {
                            Some(n) => format!("FORCED at DEMOTE_AT={n} (test door)"),
                            None => format!("{n_live} active >= HIGH={}", spec_gate_high()),
                        };
                        eprintln!("[spec-gate] demoted session to batched decode: {why} \
                                   (model {}, committed {committed}, generated {})",
                                  s.model, s.generated.len());
                    }
                }
            }
            // (a) spec bursts — COLD-FIRST (admission-latency, 2026-08-06): a session that
            // has emitted nothing yet (fresh admit / pool resume, `generated` is per-request)
            // bursts BEFORE any mid-generation peer. Without this, the admission yield only
            // moved the wait: the newcomer admitted at tick top, then the background session
            // (lower index) ran its whole NEXT B128 burst (~1.2s) before the newcomer's
            // prime ever flushed (first-result.log: fix-on 1.30s vs fix-off 1.61s — the
            // residual IS that peer burst). With it: 0.149s median (iter1 receipt). Stable
            // sort: FIFO within cold and warm classes; session order across independent
            // sessions is content-neutral (each owns its cache/scratch — greedy byte-identity
            // gates verify). Shares the MEMRA_ADMIT_YIELD=0 rollback seam: off restores the
            // full pre-lane behavior (index order + full-burst holds) in one flag.
            // BATCHDRAFT ANATOMY (diagnostics only): the original tick trace started below,
            // after this loop, so its `decode_ms` omitted the entire serial spec phase. Start a
            // phase clock here and emit one boundary record per request. This adds no sync and is
            // cold unless MEMRA_TICK_TRACE=1; MEMRA_SPEC_PHASE=1 supplies the inner round split.
            let tick_trace = tick_trace_enabled();
            let t_spec = tick_trace.then(Instant::now);
            let mut spec_calls = 0usize;
            let mut spec_prev_end_ms = 0.0f32;
            let mut spec_order: Vec<usize> = (0..active.len())
                .filter(|&i| active[i].spec.is_some())
                .collect();
            let admit_yield_on = {
                static Y: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
                *Y.get_or_init(|| std::env::var("MEMRA_ADMIT_YIELD").as_deref() != Ok("0"))
            };
            if admit_yield_on {
                spec_order.sort_by_key(|&i| !active[i].generated.is_empty());
            }
            let mut spec_order = spec_order.into_iter().peekable();
            while let Some(i) = spec_order.next() {
                if finished.contains(&i) { continue; }
                let pair = spec_order.peek().copied().filter(|&j| {
                    !finished.contains(&j)
                        && spec_pipe_pairable(&engine, &loaded, &active[i], &active[j])
                });
                if let Some(j) = pair {
                    let _ = spec_order.next();
                    let generated_i = active[i].generated.len();
                    let generated_j = active[j].generated.len();
                    let lane_i = active[i].lane;
                    let lane_j = active[j].lane;
                    let rounds_i = active[i].spec_rounds;
                    let rounds_j = active[j].spec_rounds;
                    let pair_started = Instant::now();
                    let step_result = if i < j {
                        let (left, right) = active.split_at_mut(j);
                        step_spec_pair(
                            &engine, &loaded, &mut left[i], &mut right[0], &mut spec_telem,
                        )
                    } else {
                        let (left, right) = active.split_at_mut(i);
                        step_spec_pair(
                            &engine, &loaded, &mut right[0], &mut left[j], &mut spec_telem,
                        )
                    };
                    let pair_ms = pair_started.elapsed().as_secs_f32() * 1000.0;
                    record_output_progress(
                        generated_i,
                        active[i].generated.len(),
                        lane_i,
                        pair_ms,
                        &mut n_tokens_out,
                        &mut lane_tokens,
                        &mut step_stats,
                        &mut last_interactive_decode,
                    );
                    record_output_progress(
                        generated_j,
                        active[j].generated.len(),
                        lane_j,
                        pair_ms,
                        &mut n_tokens_out,
                        &mut lane_tokens,
                        &mut step_stats,
                        &mut last_interactive_decode,
                    );
                    if tick_trace {
                        spec_calls += 2;
                        let end_ms = t_spec.unwrap().elapsed().as_secs_f32() * 1000.0;
                        eprintln!(
                            "[tick-spec-pipe] seq={}-{} slots={i},{j} gap_ms={:.3} wall_ms={pair_ms:.3} \
                             generated={generated_i}->{},{}->{} rounds={},{}",
                            spec_calls - 1,
                            spec_calls,
                            end_ms - pair_ms - spec_prev_end_ms,
                            active[i].generated.len(),
                            generated_j,
                            active[j].generated.len(),
                            active[i].spec_rounds.saturating_sub(rounds_i),
                            active[j].spec_rounds.saturating_sub(rounds_j),
                        );
                        spec_prev_end_ms = end_ms;
                    }
                    match step_result {
                        Ok((keep_i, keep_j)) => {
                            if !keep_i { finished.push(i); }
                            if !keep_j { finished.push(j); }
                        }
                        Err(err) => {
                            let message = format!("step error: {err}");
                            let _ = active[i].tx.send(Event::Error(EngineError::engine(message.clone())));
                            let _ = active[j].tx.send(Event::Error(EngineError::engine(message)));
                            finished.push(i);
                            finished.push(j);
                        }
                    }
                    continue;
                }
                let generated_before = active[i].generated.len();
                let lane = active[i].lane;
                let step_started = Instant::now();
                let trace_before = t_spec.map(|phase_start| {
                    (
                        phase_start.elapsed().as_secs_f32() * 1000.0,
                        active[i].generated.len(),
                        active[i].spec_rounds,
                        active[i].spec_drafted,
                        active[i].spec_accepted,
                        active[i].spec_k,
                        active[i].trace_id.clone().unwrap_or_else(|| "-".into()),
                        Instant::now(),
                    )
                });
                let step_result = step_session(&engine, &loaded, &mut active[i], &mut spec_telem);
                let step_elapsed_ms = step_started.elapsed().as_secs_f32() * 1000.0;
                if let Some((start_ms, generated0, rounds0, drafted0, accepted0, k, trace_id,
                             call_start)) = trace_before
                {
                    let end_ms = t_spec.unwrap().elapsed().as_secs_f32() * 1000.0;
                    spec_calls += 1;
                    eprintln!(
                        "[tick-spec] seq={} slot={i} trace={} start_ms={start_ms:.3} \
                         gap_ms={:.3} wall_ms={:.3} generated={generated0}->{} rounds={} \
                         drafted={} accepted={} k={k}",
                        spec_calls,
                        trace_id,
                        start_ms - spec_prev_end_ms,
                        call_start.elapsed().as_secs_f32() * 1000.0,
                        active[i].generated.len(),
                        active[i].spec_rounds.saturating_sub(rounds0),
                        active[i].spec_drafted.saturating_sub(drafted0),
                        active[i].spec_accepted.saturating_sub(accepted0),
                    );
                    spec_prev_end_ms = end_ms;
                }
                record_output_progress(
                    generated_before,
                    active[i].generated.len(),
                    lane,
                    step_elapsed_ms,
                    &mut n_tokens_out,
                    &mut lane_tokens,
                    &mut step_stats,
                    &mut last_interactive_decode,
                );
                match step_result {
                    Ok(true) => {}
                    Ok(false) => finished.push(i),
                    // STEP-OOM PARK-NOT-KILL (lane/admit-oom, 2026-08-06). A step that OOMs
                    // on a card-full condition used to kill the stream outright, and at c=64
                    // that killed ALL 64 in one tick sweep (research/serving-density-20260806
                    // §Q2: 0/64 well-formed). The honest admission gate above makes this rare
                    // — it is now the TRANSIENT-COLLISION backstop, for the case where two
                    // sessions' capture arenas land in the same tick despite the reserve.
                    //
                    // The session PARKS: its caches drop (freeing exactly the VRAM the retry
                    // needs) and the REQUEST goes back to the admission queue, where the
                    // reserve-floor gate holds it until a retire frees room — the same
                    // FIFO-wait every over-cap request already takes. Bounded by
                    // step_oom_retries() before the honest error, so a genuine capacity
                    // failure still surfaces instead of looping forever.
                    //
                    // WHAT PARKING COSTS, stated honestly: the session's committed KV is
                    // discarded, so the retry RE-PRIMES its prompt from scratch. That is
                    // pure latency, never a correctness change — a re-primed session emits
                    // exactly what a cold one would (the same property the F5 right-size
                    // ladder relies on). Tokens already streamed to the client are NOT
                    // re-sent: `park_requeue` rebuilds the request with the prompt only, and
                    // a session that has already emitted cannot be silently restarted, so it
                    // takes the honest error instead. Only pre-emission sessions park.
                    Err(err) if is_cuda_oom(&err.to_string())
                        && step_oom_retries() > 0
                        && active[i].generated.is_empty()
                        && active[i].oom_retries < step_oom_retries() =>
                    {
                        let n_active = active.len();
                        let s = &mut active[i];
                        s.oom_retries += 1;
                        eprintln!("[admit-oom] step OOM parked session back to queue \
                                   (model {}, retry {}/{}, {n_active} active): {err}",
                                  s.model, s.oom_retries, step_oom_retries());
                        match park_requeue(&loaded, s) {
                            Some(req) => {
                                n_step_oom_parks += 1;
                                requeue_oom.push_back(req);
                                finished.push(i);
                            }
                            None => {
                                // cannot rebuild the request (no prompt to replay) — the
                                // pre-fix honest error, quoted.
                                let _ = s.tx.send(Event::Error(EngineError::engine(format!("step error: {err}"))));
                                finished.push(i);
                            }
                        }
                    }
                    Err(err) => {
                        if is_cuda_oom(&err.to_string()) {
                            eprintln!("[admit-oom] step OOM NOT parked (model {}, retries \
                                       {}/{}, generated {}): reporting honestly",
                                      active[i].model, active[i].oom_retries,
                                      step_oom_retries(), active[i].generated.len());
                        }
                        let _ = active[i].tx.send(Event::Error(EngineError::engine(format!("step error: {err}"))));
                        finished.push(i);
                    }
                }
            }
            // Freeze this before prefill/decode work; the summary must describe phase (a),
            // not elapsed time from phase (a)'s start to the end of the whole scheduler tick.
            let spec_ms = t_spec
                .map(|started| started.elapsed().as_secs_f32() * 1000.0)
                .unwrap_or(0.0);
            // (b) INTERACTIVE prefill only (TTFT priority, full tick chunk budgets[0]).
            // Dark-lane (judge/harvest) prefill runs AFTER decode (phase d) so a judge
            // prime can never sit between an interactive stream and its next token (the
            // 282ms-p99 lesson, 2026-07-26 native-judge battery).
            // task #13 (2026-07-26): BATCH fresh short primes across sessions —
            // one concat trunk, GEMMs at m = sum_T. Measured regime (prime-batch-gate --bench):
            // +80% at B=8 T=64, +44-49% at T=128, crossover ~T=320 (above it, single primes
            // win — per-seq m already at the GEMM plateau). Gate: prime-batch-gate ALL GREEN
            // (per-seq argmax + decode-stream equality). MEMRA_PRIME_BATCH=1 disables.
            let t_prefill = tick_trace.then(Instant::now);
            let mut prefill_single_calls = 0usize;
            let mut prefill_single_tokens = 0usize;
            let mut prefill_batch_calls = 0usize;
            let mut prefill_batch_tokens = 0usize;
            let budgets = policy.prefill_budget;
            let pb_hold_ms: u64 = std::env::var("MEMRA_PRIME_BATCH_HOLD_MS").ok()
                .and_then(|v| v.parse().ok()).unwrap_or(4);
            let dedup_advanced = dedup_interactive_prefixes(
                &engine,
                &loaded,
                &eager_only,
                &mut px,
                &mut active,
                &mut finished,
                budgets[0],
                &mut n_cached_in,
                &mut ns_tokens,
            );
            // An unrelated cold request must not release a just-arrived singleton from the
            // existing batch-formation window before its same-prefix siblings reach the
            // worker. Matching groups above fire immediately; unmatched misses wait at most
            // the same hold already budgeted for a lone fresh prime.
            let dedup_waiting: std::collections::HashSet<usize> =
                if prefix_dedup_enabled() && !confidence_trace_enabled() && pb_hold_ms > 0 {
                    active.iter().enumerate()
                        .filter(|(i, s)| {
                            !finished.contains(i)
                                && prefix_fanout_eligible(s, &eager_only)
                                && s.t0.elapsed().as_millis() < pb_hold_ms as u128
                        })
                        .map(|(i, _)| i)
                        .collect()
                } else {
                    Default::default()
                };
            let (cand, held) = 'pb: loop {
                // default 6 (2026-07-26): with the varlen GDN core (task #18) the
                // concat sweet spot moved from B=4 to B=6-8 (16501 vs 15950 tok/s
                // at T=152 — the per-seq core train no longer scales with B).
                let pb_max: usize = std::env::var("MEMRA_PRIME_BATCH").ok()
                    .and_then(|v| v.parse().ok()).unwrap_or(6);
                // 320 -> 2048 (2026-07-27): the old T=320 crossover ("above it, single
                // primes win") was measured on the per-seq core train. With the wgmma
                // varlen cores (task #22 vl twins) batched wins at EVERY tested T:
                // +30.1% at T=320, +12.6% at 512, +5.9% at 937, +3.0% at 1536
                // (prime-batch-gate --bench, B=3). budgets[0] still caps per-tick load.
                let pb_maxt: usize = std::env::var("MEMRA_PRIME_BATCH_MAX_T").ok()
                    .and_then(|v| v.parse().ok()).unwrap_or(2048);
                let min_t = memra_engine::hybrid_forward::PRIME_MIN_T.max(2);
                let mut cand: Vec<usize> = Vec::new();
                let mut cand_model: Option<String> = None;
                if pb_max >= 2 && !confidence_trace_enabled() {
                    for i in 0..active.len() {
                        if finished.contains(&i) { continue; }
                        if dedup_waiting.contains(&i) { continue; }
                        let s = &active[i];
                        let ql = s.prefill_queue.len();
                        if s.spec.is_none() && !s.prefill_done && s.graph.is_none()
                            && s.lane == crate::lanes::Lane::Interactive
                            && s.fed.is_empty()
                            && s.cache.as_ref().is_some_and(|c| c.pos == 0)
                            // eager-only models have no batched prime core (engine refuses)
                            && !eager_only.contains(&s.model)
                            // prefix-cache LCP split primes alone (the boundary snapshot
                            // needs a per-session stop inside the prompt; concat can't stop).
                            && s.snapshot_at.is_none()
                            // plain-affinity checkpoint capture needs the same per-session
                            // boundary stop the concat prime cannot honor — prime alone.
                            && s.ckpt_at.is_none()
                            && ql >= min_t && ql <= pb_maxt && ql <= budgets[0]
                            && cand_model.as_ref().is_none_or(|m| *m == s.model)
                        {
                            cand_model.get_or_insert_with(|| s.model.clone());
                            cand.push(i);
                            if cand.len() == pb_max { break; }
                        }
                    }
                }
                // BATCH-FORMATION HOLD: a lone fresh candidate that arrived <hold_ms ago is
                // deferred (skipped by the single-prime loop below via the same predicate NOT
                // firing — it stays queued) so staggered arrivals can coalesce. Telemetry
                // 2026-07-26: without the hold only 25% of a 32-concurrent burst batched
                // (ticks ~1ms, arrivals staggered). TTFT cost <= hold_ms on a ~40ms prime.
                let mut held = false;
                if cand.len() == 1 && pb_hold_ms > 0 {
                    let s = &active[cand[0]];
                    if s.t0.elapsed().as_millis() < pb_hold_ms as u128 {
                        held = true;
                    }
                }
                let mut fired = false;
                if cand.len() >= 2 {
                    for &i in &cand {
                        if let Some(trace) = active[i].ttft.as_ref() {
                            trace.mark_prime_start();
                        }
                    }
                    let prompts: Vec<Vec<u32>> = cand.iter()
                        .map(|&i| active[i].prefill_queue.drain(..).collect())
                        .collect();
                    let prompt_refs: Vec<&[u32]> = prompts.iter().map(|p| p.as_slice()).collect();
                    let mut cache_refs: Vec<&mut memra_engine::cache::Cache> = active.iter_mut()
                        .enumerate()
                        .filter(|(i, _)| cand.contains(i))
                        .map(|(_, s)| s.cache.as_mut().unwrap())
                        .collect();
                    let lm = &loaded[cand_model.as_ref().unwrap()];
                    let t_pb = Instant::now();
                    match lm.model.prime_cache_batch(&engine, &prompt_refs, &mut cache_refs) {
                        Ok(outs) => {
                            let toks: usize = prompts.iter().map(|p| p.len()).sum();
                            prefill_batch_calls += 1;
                            prefill_batch_tokens += toks;
                            eprintln!("[prime-batch] B={} tokens={} in {:.1}ms",
                                      cand.len(), toks, t_pb.elapsed().as_secs_f64() * 1e3);
                            for ((&i, prompt), (l, _h, _x)) in
                                cand.iter().zip(&prompts).zip(outs)
                            {
                                let s = &mut active[i];
                                s.last_logits = l;
                                for &tok in prompt { s.fed.push(tok); s.sampler.accept(tok); }
                                s.prefill_done = true;
                                if let Some(trace) = s.ttft.as_ref() {
                                    trace.mark_prime_end();
                                }
                                // prefix-cache seed: batch-primed bytes are the concat
                                // config — the entry stores whatever config ran (contract).
                                maybe_prefix_seed(&engine, &mut px, s);
                            }
                            fired = true;
                        }
                        Err(err) => {
                            // fall back: restore queues, the per-session path serves this tick
                            eprintln!("[prime-batch] failed ({err}); single primes serve");
                            for (&i, prompt) in cand.iter().zip(&prompts) {
                                active[i].prefill_queue = prompt.iter().copied().collect();
                            }
                        }
                    }
                }
                // ROUNDS (telemetry 2026-07-26: a tick with 8 pending batched 4 and
                // single-primed the rest): keep batching while >= 2 candidates remain.
                if fired { continue 'pb; }
                break 'pb (cand, held);
            };
            let sole_unfinished = queue.is_empty()
                && requeue_oom.is_empty()
                && active.iter().enumerate()
                    .filter(|(i, _)| !finished.contains(i))
                    .count() == 1;
            for i in 0..active.len() {
                if finished.contains(&i) { continue; }
                if dedup_advanced.contains(&i) { continue; }
                if dedup_waiting.contains(&i) { continue; }
                if held && cand.first() == Some(&i) { continue; }   // batch-formation hold
                let s = &mut active[i];
                if s.spec.is_some() || s.prefill_done { continue; }
                if s.lane != crate::lanes::Lane::Interactive { continue; }
                let fresh = s.fed.is_empty()
                    && s.cache.as_ref().is_some_and(|c| c.pos == 0)
                    && s.snapshot_at.is_none()
                    && s.ckpt_at.is_none();
                let budget = interactive_prefill_budget(
                    budgets[0],
                    prefill_tick_explicit,
                    sole_unfinished,
                    fresh,
                    s.prefill_queue.len(),
                );
                match prefill_tick(&engine, &loaded, &mut px, s, budget) {
                    Ok(consumed) => {
                        if consumed > 0 {
                            prefill_single_calls += 1;
                            prefill_single_tokens += consumed;
                        }
                    }
                    Err(err) => {
                        let _ = s.tx.send(Event::Error(EngineError::engine(format!("prefill error: {err}"))));
                        finished.push(i);
                    }
                }
            }
            let prefill_ms = t_prefill
                .map(|started| started.elapsed().as_secs_f32() * 1000.0)
                .unwrap_or(0.0);
            // (c) batched decode, interactive rows first (stable sort by lane index: chunks
            // fill with protected-class rows before dark rows).
            let t_decode = Instant::now();
            // (c-) EAGER-ONLY per-session decode (lane/gemma4-serve-gaps, 2026-08-07):
            // models with no batched decode arm advance through step_session — the legacy
            // round-robin body, whose decode_step routes to the supported eager arm
            // (gemma4_decode_step_h) — INSIDE the batched scheduler, one token per tick per
            // session. Before this route, these sessions entered the batched chunks below
            // and decode_step_batch's gemma4 assert KILLED THE WORKER on the first request
            // (research/gemma4-serve-20260807/raw/repro-panic-server-*.log). They are
            // excluded from the batched chunks by the `decoding` filter beneath.
            for i in 0..active.len() {
                if finished.contains(&i) { continue; }
                if !eager_only.contains(&active[i].model) { continue; }
                if active[i].spec.is_some() || !active[i].prefill_done
                    || active[i].cache.is_none() { continue; }
                let was_interactive = active[i].lane == crate::lanes::Lane::Interactive;
                match step_session(&engine, &loaded, &mut active[i], &mut spec_telem) {
                    Ok(true) => {
                        // prefill_done rows: Ok(true) == one token emitted (decode phase).
                        n_tokens_out += 1;
                        lane_tokens[active[i].lane.idx()] += 1;
                        if was_interactive { last_interactive_decode = Instant::now(); }
                    }
                    Ok(false) => finished.push(i),
                    Err(err) => {
                        let _ = active[i].tx.send(Event::Error(
                            EngineError::engine(format!("step error: {err}"))));
                        finished.push(i);
                    }
                }
            }
            let mut decoding: Vec<usize> = (0..active.len())
                .filter(|&i| !finished.contains(&i)
                        && active[i].spec.is_none() && active[i].prefill_done
                        && active[i].cache.is_some()
                        && !eager_only.contains(&active[i].model))
                .collect();
            decoding.sort_by_key(|&i| active[i].lane.idx());
            let mut had_interactive = false;
            // sample + emit + stop checks (host); survivors carry their next token
            let mut ready: Vec<(usize, u32)> = Vec::new();
            for &i in &decoding {
                let (cont, next) = advance_sample_emit(&loaded, &mut active[i]);
                match (cont, next) {
                    (false, _) => finished.push(i),
                    (true, Some(t)) => {
                        // GRAMMAR MASK STAGING (constrained-full): compute the post-consume
                        // token mask and H2D the packed bitset into the session's stable
                        // device buffer — the batched step bans on device BEFORE its device
                        // sampler, so this row rides the same lean tick as everyone else.
                        if let Err(err) = stage_grammar_mask(&engine, &mut active[i]) {
                            let _ = active[i].tx.send(Event::Error(
                                EngineError::engine(format!("constraint mask: {err}"))));
                            finished.push(i);
                            continue;
                        }
                        had_interactive |= active[i].lane == crate::lanes::Lane::Interactive;
                        ready.push((i, t));
                    }
                    (true, None) => {} // nothing to do this tick
                }
            }
            // batched steps in per-model chunks (chunk_cap_for: exact-16 tier models chunk
            // at 16, everything else 8; MEMRA_DECODE_BATCH_CAP is the explicit door).
            // D2H audit (inc3 3c): the per-chunk [B]-u32 device-token readback inside the
            // step is the tick's ONLY steady-state D2H — one per chunk, none per seq. A
            // deferred one-per-TICK variant measured FLAT (±0.7%, N=4, c=8/16/32, 5090 —
            // research/batched-tick-inc3-20260801) and was killed per the flags doctrine.
            for chunk in group_chunks(&active, &ready, &chunk_caps) {
                let toks: Vec<u32> = chunk.iter().map(|&(_, t)| t).collect();
                let idxs: Vec<usize> = chunk.iter().map(|&(i, _)| i).collect();
                let model_name = active[idxs[0]].model.clone();
                let lm = &loaded[&model_name];
                // DEVICE-SIDE SAMPLING metas (MEMRA_SERVE_DEVSAMPLE=0 reverts to host): rows
                // whose sampler is greedy-no-penalties (device argmax, bit-identical) or
                // pure-temperature (seeded gumbel draw — top-k/top-p/min-p/penalty configs
                // keep the host path) sample on device inside the batched step; the next
                // tick's advance_sample_emit consumes the token instead of the O(n_vocab)
                // host sample. Counter = generated.len() — a session-progress function,
                // independent of batch composition (the isolation contract, gate3).
                let samp: Vec<Option<(f32, u64, u32)>> = idxs
                    .iter()
                    .map(|&i| {
                        let s = &active[i];
                        // constrained rows: device-sample iff a mask was staged this tick
                        // (fallback sampler configs / MEMRA_CONSTRAIN_HOST keep the v1
                        // host masked-copy sample — mask_words stays 0 for them).
                        if s.constraint.is_some() && s.mask_words == 0 {
                            return None;
                        }
                        devsample_meta(s)
                    })
                    .collect();
                // GRAMMAR MASKS: staged rows pass (stable device buffer, word count). Raw
                // pointers here because the caches split-borrow below takes as_mut_ptr on
                // `active` — the fields are disjoint (mask_dev vs cache), same soundness
                // class as the existing unique-index split-borrow.
                let mask_ptrs: Vec<Option<(*const CudaSlice<u32>, usize)>> = idxs
                    .iter()
                    .map(|&i| {
                        let s = &active[i];
                        if s.mask_words > 0 {
                            s.mask_dev.as_ref().map(|d| (d as *const _, s.mask_words))
                        } else {
                            None
                        }
                    })
                    .collect();
                let logits = {
                    // split-borrow: pull the caches out via split_at_mut-style indexing
                    let mut caches: Vec<&mut Cache> = Vec::with_capacity(idxs.len());
                    // SAFETY: idxs are unique indices into `active`; we take disjoint &mut.
                    let base = active.as_mut_ptr();
                    for &i in &idxs {
                        let s = unsafe { &mut *base.add(i) };
                        caches.push(s.cache.as_mut().unwrap());
                    }
                    // LEAN LOGITS (inc2 component 3): device-sampled rows skip the
                    // [n_vocab] D2H — their last_logits comes back EMPTY and the row is
                    // parked on-device (cache.last_logits_dev) for the retire-time pool
                    // park below. MEMRA_SERVE_LEANLOGITS=0 restores the full D2H.
                    // SAFETY: mask_ptrs point at Session.mask_dev fields — disjoint from
                    // the caches taken above; nothing mutates them for this call's life.
                    let masks: Vec<Option<(&CudaSlice<u32>, usize)>> = mask_ptrs
                        .iter()
                        .map(|m| m.map(|(p, w)| (unsafe { &*p }, w)))
                        .collect();
                    lm.model.decode_step_batch_sampled_lean_masked(
                        &engine, &toks, &mut caches, &samp, &masks, serve_leanlogits())
                };
                match logits {
                    Ok((rows, next_toks)) => {
                        for (k, &i) in idxs.iter().enumerate() {
                            active[i].last_logits = rows[k].clone();
                            active[i].device_next = next_toks[k];
                            active[i].fed.push(toks[k]);
                            n_tokens_out += 1;
                            lane_tokens[active[i].lane.idx()] += 1;
                        }
                    }
                    Err(err) => {
                        for &i in &idxs {
                            let _ = active[i].tx.send(Event::Error(EngineError::engine(format!("batch step: {err}"))));
                            finished.push(i);
                        }
                    }
                }
            }
            if had_interactive {
                last_interactive_decode = Instant::now();
            }
            last_batch = ready.len();
            // MEMRA_TICK_TRACE=1: per-tick phase timing to stderr (diagnosis only).
            if tick_trace {
                let n_int = active.iter()
                    .filter(|s| s.lane == crate::lanes::Lane::Interactive).count();
                let n_pref = active.iter().filter(|s| !s.prefill_done).count();
                // `spec` + `demoted` (lane/spec-gate): the policy's own observables — how many
                // rows are on the serial burst path this tick, and the cumulative handoff count
                // (thrash = this climbing per tick instead of per load crossing).
                let n_spec = active.iter().filter(|s| s.spec.is_some()).count();
                eprintln!("[tick] act={} int={} priming={} ready={} spec={} demoted={} \
                           spec_calls={} spec_ms={:.1} \
                           prefill_single_calls={} prefill_single_tokens={} \
                           prefill_batch_calls={} prefill_batch_tokens={} \
                           prefill_ms={:.1} decode_ms={:.1}",
                          active.len(), n_int, n_pref, ready.len(), n_spec, n_demoted,
                          spec_calls, spec_ms,
                          prefill_single_calls, prefill_single_tokens,
                          prefill_batch_calls, prefill_batch_tokens, prefill_ms,
                          t_decode.elapsed().as_secs_f32() * 1000.0);
            }
            // (d) dark-lane prefill, ADAPTIVE: the tick period IS the client TPOT, so dark
            // primes may only consume the SLO headroom decode left over (2026-07-26 yield
            // battery: fixed 256-tok chunks pushed client p99 42 -> 91ms while the
            // decode-only estimator read 44ms). Chunk tokens = headroom_ms x prime rate.
            let decode_ms = t_decode.elapsed().as_secs_f32() * 1000.0;
            let headroom_ms = (policy.slo_p99_ms - decode_ms).max(0.0);
            let prime_tok_per_ms: f32 = std::env::var("MEMRA_PRIME_TOK_PER_MS").ok()
                .and_then(|v| v.parse().ok()).unwrap_or(8.0);
            let adaptive_cap = (headroom_ms * prime_tok_per_ms) as usize;
            // task #17 increment (2026-07-30): CONCAT small FRESH dark prefills — the
            // harvest profile (many short prompts) previously burned one tick per
            // session; a single prime_cache_batch serves them together at m = sum_T,
            // INSIDE the same headroom budget (sum_T <= lane budget AND adaptive cap,
            // so the 282ms-p99 lesson holds: dark work never exceeds the SLO headroom).
            // Same lane + same model only (budget accounting stays per-lane); >= 2
            // candidates, else the single-chunk path below serves as before.
            let mut dark_batched = false;
            {
                let min_t = memra_engine::hybrid_forward::PRIME_MIN_T.max(2);
                let mut dcand: Vec<usize> = Vec::new();
                let mut dmodel: Option<String> = None;
                let mut dlane: Option<usize> = None;
                let mut dsum = 0usize;
                for i in 0..active.len() {
                    if finished.contains(&i) { continue; }
                    let s = &active[i];
                    let li = s.lane.idx();
                    let ql = s.prefill_queue.len();
                    if li == 0 || budgets[li] == 0 { continue; }
                    // FRESH (pos==0, nothing fed) or CONTINUATION (cache primed exactly
                    // through fed): both prime from cache.pos. Carried gemma4 stays
                    // single-chunk (no continuation prime; engine rejects). LCP-split
                    // sessions prime alone (the boundary snapshot needs a per-session
                    // stop inside the prompt; concat can't stop).
                    if s.spec.is_some() || s.prefill_done || s.graph.is_some()
                        || s.snapshot_at.is_some()
                        || s.ckpt_at.is_some()
                        || !s.cache.as_ref().is_some_and(|c| c.pos == s.fed.len()) { continue; }
                    // eager-only models never join a prime batch (no batched prime core —
                    // the engine refuses fresh AND carried since lane/gemma4-serve-gaps).
                    if eager_only.contains(&s.model) { continue; }
                    let cap = budgets[li].min(adaptive_cap);
                    if ql < min_t || dsum + ql > cap { continue; }
                    if dlane.is_some_and(|l| l != li) { continue; }
                    if dmodel.as_ref().is_some_and(|m| *m != s.model) { continue; }
                    dlane.get_or_insert(li);
                    dmodel.get_or_insert_with(|| s.model.clone());
                    dsum += ql;
                    dcand.push(i);
                }
                if dcand.len() >= 2 {
                    let prompts: Vec<Vec<u32>> = dcand.iter()
                        .map(|&i| active[i].prefill_queue.drain(..).collect())
                        .collect();
                    let prompt_refs: Vec<&[u32]> = prompts.iter().map(|p| p.as_slice()).collect();
                    let mut cache_refs: Vec<&mut memra_engine::cache::Cache> = active.iter_mut()
                        .enumerate()
                        .filter(|(i, _)| dcand.contains(i))
                        .map(|(_, s)| s.cache.as_mut().unwrap())
                        .collect();
                    let lm = &loaded[dmodel.as_ref().unwrap()];
                    match lm.model.prime_cache_batch(&engine, &prompt_refs, &mut cache_refs) {
                        Ok(outs) => {
                            let ncar = dcand.iter()
                                .filter(|&&i| !active[i].fed.is_empty()).count();
                            eprintln!("[prime-batch dark] lane={} B={} tokens={dsum} carried={ncar}",
                                      dlane.unwrap(), dcand.len());
                            for ((&i, prompt), (l, _h, _x)) in
                                dcand.iter().zip(&prompts).zip(outs)
                            {
                                let s = &mut active[i];
                                s.last_logits = l;
                                for &tok in prompt { s.fed.push(tok); s.sampler.accept(tok); }
                                s.prefill_done = true;
                            }
                        }
                        Err(err) => {
                            eprintln!("[prime-batch dark] failed ({err}); chunks serve");
                            for (&i, prompt) in dcand.iter().zip(&prompts) {
                                active[i].prefill_queue = prompt.iter().copied().collect();
                            }
                            dcand.clear();
                        }
                    }
                    dark_batched = !dcand.is_empty(); // the batch WAS this tick's dark action
                }
            }
            for i in 0..active.len() {
                if dark_batched { break; }
                if finished.contains(&i) { continue; }
                let s = &mut active[i];
                if s.spec.is_some() || s.prefill_done { continue; }
                let li = s.lane.idx();
                if li == 0 || budgets[li] == 0 { continue; }
                let chunk = budgets[li].min(adaptive_cap);
                if chunk < memra_engine::hybrid_forward::PRIME_MIN_T { break; }
                if let Err(err) = prefill_tick(&engine, &loaded, &mut px, s, chunk) {
                    let _ = s.tx.send(Event::Error(EngineError::engine(format!("prefill error: {err}"))));
                    finished.push(i);
                }
                break; // one dark chunk per tick — the headroom budget is tick-global
            }
            // Engine-truth interactive TPOT = the FULL client-visible tick (decode + any
            // dark prime). Only interactive-carrying ticks feed the SLO estimator; on
            // naked (all-interactive) traffic this is exactly the pre-gate had_decode.
            if had_interactive {
                step_stats.record(t_decode.elapsed().as_secs_f32() * 1000.0);
            }
        }
        // retire finished sessions (reverse order so indices stay valid). Long-enough sessions
        // park their (fed, cache, last_logits) in the reuse pool instead of dropping the cache.
        finished.sort_unstable();
        finished.dedup();
        for &i in finished.iter().rev() {
            let mut s = active.remove(i);
            retire_prefix_pin(&mut px, &mut s.prefix_pin);
            let pool_key = s.pool_key(); // before the partial moves below (PC-ISO park key)
            n_completed += 1;
            // G5 fault injection (MEMRA_PANIC_AFTER, unset in every real deployment): panic
            // the worker here, with a live CUDA context and the supervisor above us, so the
            // catch_unwind -> mark_dead -> respawn -> exit-70 ladder is proved on the wire and
            // not only against a fake worker in unit tests.
            if panic_injection_due(n_completed) {
                panic!("MEMRA_PANIC_AFTER={} fault injection: \
                        deliberate worker panic after {n_completed} completed request(s)",
                       panic_after().unwrap_or(0));
            }
            lane_completed[s.lane.idx()] += 1;
            if s.spec_rounds > 0 { spec_telem_dirty = true; } // force-publish on spec retire
            if s.spec_drafted > 0 {
                let tenant = crate::auth::meter_key(&s.cache_ns);
                if let Some(event) = adsd_detector.observe(
                    &s.model,
                    tenant,
                    s.spec_accepted as u64,
                    s.spec_drafted as u64,
                ) {
                    eprintln!(
                        "[adsd-suspect] tenant={:?} model={:?} window_acceptance={:.3} \
                         baseline_acceptance={:.3} z={:.2} drafted={} detection_only=true",
                        event.tenant,
                        event.model,
                        event.tenant_rate,
                        event.baseline_rate,
                        event.z_score,
                        event.drafted,
                    );
                }
            }
            if let Some(mut sess) = s.spec {
                // PENDING-CARRY flush before parking: a parked session must be fully committed
                // (committed_text drives the text-prefix resume match — an uncommitted pending
                // would double-feed on resume). One T=1 pass per RETIRED request, not per burst.
                if sess.pending_tok.is_some() {
                    if let Err(err) = loaded[&s.model].model.spec_flush_pending(&engine, &mut sess) {
                        eprintln!("[worker] spec pending flush failed ({err}); dropping session");
                        continue;
                    }
                }
                if sess.committed.len() >= REUSE_MIN_PREFIX && sess.next_pred.is_some() {
                    // skip the leading BOS when rendering: the client's prompt STRING never
                    // contains it (encode() adds it), so it would poison the text-prefix match.
                    let toks = &sess.committed;
                    let skip = loaded[&s.model].tok.bos_id()
                        .map(|b| toks.first() == Some(&b)).unwrap_or(false) as usize;
                    let committed_text = loaded[&s.model].tok.decode_special(&toks[skip..], true);
                    // SESSION AFFINITY: identity of the conversation this session served, so a
                    // later turn that REWRITES history can still recognize and rewind it. The
                    // fingerprint chain is taken over the COMMITTED tokens (no live tail to
                    // drop — a parked session's stream is all history).
                    let tok = &loaded[&s.model].tok;
                    let fingerprint = conversation_fingerprint(
                        toks, &|t| tok.token_is_control(t), false);
                    let pool = spec_reuse.entry(pool_key).or_default();
                    // cap 0 = pooling off: park NOTHING. (Was an unguarded `pool.remove(0)`,
                    // which panicked the worker thread on the first retire at cap 0 — index 0
                    // of an empty vec. Found while wiring the affinity gate's control arm.)
                    while pool.len() >= reuse_pool_per_model().max(1) {
                        pool.remove(0);
                        reuse_metrics.spec_evictions += 1;
                    }
                    if reuse_pool_per_model() > 0 {
                        pool.push(SpecReuseEntry {
                            sess, committed_text, affinity: s.affinity, fingerprint,
                            parked_at: Instant::now(),
                        });
                    }
                }
            } else if s.fed.len() >= REUSE_MIN_PREFIX && s.prefill_done {
                if let Some(cache) = s.cache {
                    // LEAN LOGITS (inc2 component 3): device-sampled sessions carried no
                    // host last_logits — recover the final row from the device park with
                    // ONE D2H here (retire-time, pool-bound sessions only). A session with
                    // neither host nor device logits cannot serve an empty-suffix resume:
                    // skip parking it rather than park a poisoned entry.
                    let last_logits = if s.last_logits.is_empty() {
                        cache.last_logits_dev.as_ref()
                            .and_then(|d| engine.dtoh(d).ok())
                            .unwrap_or_default()
                    } else {
                        s.last_logits
                    };
                    if !last_logits.is_empty() {
                        // PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09): carry the
                        // conversation's identity + rewind checkpoint into the parked entry so a
                        // later rewritten-history turn can recognize it and prime only its delta.
                        // The fingerprint chain is over the COMMITTED (== fed) tokens, no live
                        // tail to drop — a parked session's stream is all history. Only useful
                        // when a checkpoint was captured; entries without one keep the legacy
                        // exact-extension behavior exactly.
                        let tok = &loaded[&s.model].tok;
                        let ckpt = s.ckpt_snap;
                        let affinity = s.affinity;
                        let fingerprint = if ckpt.is_some() {
                            conversation_fingerprint(&s.fed, &|t| tok.token_is_control(t), false)
                        } else {
                            Vec::new()
                        };
                        // H5 (double-park guard, code-audit-20260809 §2.6): a conversation
                        // served by spec on some turns and plain on others must not hold entries
                        // in BOTH pools under one explicit id. When plain-parking with an
                        // explicit affinity id, drop the same-id spec entry first.
                        if let Some(id) = affinity.as_deref() {
                            if let Some(sp) = spec_reuse.get_mut(&pool_key) {
                                let before = sp.len();
                                sp.retain(|e| e.affinity.as_deref() != Some(id));
                                reuse_metrics.spec_evictions += (before - sp.len()) as u64;
                            }
                        }
                        let pool = reuse.entry(pool_key).or_default();
                        // LRU: oldest first. cap 0 = pooling off, park nothing (see the spec
                        // pool above — the unguarded remove(0) panicked at cap 0).
                        while pool.len() >= reuse_pool_per_model().max(1) {
                            pool.remove(0);
                            reuse_metrics.continuation_evictions += 1;
                        }
                        let cap = cache.max_ctx;
                        if reuse_pool_per_model() > 0 {
                            pool.push(ReuseEntry {
                                fed: s.fed, cache, last_logits, cap,
                                ckpt, affinity, fingerprint,
                                parked_at: Instant::now(),
                            });
                        }
                    }
                }
            }
        }
        // STEP-OOM PARK (lane/admit-oom): re-queue parked requests AFTER the retire sweep
        // above — the retire is what actually released their VRAM. Front-inserted in original
        // order so a parked session keeps its place ahead of later arrivals.
        while let Some(req) = requeue_oom.pop_back() {
            queue.push_front(req);
        }
        // publish serving metrics (worker owns the counters; axum reads the snapshot).
        // THROTTLED: the per-tick mutex+percentile cost ~1.7ms/token of B=1 TPOT
        // (2026-07-26 live A/B) — publish every 32nd tick. A spec-session retire forces
        // a publish so a one-shot request's acceptance counts land without a 32-tick wait
        // (retires are per-request, not per-token — no hot-path cost class).
        // LANE/CACHE-METERING: EVERY retire forces a publish (`!finished.is_empty()`),
        // not just spec retires — otherwise a workload whose last tick lands off the
        // 32-boundary parks its final prompt/cached counters unpublished while the
        // worker blocks idle in recv(), and the post-workload /metrics scrape (the
        // hit-rate receipt query) reads stale totals. Same cost class as the spec
        // force-publish: per-request, never per-token.
        tick_n = tick_n.wrapping_add(1);
        if tick_n % 32 == 0 || spec_telem_dirty || !finished.is_empty() {
            if let Ok(mut m) = metrics.lock() {
            spec_telem_dirty = false;
            m.admitted = n_admitted;
            m.completed = n_completed;
            m.tokens_out = n_tokens_out;
            m.step_p50_ms = step_stats.p(50.0).unwrap_or(0.0);
            m.step_p99_ms = step_stats.p(99.0).unwrap_or(0.0);
            m.prompt_tokens_in = n_prompt_in;
            m.cached_tokens_in = n_cached_in;
            m.prefix_hits = px.hits;
            m.prefix_entries = px.n_entries() as u64;
            m.prefix_bytes = px.total_bytes as u64;
            m.prefix_misses = px.misses;
            m.prefix_inserts = px.inserts;
            m.prefix_evictions = px.evictions;
            m.prefix_hit_tokens = px.hit_tokens;
            m.admission_session_defers = n_session_defers;
            m.admission_vram_defers = n_vram_defers;
            m.step_oom_parks = n_step_oom_parks;
            m.continuation_pool_hits = reuse_metrics.continuation_hits;
            m.continuation_pool_evictions = reuse_metrics.continuation_evictions;
            m.plain_affinity_rewinds = reuse_metrics.plain_affinity_rewinds;
            m.spec_pool_hits = reuse_metrics.spec_hits;
            m.spec_pool_misses = reuse_metrics.spec_misses;
            m.spec_pool_affinity_rewinds = reuse_metrics.spec_affinity_rewinds;
            m.spec_pool_evictions = reuse_metrics.spec_evictions;
            m.active_sessions = active.len() as u64;
            m.queued_requests = queue.len() as u64;
            m.continuation_pool_entries =
                reuse.values().map(|pool| pool.len() as u64).sum();
            m.spec_pool_entries =
                spec_reuse.values().map(|pool| pool.len() as u64).sum();
            m.cuda_driver_free_bytes = engine.ctx().mem_get_info()
                .map(|(free, _)| free as u64).unwrap_or(0);
            let (pool_reserved, pool_used) = engine.pool_reserved_used();
            m.cuda_pool_reserved_bytes = pool_reserved as u64;
            m.cuda_pool_used_bytes = pool_used as u64;
            m.cuda_pool_cached_bytes = engine.pool_cached_bytes() as u64;
            m.lcp_hist = px.lcp_hist;
            m.ns_tokens = ns_tokens.clone();
            m.lane_admitted = lane_admitted;
            m.lane_shed = lane_shed;
            m.lane_completed = lane_completed;
            m.lane_tokens = lane_tokens;
            m.batch_size_last = last_batch;
            m.spec = spec_telem.clone();
            m.adsd_suspect_total = adsd_detector.suspect_total.clone();
        } }
        if !finished.is_empty() && std::env::var("MEMRA_SPILL_STATS").as_deref() == Ok("1") {
            if let Some((reads, bytes, errors, short, fallbacks, waits, ring_full)) =
                engine.moe_pread_stats() {
                eprintln!("[spill-pread] snapshot reads={reads} bytes={bytes} errors={errors} \
                           short_reads={short} fallbacks={fallbacks} buffer_waits={waits} \
                           ring_full={ring_full}");
            }
            if let Some((hits, misses, staged_bytes, slots)) = engine.moe_cache_stats() {
                let accesses = hits.saturating_add(misses);
                let hit_rate = if accesses == 0 {
                    0.0
                } else {
                    100.0 * hits as f64 / accesses as f64
                };
                eprintln!("[moe-cache] snapshot hits={hits} misses={misses} \
                           hit_rate={hit_rate:.3} staged_bytes={staged_bytes} slots={slots}");
            }
        }
    }
}

fn handle_cmd(
    cmd: Cmd,
    loaded: &HashMap<String, LoadedModel>,
    order: &[String],
    queue: &mut std::collections::VecDeque<Box<Request>>,
) {
    // Pending-admit gauge (admission yield): the request is now in the worker's hands
    // (queued or rejected below) — the tick-top admission phase runs before the next burst,
    // so no in-flight burst needs to yield for it anymore. Saturating: a direct-channel
    // sender that never incremented (tests) must not underflow.
    let _ = PENDING_ADMITS.fetch_update(
        std::sync::atomic::Ordering::AcqRel,
        std::sync::atomic::Ordering::Acquire,
        |v| v.checked_sub(1),
    );
    match cmd {
        Cmd::Generate(req) => {
            if !loaded.contains_key(&req.model) {
                let _ = req.tx.send(Event::Error(EngineError::model_not_found(format!(
                    "unknown model {:?}; loaded: {:?}", req.model, order))));
                return;
            }
            queue.push_back(req);
        }
    }
}

fn request_ctx_cap(
    server_ctx: usize,
    model_ctx: usize,
    prompt_len: usize,
    max_ctx: Option<usize>,
    max_new: usize,
) -> usize {
    match (max_ctx, max_new) {
        // A request-supplied hard cap is authoritative. In particular, a 128k request on a
        // 256k-default server must allocate and be charged as 128k, not inherit the default.
        (Some(c), _) => c,
        (None, MAX_NEW_CTX_BOUNDED) => {
            // With no output bound, use the server context default. A prompt that does not fit
            // grows to prompt + one default window of room, capped at the model's trained
            // context when it is known.
            let mut cap = server_ctx;
            if prompt_len.saturating_add(16) > cap {
                cap = prompt_len.saturating_add(server_ctx);
            }
            if model_ctx > 0 {
                cap = cap.min(model_ctx);
            }
            cap
        }
        (None, max_new) => prompt_len
            .saturating_add(max_new)
            .saturating_add(8),
    }
}

/// Render/tokenize once, then derive the request's exact context allocation shape before the
/// VRAM gate. `admit` consumes this cached prompt only after the gate passes.
fn prepare_request(
    loaded: &HashMap<String, LoadedModel>,
    req: &mut Request,
) -> Result<RequestShape, EngineError> {
    let lm = &loaded[&req.model];
    if req.prepared_prompt.is_none() {
        if let Some(trace) = req.ttft.as_ref() {
            trace.mark_tokenize_start();
        }
        // Prefer explicit ids (exact-token validation); otherwise render the same template path
        // admission historically used inside `admit`.
        let prompt = if !req.prompt_ids.is_empty() {
            req.prompt_ids.clone()
        } else if !req.chat_turns.is_empty() {
            let plain = req.tools_json.is_empty()
                && req.think == memra_tokenizer::chat::ThinkMode::Default
                && req.reasoning_effort.is_none()
                && req.chat_turns.iter().all(|t| t.role != "tool" && t.tool_calls.is_empty());
            let rendered = if plain {
                let messages: Vec<_> = req.chat_turns.iter()
                    .map(|t| (t.role.as_str(), t.content.as_str()))
                    .collect();
                lm.tok.apply_chat_template(&messages, true)
            } else {
                lm.tok.apply_chat_template_tools(
                    &req.chat_turns,
                    true,
                    &req.tools_json,
                    req.think,
                    req.reasoning_effort.as_deref(),
                ).map_err(|err| EngineError::invalid_param(
                    format!("chat template: {err}"), "messages"))?
            };
            lm.tok.encode(&rendered, true)
        } else if req.chat {
            let rendered = lm.tok.apply_chat_template(
                &[("user", req.prompt_text.as_str())], true);
            lm.tok.encode(&rendered, true)
        } else {
            lm.tok.encode(&req.prompt_text, true)
        };
        if prompt.is_empty() {
            return Err(EngineError::invalid_param(
                "empty prompt after tokenization", "prompt"));
        }
        if let Some(trace) = req.ttft.as_ref() {
            trace.mark_tokenize_end(prompt.len());
        }
        req.prepared_prompt = Some(prompt);
    }

    let prompt_len = req.prepared_prompt.as_ref().unwrap().len();
    let server_ctx = std::env::var("MEMRA_CTX")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(8192);
    let ctx_cap = request_ctx_cap(
        server_ctx,
        lm.model.cfg.context_length as usize,
        prompt_len,
        req.params.max_ctx,
        req.params.max_new,
    );
    if prompt_len >= ctx_cap {
        return Err(EngineError::context_length(format!(
            "prompt ({prompt_len} tok) >= context cap ({ctx_cap})")));
    }
    let budget = req.params.max_new.min(ctx_cap - prompt_len);
    let need = prompt_len.saturating_add(budget).saturating_add(SPEC_SHRINK_SLACK);
    Ok(RequestShape { ctx_cap, budget, need })
}

/// Conservative pre-admit path choice. Reuse or request constraints may ultimately fall back to
/// plain serving, but treating an MTP-capable request as spec here can only reserve more memory.
fn admission_request_may_spec(
    lm: &LoadedModel,
    req: &Request,
    projected_active: usize,
    prompt_len: usize,
) -> bool {
    if confidence_trace_enabled() || lm.model.mtp.is_none() || !serve_spec_enabled() {
        return false;
    }
    req.spec_k_replay.unwrap_or_else(|| {
        choose_spec_k(
            spec_k_pin(),
            spec_gate_on(),
            *spec_gate_thresholds(),
            projected_active,
            prompt_len,
            0,
        ).k
    }) > 0
}

/// Driver-free plus bytes already mapped but reusable in the async pool.
fn effective_free_bytes(engine: &Engine) -> Option<(usize, usize)> {
    engine.ctx().mem_get_info().ok().map(|(driver_free, _)| {
        let pool_cached = engine.pool_cached_bytes();
        (driver_free.saturating_add(pool_cached), pool_cached)
    })
}

/// STEP-OOM PARK (lane/admit-oom, 2026-08-06): rebuild a live session's `Request` so it can go
/// back to the admission queue after a step-time CUDA OOM, instead of the stream dying.
///
/// PRECONDITION (enforced by the caller, not here): the session has emitted NOTHING. A session
/// that already streamed tokens cannot be restarted — the client would see the prefix twice —
/// so those take the honest error. This is why the function needs no emitted-state surgery.
///
/// The rebuilt request replays the ORIGINAL render inputs (`ReplayPlan`), so re-admission runs
/// the identical template + tokenize and produces the session a cold arrival would have. The
/// retry counter rides along on the Request, keeping the bound per-request across re-admits.
/// Returns None when the plan cannot produce a prompt (nothing to replay) — caller errors.
fn park_requeue(loaded: &HashMap<String, LoadedModel>, s: &Session) -> Option<Box<Request>> {
    // A plan with no prompt source at all would re-admit into "empty prompt after
    // tokenization" — report the OOM honestly instead of laundering it into a 400.
    let p = &s.replay;
    if p.prompt_ids.is_empty() && p.prompt_text.is_empty() && p.chat_turns.is_empty() {
        return None;
    }
    debug_assert!(loaded.contains_key(&s.model), "parked session's model must still be loaded");
    Some(Box::new(Request {
        model: s.model.clone(),
        prompt_ids: p.prompt_ids.clone(),
        prompt_text: p.prompt_text.clone(),
        chat: p.chat,
        chat_turns: p.chat_turns.clone(),
        tools_json: p.tools_json.clone(),
        think: p.think,
        reasoning_effort: p.reasoning_effort.clone(),
        params: p.params.clone(),
        sampler_cfg: p.sampler_cfg.clone(),
        stop_strings: s.stop_strings.clone(),
        trace_id: s.trace_id.clone(),
        cache_ns: s.cache_ns.clone(),
        affinity: s.affinity.clone(),
        lane: s.lane,
        grammar: p.grammar.clone(),
        oom_retries: s.oom_retries,
        spec_k_replay: Some(s.spec_k),
        prepared_prompt: None,
        ttft: s.ttft.clone(),
        tx: s.tx.clone(),
    }))
}

/// Build a Session from the prompt prepared before admission, allocate its cache, and build its
/// sampler. The prompt is NOT primed here — it's fed one token per scheduler tick so prefill of a
/// new session interleaves with other sessions' decode (the BASE-4 interleave).
/// `n_active` = live session count at admit time, the K policy's concurrency signal.
/// This request's projected count is `n_active + 1`.
#[allow(clippy::too_many_arguments)]
fn admit(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    reuse: &mut HashMap<PoolKey, Vec<ReuseEntry>>,
    spec_reuse: &mut HashMap<PoolKey, Vec<SpecReuseEntry>>,
    spec_sizing: &mut SpecSizing,
    reuse_metrics: &mut ReuseMetrics,
    px: &mut PrefixCache,
    n_active: usize,
    mut req: Request,
    shape: RequestShape,
) -> Result<Session, (tokio::sync::mpsc::UnboundedSender<Event>, EngineError)> {
    let lm = &loaded[&req.model];
    let prompt = req.prepared_prompt.take()
        .expect("admit requires a prompt prepared by the admission gate");
    let RequestShape { ctx_cap, budget, need } = shape;
    // PC-ISO: every reuse-pool probe below scans ONLY this (model, namespace) pool.
    let pool_key: PoolKey = (req.model.clone(), req.cache_ns.clone());
    // STEP-OOM PARK plan (lane/admit-oom): snapshot the render inputs before this function
    // consumes them, so a step-time OOM can re-admit an identical request. Host-side only.
    let replay = Box::new(ReplayPlan {
        prompt_ids: req.prompt_ids.clone(),
        prompt_text: req.prompt_text.clone(),
        chat: req.chat,
        chat_turns: req.chat_turns.clone(),
        tools_json: req.tools_json.clone(),
        think: req.think,
        reasoning_effort: req.reasoning_effort.clone(),
        params: req.params.clone(),
        sampler_cfg: req.sampler_cfg.clone(),
        grammar: req.grammar.clone(),
    });
    let req_oom_retries = req.oom_retries;
    let req_spec_k_replay = req.spec_k_replay;

    // KV PREFIX REUSE probe: a parked session whose fed sequence is an EXACT PREFIX of this
    // prompt (and whose cache has room) resumes — only the suffix gets primed. The sampler's
    // penalty history is replayed on host (cheap) so sampling matches a cold run exactly.
    let mut reused: Option<ReuseEntry> = None;
    // DEFAULT-ON (2026-07-05): the identity gate now exists at the engine level — session-gate
    // (bins) pins 3-turn continuation-prime output == fresh-greedy oracle on both models, and the
    // continuation path the reuse pool takes (prime_cache with cache.pos>0 / decode_step) is
    // exactly what it validates. MEMRA_KV_REUSE=0 disables.
    let reuse_on = !confidence_trace_enabled()
        && std::env::var("MEMRA_KV_REUSE").map(|v| v != "0").unwrap_or(true);
    if let (true, Some(pool)) = (reuse_on, reuse.get_mut(&pool_key)) {
        if let Some(idx) = pool.iter().rposition(|e|
            e.fed.len() >= REUSE_MIN_PREFIX && e.cap >= ctx_cap
                && prompt.len() >= e.fed.len() && prompt.starts_with(&e.fed)) {
            reused = Some(pool.remove(idx));
        }
    }
    if reused.is_some() {
        reuse_metrics.continuation_hits += 1;
    }

    // PLAIN-SESSION AFFINITY resume (lane/plain-affinity, 2026-08-09). The exact-extension probe
    // above only serves a prompt that EXTENDS a parked session's whole fed stream — a client that
    // REWRITES conversation history (the pi client strips `<think>` out of prior assistant turns)
    // misses it on every turn, and the parked full-context session is discarded while the whole
    // growing conversation re-primes (the 2.35 -> 13.7s TTFT slope, research/cachespec-20260809).
    //
    // Affinity asks the OTHER question — is this the SAME CONVERSATION? — and answers it exactly
    // as the spec tier does: identity NOMINATES (explicit id, else the structural fingerprint
    // chain), an exact token diff against the parked session's REWIND CHECKPOINT DECIDES. A
    // history rewrite mutates what the session GENERATED, so the new prompt still reproduces the
    // committed tokens up to the pre-generation boundary; only this turn's delta primes. A
    // fingerprint collision costs one wasted comparison, never a wrong resume (bytes decide).
    // MEMRA_AFFINITY=0 declines every candidate (the exactness A/B arm).
    if reuse_on && reused.is_none() && affinity_enabled() {
        let req_fp = conversation_fingerprint(&prompt, &|t| lm.tok.token_is_control(t), true);
        let candidate = if let Some(pool) = reuse.get(&pool_key) {
            // WHY A DECLINE IS LOGGED (mirrors the spec tier): every requirement below is
            // invisible outside the worker, and the lane's evidence is per-turn resume counts
            // read from this log. The reason is for the LAST candidate examined (pool depth 1-2).
            let mut why: String = "empty pool".into();
            let cand = pool.iter().enumerate().rev().find_map(|(i, e)| {
                let Some(ckpt) = e.ckpt.as_ref() else {
                    why = "no checkpoint retained".into(); return None;
                };
                let pos = ckpt.pos;
                // SWA RING (lane/kv256-capacity): a ring-capped cache may have overwritten rows
                // below this checkpoint — a lapped checkpoint must DECLINE to the cold path,
                // never restore stale ring rows. No-op on full-slab caches.
                if !e.cache.can_rollback(&ckpt.snap, 0) {
                    why = format!("SWA ring lapped checkpoint {pos}");
                    return None;
                }
                // IDENTITY NOMINATES: explicit id when both sides named one, else the implicit
                // fingerprint chain's shared leading run.
                let identity_matches = match (&req.affinity, &e.affinity) {
                    (Some(a), Some(b)) if a == b => true,
                    (Some(_), _) | (_, Some(_)) => false,
                    _ => fingerprint_affinity(&req_fp, &e.fingerprint) >= FP_MIN_SEGMENTS,
                };
                // Grow to this request's bounded `need`, not the server-global context cap. The
                // admission estimator charges the same request-shaped capacity before admit.
                match affinity_resume_target(
                    &prompt, &e.fed, pos, e.cap, need, identity_matches,
                ) {
                    Ok(target_cap) => Some((i, target_cap)),
                    Err(reason) => { why = reason; None }
                }
            });
            if cand.is_none() && !pool.is_empty() {
                eprintln!("[worker] plain-affinity: declined ({why}; {} parked, {} prompt \
                           tokens; model {})", pool.len(), prompt.len(), req.model);
            }
            cand
        } else {
            None
        };
        if let Some((idx, target_cap)) = candidate {
            let mut e = reuse.get_mut(&pool_key)
                .expect("plain-affinity candidate pool vanished")
                .remove(idx);
            let ckpt = e.ckpt.take().expect("nominated candidate must carry a checkpoint");
            let pos = ckpt.pos;
            let old_cap = e.cap;
            // Roll back in place when there is already room. Otherwise allocate a PP-aware cache
            // at the request-owned charged capacity and restore the checkpoint into it. The old
            // and new buffers overlap only for this D2D copy; on OOM, reclaim once exactly like a
            // cold session allocation, then drop the parked entry and take the cold path.
            let restored: Result<(), Box<dyn std::error::Error>> = if target_cap > old_cap {
                match alloc_with_single_reclaim_retry(
                    || memra_engine::pp::new_cache(engine, &lm.model.cfg, target_cap),
                    |err| {
                        let evicted_prefix = px.evict_all();
                        if evicted_prefix > 0 {
                            eprintln!("[prefix-cache] evicted {evicted_prefix} entries after \
                                       plain-affinity grow alloc failure; retrying");
                        }
                        let evicted_parked = if is_cuda_oom(&err.to_string()) {
                            evict_oldest_parked(reuse, spec_reuse, reuse_metrics)
                        } else {
                            None
                        };
                        if let Some(pool) = evicted_parked {
                            eprintln!("[admit-oom] plain-affinity grow: evicted oldest {} parked \
                                       session (global LRU); retrying cache alloc once",
                                      match pool {
                                          ParkedPool::Plain => "plain",
                                          ParkedPool::Spec => "spec",
                                      });
                        }
                        evicted_prefix > 0 || evicted_parked.is_some()
                    },
                ) {
                    Ok(mut grown) => match memra_engine::pp::restore_cache_checkpoint(
                        engine,
                        &lm.model.cfg,
                        Some(&e.cache),
                        &mut grown,
                        &ckpt.snap,
                    ) {
                        Ok(()) => {
                            e.cache = grown;
                            e.cap = target_cap;
                            Ok(())
                        }
                        Err(err) => Err(err),
                    },
                    Err(err) => Err(err),
                }
            } else {
                memra_engine::pp::restore_cache_checkpoint(
                    engine,
                    &lm.model.cfg,
                    None,
                    &mut e.cache,
                    &ckpt.snap,
                )
            };
            match restored {
                Ok(()) => {
                    debug_assert_eq!(e.cache.pos, pos, "plain rewind landed off the checkpoint");
                    debug_assert_eq!(e.cache.max_ctx, e.cap, "plain cache cap metadata drift");
                    e.fed.truncate(pos);
                    e.last_logits = ckpt.last_logits;
                    reuse_metrics.continuation_hits += 1;
                    reuse_metrics.plain_affinity_rewinds += 1;
                    if target_cap > old_cap {
                        eprintln!("[worker] plain-affinity: grew parked cache {old_cap} -> \
                                   {target_cap} rows (request-owned need)");
                    }
                    eprintln!("[worker] plain-affinity: rewound to {pos} of {} prompt tokens \
                               (priming {} suffix; model {})",
                              prompt.len(), prompt.len() - pos, req.model);
                    reused = Some(e);
                }
                // Allocation, copy, or rollback failure leaves no trustworthy resume state. Drop
                // the entry and let the existing cold allocation path serve the request.
                Err(err) => eprintln!("[worker] plain-affinity resume failed ({err}); \
                                       dropping session, full prime"),
            }
        }
    }

    // SPEC ELIGIBILITY decides the prefix-cache policy up front: spec sessions bypass the
    // cross-request prefix cache entirely (SpecSession owns trunk + draft caches; restoring a
    // trunk-only prefix would leave draft state unprimed — the spec tier keeps its own
    // continuation pool below). Mirrors the spec-branch condition exactly.
    // ST-SPEC QUARANTINE LIFTED (#68 closed, 2026-08-04): the serve-spec divergence on
    // dir-loaded checkpoints was never ST-specific — the per-session persistent draft
    // graph replayed with dangling pool addresses (capture transients not retained +
    // fa_part_pool freeing grown-past buffers the capture baked; fixed in spec.rs/lib.rs,
    // receipts research/fp8ship-20260804/RESULTS.md — the same corruption reproduced on
    // GGUF session bursts at n>=600). Dir checkpoints are spec-eligible again; the
    // serve-st gate pins default-serve text == the run-gen CLI tokenwise oracle.
    let serve_spec = !confidence_trace_enabled()
        && std::env::var("MEMRA_SERVE_SPEC").map(|v| v != "0").unwrap_or(true);
    let mut sampler = Sampler::new(req.sampler_cfg);
    // GREEDY + penalties keeps the legacy tokenwise path (gap-scan F3 plumbing): the greedy
    // spec arm verifies by pure argmax (sampling=None), which would silently ignore the
    // penalties the host sampler applies pre-argmax. Sampled requests carry penalties into
    // the rejection-sampling verify (SpecSampling) and stay spec-eligible.
    let greedy_penalized = sampler.is_greedy()
        && (sampler.penalty_repeat() != 1.0 || sampler.penalty_freq() != 0.0
            || sampler.penalty_present() != 0.0);
    // CONSTRAINED DECODING (response_format): compile the request's grammar against this
    // model's lazily-built vocab factory. Compile errors are clean request errors here —
    // never a mid-stream worker failure. Unconstrained requests skip everything.
    let constraint = match &req.grammar {
        None => None,
        Some(spec) => {
            let factory = lm.constraints.get_or_init(||
                crate::constrained::ConstraintFactory::new(&lm.tok));
            match factory {
                Err(err) => return Err((req.tx, EngineError::invalid_param(
                    format!("constrained decoding: {err}"), "response_format"))),
                Ok(f) => {
                    let sc = f.matcher(spec);
                    if let Some(err) = sc.error() {
                        return Err((req.tx, EngineError::invalid_param(
                            format!("response_format: {err}"), "response_format")));
                    }
                    Some(sc)
                }
            }
        }
    };
    let prefix_requested = reuse_on && serve_batching() && prefix_cache_budget_bytes() > 0;
    let ring_prefix_excluded = memra_engine::cache::swa_ring_on()
        && lm.model.cfg.arch.is_step35();
    if prefix_requested && ring_prefix_excluded {
        eprintln!("[prefix-cache] refused for MEMRA_SWA_RING=1 Step35 session (flat-history \
                   snapshots/restores are excluded)");
    }
    let prefix_on = prefix_requested && !ring_prefix_excluded;
    let policy_lcp = if prefix_on { px.best_lcp(&pool_key, &prompt) } else { 0 };
    let mut spec_k_decision = match req_spec_k_replay {
        Some(k) => SpecKDecision { k, reason: SpecKReason::Replay },
        None => choose_spec_k(
            spec_k_pin(),
            spec_gate_on(),
            *spec_gate_thresholds(),
            n_active + 1,
            prompt.len(),
            0,
        ),
    };

    // SPEC x CONSTRAINED (constrained-full, 2026-08-03): greedy constrained sessions ride
    // spec bursts — the grammar truncates acceptance AFTER the exactness verify and forces
    // the masked argmax at the cut slot (generate_spec_session_constrained). Sampled
    // constrained and the MEMRA_CONSTRAIN_HOST oracle keep plain decode.
    // The request-conditioned K policy owns the placement/concurrency decision: K=0 takes
    // plain decode, while positive K remains subject to the correctness eligibility checks.
    let spec_eligible = serve_spec
        && spec_k_decision.k > 0
        && (constraint.is_none() || (sampler.is_greedy() && !constrain_host()))
        && (sampler.is_greedy() || sampler.temperature() > 0.0)
        && !greedy_penalized
        && lm.model.mtp.is_some();

    // CROSS-REQUEST PREFIX CACHE probe (2026-08-02; module doc at PrefixCache). Only when the
    // continuation pool missed, the session won't go spec, and batched scheduling is live.
    // A hit deep-copies the longest matching entry into a fresh session cache (entries are
    // reusable); a miss with a long-enough LCP against an existing entry arms the split-prime
    // learning insert; cold long prompts arm the seed insert.
    let mut prefix_hit = false;
    let mut prefix_pin = None;
    let mut snapshot_at: Option<usize> = None;
    let mut prefix_miss_lcp: Option<usize> = None;
    let mut seed_prefix = false;
    if prefix_on && reused.is_none() && !spec_eligible {
        if let Some(i) = px.lookup(&pool_key, &prompt) {
            let restored = {
                let e = &px.entries[&pool_key][i];
                // `pp::new_cache`, not `Cache::new` — stage-owned KV under an open ppN door
                // (see the session-cache site below for the full reason). `prefix_restore`
                // then copies plane-by-plane into whatever device each layer landed on.
                match memra_engine::pp::new_cache(engine, &lm.model.cfg, ctx_cap) {
                    Ok(mut c) => match prefix_restore(engine, &mut c, e) {
                        // A prefix-cache restore is a transient carrier consumed straight into a
                        // fresh session below (never re-parked from here), so the plain-affinity
                        // fields are inert defaults — a new checkpoint is armed at Session build.
                        Ok(()) => Ok(ReuseEntry {
                            fed: e.toks.clone(),
                            cache: c,
                            last_logits: e.last_logits.clone(),
                            cap: ctx_cap,
                            ckpt: None,
                            affinity: None,
                            fingerprint: Vec::new(),
                            parked_at: Instant::now(),
                        }),
                        Err(err) => Err(format!("restore failed: {err}")),
                    },
                    Err(err) => Err(format!("session cache alloc failed: {err}")),
                }
            };
            match restored {
                Ok(entry) => {
                    prefix_pin = px.pin(&pool_key, i);
                    debug_assert!(prefix_pin.is_some(), "lookup entry vanished before pin");
                    px.hits += 1;
                    px.hit_tokens += entry.fed.len() as u64;
                    px.record_lcp(entry.fed.len()); // histogram: served-prefix length
                    prefix_hit = true;
                    eprintln!("[prefix-cache] hit: {} of {} prompt tokens from cache (model {})",
                              entry.fed.len(), prompt.len(), req.model);
                    reused = Some(entry);
                }
                Err(msg) => {
                    // headroom discipline: sessions win over the cache — on alloc pressure
                    // drop every entry so the cold path (and the retries behind it) can fit.
                    if msg.starts_with("session cache alloc failed") {
                        let n = px.evict_all();
                        eprintln!("[prefix-cache] {msg}; evicted {n} entries, cold path serves");
                    } else {
                        eprintln!("[prefix-cache] {msg}; cold path serves");
                    }
                }
            }
        }
        if reused.is_none() {
            px.misses += 1;
            let l = px.best_lcp(&pool_key, &prompt);
            px.record_lcp(l); // histogram: best available LCP on a miss
            prefix_miss_lcp = Some(l);
            if l >= PREFIX_CACHE_MIN_TOKENS && l < prompt.len()
                && !px.has_key(&pool_key, &prompt[..l])
            {
                snapshot_at = Some(l);
            }
            if prompt.len() >= PREFIX_CACHE_MIN_TOKENS {
                seed_prefix = true; // re-checked against covering entries at prefill-done
            }
        }
    }

    let (cache, seed_fed, seed_logits) = match reused {
        Some(e) => {
            if !prefix_hit {
                eprintln!("[worker] kv-reuse: {} of {} prompt tokens resumed (model {})",
                          e.fed.len(), prompt.len(), req.model);
            }
            (Some(e.cache), e.fed, e.last_logits)
        }
        // legacy cache deferred: allocated below ONLY if the spec path doesn't take the session.
        None => (None, Vec::new(), Vec::new()),
    };

    // EOS: union of caller-supplied eos + the model's END-OF-GENERATION set (eos + the
    // turn-end control tokens present in the vocab — llama's special_eog: <|im_end|>,
    // <turn|>, <end_of_turn>). eog_ids(), not eos_id alone (lane/gemma4-serve-gaps,
    // 2026-08-07): gemma4's GGUF eos is <eos>=1, but its chat turns end with <turn|> —
    // with only eos_id in the set, generation blew straight through the turn end and the
    // client received literal '<turn|><turn|>thought…' as content
    // (research/gemma4-serve-20260807/raw/postfix-client1-*.json). run_gen and gemma-gate
    // already stop on eog_ids(); the serve path now matches. The EOS token's text is never
    // streamed (existing rule), so the turn token also stops leaking as text.
    let mut params = req.params;
    for id in lm.tok.eog_ids() {
        if !params.eos.contains(&id) { params.eos.push(id); }
    }

    // Suffix-only prefill on a reuse hit; sampler penalty history replayed over the whole prefix.
    for &t in &seed_fed { sampler.accept(t); }
    let suffix: Vec<u32> = prompt[seed_fed.len()..].to_vec();
    let prefill_done_at_admit = suffix.is_empty();
    // SPEC-DECODE serve path (2026-07-05): greedy + MTP head + not a KV-reuse resume (the spec
    // session owns its own caches; folding the reuse pool into SpecSession is a follow-up) +
    // MEMRA_SERVE_SPEC!=0. The whole prompt goes to the spec session as turn 1's suffix; the
    // legacy prefill/decode path is bypassed entirely in step_session.
    let mut spec_resumed = 0usize;
    let mut text_suffix: Option<Vec<u32>> = None;
    // Sampled-spec serve: temperature + filters + penalties ALL ride the rejection-sampling
    // spec path (transforms applied to p and q symmetrically) — the legacy per-token path
    // remains only as the no-MTP/resume fallback.
    let spec = if spec_eligible && seed_fed.is_empty() {
        // POOL RESUME: a parked spec session whose committed sequence exactly prefixes this
        // prompt (with cache room) resumes — only the suffix primes; equal-length = pure burst.
        // Match order: exact token prefix (bit-clean), else TEXT prefix (survives BPE boundary
        // divergence — the ~50% chat-turn miss class). Text hits re-tokenize only the remainder.
        // CONSTRAINED requests never resume parked spec sessions: the park's stashed
        // next_pred/pending is unconstrained state, and the grammar must own generation
        // from token 1. Cold spec session instead (still spec — just no pool hit).
        let mut affinity_rewound: Option<(usize, &'static str)> = None;
        enum SpecResumeProbe {
            Exact(usize),
            Text { index: usize, suffix: Vec<u32> },
            Affinity {
                index: usize,
                explicit: bool,
                old_cap: usize,
                target_cap: usize,
            },
        }
        let resumed = if constraint.is_some() {
            None
        } else {
            let mut probe = None;
            if let Some(pool) = spec_reuse.get(&pool_key) {
                if let Some(index) = pool.iter().rposition(|e|
                    e.sess.cache_max_ctx() >= ctx_cap
                        && prompt.len() >= e.sess.committed.len()
                        && prompt.starts_with(&e.sess.committed))
                {
                    probe = Some(SpecResumeProbe::Exact(index));
                } else if !req.prompt_text.is_empty() {
                    if let Some(index) = pool.iter().rposition(|e|
                        e.sess.cache_max_ctx() >= ctx_cap
                            && req.prompt_text.len() >= e.committed_text.len()
                            && req.prompt_text.starts_with(e.committed_text.as_str()))
                    {
                        let rem = &req.prompt_text[pool[index].committed_text.len()..];
                        probe = Some(SpecResumeProbe::Text {
                            index,
                            suffix: lm.tok.encode(rem, false),
                        });
                    }
                }

            // ---- SESSION AFFINITY (lane/session-affinity, 2026-08-05) ----
            // Both probes above require the new prompt to EXTEND the parked session. A client
            // that rewrites conversation history (the owner's: `<think>` blocks stripped out of
            // prior assistant turns) fails both on every turn, and the parked multi-GB session
            // is discarded while the whole growing conversation re-primes (~3s TTFT at 11k-14k
            // tokens vs llama's 0.19s — research/specpool-20260804/RESULTS.md).
            //
            // Affinity asks the other question: is this the SAME CONVERSATION? Nomination is by
            // identity (explicit client id, else the structural fingerprint chain); the resume
            // decision is then made on BYTES against the session's REWIND BOUNDARY — the
            // prompt-end checkpoint its last turn retained. A history rewrite mutates what the
            // session GENERATED, so the new prompt still agrees with the session's committed
            // tokens up to that boundary, and only this turn's delta (rewritten answer + new
            // user turn) needs priming.
            //
                // Requires a retained checkpoint, an exact byte match through it, and a
                // non-empty suffix. Capacity no longer vetoes: a too-small parked session grows
                // to this request's bounded, admission-charged `need` before rewind.
                if probe.is_none() && affinity_enabled() {
                    let req_fp = conversation_fingerprint(
                        &prompt, &|t| lm.tok.token_is_control(t), true);
                    let mut why: String = "empty pool".into();
                    let cand = pool.iter().enumerate().rev().find_map(|(index, e)| {
                        let Some(pos) = e.sess.rewind_pos() else {
                            why = "no turn checkpoint retained".into();
                            return None;
                        };
                        // SWA RING (lane/kv256-capacity): a ring-capped cache may have
                        // overwritten rows below the rewind boundary — a lapped checkpoint
                        // must DECLINE, never resume over stale ring rows. No-op on full slabs.
                        if !e.sess.rewind_is_resident() {
                            why = format!("SWA ring lapped checkpoint {pos}");
                            return None;
                        }
                        let identity_matches = match (&req.affinity, &e.affinity) {
                            (Some(a), Some(b)) if a == b => true,
                            (Some(_), _) | (_, Some(_)) => false,
                            _ => fingerprint_affinity(&req_fp, &e.fingerprint) >= FP_MIN_SEGMENTS,
                        };
                        match affinity_resume_target(
                            &prompt,
                            &e.sess.committed,
                            pos,
                            e.sess.cache_max_ctx(),
                            need,
                            identity_matches,
                        ) {
                            Ok(target_cap) => Some(SpecResumeProbe::Affinity {
                                index,
                                explicit: e.affinity.is_some(),
                                old_cap: e.sess.cache_max_ctx(),
                                target_cap,
                            }),
                            Err(reason) => {
                                why = reason;
                                None
                            }
                        }
                    });
                    if cand.is_none() && !pool.is_empty() {
                        eprintln!("[worker] spec-affinity: declined ({why}; {} parked, {} prompt \
                                   tokens; model {})", pool.len(), prompt.len(), req.model);
                    }
                    probe = cand;
                }
            }

            match probe {
                Some(SpecResumeProbe::Exact(index)) => Some(
                    spec_reuse.get_mut(&pool_key)
                        .expect("spec exact candidate pool vanished")
                        .remove(index)
                        .sess,
                ),
                Some(SpecResumeProbe::Text { index, suffix }) => {
                    text_suffix = Some(suffix);
                    Some(
                        spec_reuse.get_mut(&pool_key)
                            .expect("spec text candidate pool vanished")
                            .remove(index)
                            .sess,
                    )
                }
                Some(SpecResumeProbe::Affinity {
                    index,
                    explicit,
                    old_cap,
                    target_cap,
                }) => {
                    let mut entry = spec_reuse.get_mut(&pool_key)
                        .expect("spec affinity candidate pool vanished")
                        .remove(index);
                    let rewound = if target_cap > old_cap {
                        alloc_with_single_reclaim_retry(
                            || lm.model.spec_grow_and_rewind_to_checkpoint(
                                engine,
                                &mut entry.sess,
                                target_cap,
                            ),
                            |err| {
                                if !is_cuda_oom(&err.to_string()) {
                                    return false;
                                }
                                let evicted_prefix = px.evict_all();
                                if evicted_prefix > 0 {
                                    eprintln!("[prefix-cache] evicted {evicted_prefix} entries \
                                               after spec-affinity grow OOM; retrying");
                                }
                                let evicted_parked =
                                    evict_oldest_parked(reuse, spec_reuse, reuse_metrics);
                                if let Some(pool) = evicted_parked {
                                    eprintln!("[admit-oom] spec-affinity grow: evicted oldest {} \
                                               parked session (global LRU); retrying once",
                                              match pool {
                                                  ParkedPool::Plain => "plain",
                                                  ParkedPool::Spec => "spec",
                                              });
                                }
                                evicted_prefix > 0 || evicted_parked.is_some()
                            },
                        )
                    } else {
                        lm.model.spec_rewind_to_checkpoint(engine, &mut entry.sess)
                    };
                    match rewound {
                        Ok(Some(pos)) => {
                            if target_cap > old_cap {
                                eprintln!("[worker] spec-affinity: grew parked session {old_cap} \
                                           -> {target_cap} rows (request-owned need)");
                            }
                            affinity_rewound = Some((
                                pos,
                                if explicit { "explicit" } else { "fingerprint" },
                            ));
                            Some(entry.sess)
                        }
                        Ok(None) => {
                            eprintln!("[worker] affinity rewind failed (checkpoint vanished); \
                                       dropping session, full prime");
                            None
                        }
                        Err(err) => {
                            eprintln!("[worker] affinity rewind failed ({err}); \
                                       dropping session, full prime");
                            None
                        }
                    }
                }
                None => None,
            }
        };
        match resumed {
            Some(mut sess) => {
                reuse_metrics.spec_hits += 1;
                if affinity_rewound.is_some() {
                    reuse_metrics.spec_affinity_rewinds += 1;
                }
                // Q2 (audit 2026-08-05): a parked session carries its draft-graph failure
                // memoization; a NEW request gets a fresh capture chance (transient VRAM
                // pressure at park time must not become permanent coverage loss).
                sess.reset_graph_fallback_on_resume();
                spec_resumed = sess.committed.len();
                match affinity_rewound {
                    Some((pos, tier)) => eprintln!(
                        "[worker] spec-affinity: rewound to {pos} of {} prompt tokens \
                         ({tier}; priming {} suffix; model {})",
                        prompt.len(), prompt.len() - pos, req.model),
                    None => eprintln!(
                        "[worker] spec-reuse: {} committed tokens resumed{} (model {})",
                        spec_resumed,
                        if text_suffix.is_some() { " [text-prefix]" } else { "" }, req.model),
                }
                Some(sess)
            }
            None => {
                reuse_metrics.spec_misses += 1;
                // POOL MISS: a parked session's caches (~4GB at 128k: 17-layer trunk KV + draft
                // scratch) can starve the NEW allocation — 2 x 128k sessions + weights don't fit
                // 24GB. Misses survive affinity when the client rewrote history BELOW the
                // session's rewind boundary (or the session never captured one), so the parked
                // session is DEAD WEIGHT for this conversation: evict the pool, then allocate.
                //
                // F5 (spec-pool thrash, 2026-08-05 — research/specpool-20260804): on a
                // VRAM-tight rig EVERY turn of the daily driver is a miss (the client
                // rewrites history), so the old fail->evict->realloc walk ran once per
                // request, progressively slower as the doomed full-size ask grew the churn.
                // Two learned behaviors replace it:
                //   1. EVICT-FIRST: once a model has observed "parked ghost + new session
                //      don't fit" (evict_first), later misses evict the dead-weight pool
                //      BEFORE allocating — same eviction the failure forced anyway, minus
                //      the failed alloc. Roomy rigs never set the flag and keep the pool.
                //   2. RIGHT-SIZE LADDER: a post-evict (genuine) failure no longer dumps
                //      the whole burst to the tokenwise path. Shrink the ask toward
                //      `need` = prompt + budget + SPEC_SHRINK_SLACK — the exact cap this
                //      request's emission needs (MaxNew preempts ContextFull by
                //      construction, so a shrunken session emits identical tokens).
                //      The landing size is memoized (learned_ctx) so later misses ladder
                //      from it instead of re-walking. Below `need` = tokenwise fallback.
                if spec_sizing.evict_first.contains(&req.model) {
                    if let Some(n) = spec_reuse.get_mut(&pool_key)
                        .map(|p| { let n = p.len(); p.clear(); n }).filter(|&n| n > 0)
                    {
                        reuse_metrics.spec_evictions += n as u64;
                        eprintln!("[worker] spec pool evicted ({n}) pre-alloc \
                                   (learned VRAM-tight; model {})", req.model);
                    }
                }
                match lm.model.new_session(engine, ctx_cap) {
                    Ok(sess) => Some(sess),
                    Err(first_err) => {
                        let evicted = spec_reuse.get_mut(&pool_key)
                            .map(|p| { let n = p.len(); p.clear(); n }).unwrap_or(0);
                        if evicted > 0 {
                            reuse_metrics.spec_evictions += evicted as u64;
                            spec_sizing.evict_first.insert(req.model.clone());
                            eprintln!("[worker] spec pool evicted ({evicted}) after alloc \
                                       failure; retrying (evict-first learned)");
                        }
                        let retried = if evicted > 0 {
                            lm.model.new_session(engine, ctx_cap).ok()
                        } else { None };
                        match retried {
                            Some(sess) => Some(sess),
                            None => {
                                // Genuine capacity failure (pool empty). Right-size:
                                // ladder down from the learned/half ask toward `need`.
                                let mut sess = None;
                                if need <= ctx_cap {
                                    let mut ask = spec_sizing.learned_ctx.get(&req.model)
                                        .copied().unwrap_or(ctx_cap / 2)
                                        .clamp(need, ctx_cap);
                                    loop {
                                        let landed = match lm.model.new_session(engine, ask) {
                                            Ok(s) => {
                                                // transient reserve (see SPEC_SHRINK_RESERVE):
                                                // a fit that leaves no headroom panics later on
                                                // a lazy upload — treat as a miss, shrink on.
                                                // (a) the embed table is the biggest lazy
                                                // transient: make it resident FALLIBLY now;
                                                // (b) on a NEW landing size only (ask > learned
                                                // — a size that already served a burst has
                                                // proven its transients resident), PROBE-
                                                // allocate the reserve and drop it. A probe,
                                                // not a mem_get_info read, is the fit signal:
                                                // the async pool's pinned release threshold
                                                // keeps freed blocks cached and invisible to
                                                // free-VRAM queries — and re-probing after the
                                                // transients are resident double-counts them
                                                // (observed: turn-1 ladder walked to need and
                                                // still failed while a 16k session + resident
                                                // transients served fine on turn 0).
                                                let proven = spec_sizing.learned_ctx.get(&req.model)
                                                    .is_some_and(|&l| ask <= l);
                                                let ok = lm.model.ensure_embed_resident(engine).is_ok()
                                                    && (proven
                                                        || engine.alloc_u8_uninit(SPEC_SHRINK_RESERVE).is_ok());
                                                if ok { Some(s) } else { drop(s); None }
                                            }
                                            Err(_) => None,
                                        };
                                        match landed {
                                            Some(s) => {
                                                eprintln!("[worker] spec session right-sized: \
                                                           ctx {ask} of {ctx_cap} (prompt {} + \
                                                           budget {budget}; model {})",
                                                          prompt.len(), req.model);
                                                spec_sizing.learned_ctx.insert(req.model.clone(), ask);
                                                sess = Some(s);
                                                break;
                                            }
                                            None if ask > need => { ask = (ask / 2).max(need); }
                                            None => break,
                                        }
                                    }
                                }
                                if sess.is_none() {
                                    eprintln!("[worker] spec session alloc failed ({first_err}); \
                                               tokenwise path");
                                }
                                sess
                            }
                        }
                    }
                }
            }
        }
    } else { None };
    // spec-resume: replay sampler penalty history over the resumed prefix; queue only the suffix.
    // (text-prefix hit: replay the SESSION's committed ids — the prompt's own ids diverge at the
    // boundary; greedy sessions ignore penalties anyway, this keeps sampled-future-proofing sane.)
    if spec_resumed > 0 {
        match (&spec, &text_suffix) {
            (Some(sess), Some(_)) => { for &t in &sess.committed { sampler.accept(t); } }
            _ => { for &t in &prompt[..spec_resumed] { sampler.accept(t); } }
        }
    }
    // legacy tokenwise cache only when the spec path did NOT take the session (spec owns its own).
    //
    // STAGE-OWNED KV (pp2-batch 2026-08-06): `pp::new_cache`, not `Cache::new`. With the ppN
    // door shut it IS `Cache::new` (one branch, same allocations); with the door open across
    // devices it allocates each layer's KV/recurrent state through the engine of the STAGE that
    // runs that layer, and adds the cache-birth barrier. Allocating a serving cache on the
    // primary under an open door would leave every remote stage peer-reading its OWN cache
    // every step — the same silent-PCIe class as unsharded weights (13.9-28x on a PRO 6000
    // pair), and invisible to exactness gates because peer reads are byte-exact.
    let cache = match (&spec, cache) {
        (Some(_), c) => c,        // reuse hit carried a cache? keep it parked as-is (rare; None normally)
        (None, Some(c)) => Some(c),
        (None, None) => match alloc_with_single_reclaim_retry(
            || memra_engine::pp::new_cache(engine, &lm.model.cfg, ctx_cap),
            |err| {
                // Headroom discipline: prefix entries always yield before a session errors.
                // A quoted allocation OOM additionally reuses cap256k's global continuation-pool
                // LRU hook. Both drops happen before ONE retry; a second failure is reported.
                let evicted_prefix = px.evict_all();
                if evicted_prefix > 0 {
                    eprintln!("[prefix-cache] evicted {evicted_prefix} entries after cache alloc \
                               failure; retrying");
                }
                let evicted_parked = if is_cuda_oom(&err.to_string()) {
                    evict_oldest_parked(reuse, spec_reuse, reuse_metrics)
                } else {
                    None
                };
                if let Some(pool) = evicted_parked {
                    eprintln!("[admit-oom] reclaim-on-alloc-oom: evicted oldest {} parked \
                               session (global LRU); retrying cache alloc once",
                              match pool {
                                  ParkedPool::Plain => "plain",
                                  ParkedPool::Spec => "spec",
                              });
                }
                evicted_prefix > 0 || evicted_parked.is_some()
            },
        ) {
            Ok(c) => Some(c),
            Err(err) => return Err((req.tx,
                EngineError::engine(format!("cache alloc failed: {err}")))),
        },
    };
    // WORKER-TRUTH usage accounting: total prompt tokens (as the worker actually feeds/resumes
    // them — the text-prefix spec resume re-tokenizes only the remainder) + how many came from
    // a cache instead of being computed.
    let (n_prompt, n_cached) = if spec_resumed > 0 {
        let suffix_len = text_suffix.as_ref().map(|t| t.len())
            .unwrap_or_else(|| prompt.len() - spec_resumed);
        (spec_resumed + suffix_len, spec_resumed)
    } else {
        (prompt.len(), seed_fed.len())
    };
    if spec.is_some() && req_spec_k_replay.is_none() {
        spec_k_decision = choose_spec_k(
            spec_k_pin(),
            spec_gate_on(),
            *spec_gate_thresholds(),
            n_active + 1,
            n_prompt,
            n_cached,
        );
    }
    let spec_k = if spec.is_some() { spec_k_decision.k } else { 0 };
    if lm.model.mtp.is_some() {
        let source = if spec_k == spec_k_decision.k {
            spec_k_decision.reason.as_str()
        } else {
            "eligibility-fallback"
        };
        let placement = if spec_gate_pp2_placement() {
            "pp2-cross-device"
        } else {
            "single-or-non-pp2"
        };
        eprintln!(
            "[spec-k] model={:?} tenant={:?} K={spec_k} source={source} \
             prompt={n_prompt} cached={n_cached} lcp={policy_lcp} \
             active={} placement={placement}",
            req.model,
            crate::auth::meter_key(&req.cache_ns),
            n_active + 1,
        );
    }
    // PLAIN-SESSION AFFINITY checkpoint arming (lane/plain-affinity, 2026-08-09). A plain-path
    // session captures a rewind checkpoint at a STABLE PRE-GENERATION boundary so its NEXT
    // rewritten-history turn resumes here. Armed only when:
    //   - affinity is on (the rollback seam / A/B arm),
    //   - this session is on the PLAIN path (spec owns its own SpecCheckpoint tier),
    //   - the model can continuation-prime a suffix over a rewound cache (eager-only gemma4
    //     cannot — the engine refuses pos > 0 prime — so it could never resume; don't capture),
    //   - the checkpoint is NOMINATABLE (2026-08-09 cache-metering regression fix): the client
    //     named its conversation (explicit tier), or the prompt carries enough turn-marker
    //     structure that the implicit fingerprint tier could ever reach the FP_MIN_SEGMENTS
    //     nomination bar. A markerless anonymous prompt can never be nominated, so arming it
    //     bought nothing and COST the in-batch fanout (an armed ckpt_at needs a per-session
    //     boundary-stopped prime, which excludes the session from fanout/prime-batch): the
    //     serve-smoke cache-meter gate's 5-way shared-prefix prompt_ids burst went 0-hit/6-miss
    //     because every session armed a guard-window checkpoint nothing could resume,
    //   - the boundary lies AHEAD of what is already primed (`> seed_fed.len()`), so the prefill
    //     tick will actually stop there and snapshot (a boundary already inside the resumed
    //     prefix cannot be captured by a prime-stop; that turn simply re-primes next time).
    // The boundary is derived from the prompt's own turn markers (`plain_checkpoint_boundary`),
    // never a hardcoded offset; the exact diff at resume still decides on bytes.
    let ckpt_at = if affinity_enabled()
        && spec.is_none()
        && !eager_only_model(lm)
        && !confidence_trace_enabled()
        && (req.affinity.is_some()
            || plain_ckpt_nominatable(&prompt, &|t| lm.tok.token_is_control(t)))
    {
        plain_checkpoint_boundary(&prompt, &|t| lm.tok.token_is_control(t))
            .filter(|&b| b > seed_fed.len())
    } else {
        None
    };
    Ok(Session {
        model: req.model,
        spec_k,
        cache_ns: req.cache_ns,
        affinity: req.affinity,
        lane: req.lane,
        cache,
        sampler,
        spec,
        graph: None,
        graph_pending: None,
        oom_retries: req_oom_retries,
        replay,
        spec_drafted: 0,
        spec_accepted: 0,
        spec_rounds: 0,
        last_logits: seed_logits,
        device_next: None,
        constraint,
        mask_dev: None,
        mask_words: 0,
        fed: seed_fed,
        prefill_queue: if let Some(ts) = text_suffix { ts.into_iter().collect() }
                       else if spec_resumed > 0 { prompt[spec_resumed..].to_vec().into_iter().collect() }
                       else { suffix.into_iter().collect() },
        prefill_done: prefill_done_at_admit,
        generated: Vec::new(),
        tokens_emitted: 0,
        params,
        stop_strings: req.stop_strings,
        trace_id: req.trace_id,
        emitted_bytes: 0,
        budget,
        n_prompt,
        n_cached,
        snapshot_at,
        ckpt_at,
        ckpt_snap: None,
        prefix_miss_lcp,
        seed_prefix,
        prefix_pin,
        tx: req.tx,
        ttft: req.ttft,
        t0: Instant::now(),
    })
}

/// Return only the newly completed UTF-8 text. Tokenizer byte-fallback sequences may span token
/// boundaries; retain an incomplete suffix until a later token completes it instead of emitting a
/// permanent replacement character. Truly invalid bytes are consumed as U+FFFD so they cannot
/// stall every later delta.
fn utf8_delta(decoded: &[u8], emitted_bytes: &mut usize) -> String {
    if *emitted_bytes > decoded.len() {
        return String::new();
    }
    let mut cursor = *emitted_bytes;
    let mut delta = String::new();
    while cursor < decoded.len() {
        match std::str::from_utf8(&decoded[cursor..]) {
            Ok(text) => {
                delta.push_str(text);
                cursor = decoded.len();
            }
            Err(err) => {
                let valid = err.valid_up_to();
                if valid != 0 {
                    // SAFETY: `valid_up_to` is the exact valid UTF-8 prefix certified by Rust.
                    delta.push_str(unsafe {
                        std::str::from_utf8_unchecked(&decoded[cursor..cursor + valid])
                    });
                    cursor += valid;
                }
                match err.error_len() {
                    None => break,
                    Some(invalid) => {
                        delta.push('\u{fffd}');
                        cursor += invalid;
                    }
                }
            }
        }
    }
    *emitted_bytes = cursor;
    delta
}

/// Publish one token-id event and advance the receipt counter only after the channel accepted it.
fn send_token_event(s: &mut Session, id: u32, text: String) -> bool {
    if s.tx.send(Event::Token { id, text }).is_err() {
        return false;
    }
    s.tokens_emitted += 1;
    true
}

/// Number of tokens from an engine-committed speculative burst that belong to this request.
/// Session-mode engine output may cross the scheduler's burst target to keep cache rows and
/// `SpecSession::committed` identical. That surplus is still public on a non-final burst; only
/// the request's remaining budget (or the first EOS) clamps event/generated/usage surfaces.
fn spec_visible_len(tokens: &[u32], request_room: usize, eos_ids: &[u32]) -> usize {
    let capped = tokens.len().min(request_room);
    tokens[..capped]
        .iter()
        .position(|id| eos_ids.contains(id))
        .map_or(capped, |i| i + 1)
}

#[derive(Debug, Default, PartialEq, Eq)]
struct SpecEmitResult {
    sent: usize,
    send_ok: bool,
}

/// Emit a speculative commit slice one token id at a time. `remaining` is the request-owned
/// emission budget, deliberately separate from the engine's committed/cache-row count.
fn emit_spec_token_events<D, S>(
    tokens: &[u32],
    remaining: &mut usize,
    decoded: &mut Vec<u8>,
    cursor: &mut usize,
    eos_ids: &[u32],
    eos_seen: &mut bool,
    mut decode: D,
    mut send: S,
) -> SpecEmitResult
where
    D: FnMut(u32) -> Vec<u8>,
    S: FnMut(Event) -> bool,
{
    let mut result = SpecEmitResult { send_ok: true, ..Default::default() };
    for &id in tokens {
        if *remaining == 0 || *eos_seen {
            break;
        }
        *remaining -= 1;
        let text = if eos_ids.contains(&id) {
            // EOS is still a generated/billed token id, but its marker text is never streamed.
            *eos_seen = true;
            String::new()
        } else {
            decoded.extend_from_slice(&decode(id));
            utf8_delta(decoded, cursor)
        };
        if !send(Event::Token { id, text }) {
            result.send_ok = false;
            break;
        }
        result.sent += 1;
    }
    result
}

/// Account one scheduler call in client-output units. A speculative call may publish many
/// tokens; its wall time is converted to a per-token sample and weighted once per emitted token,
/// matching the one-token legacy path and the rate-limit estimator's `tokens * step_ms` units.
#[allow(clippy::too_many_arguments)]
fn record_output_progress(
    generated_before: usize,
    generated_after: usize,
    lane: Lane,
    elapsed_ms: f32,
    n_tokens_out: &mut u64,
    lane_tokens: &mut [u64; 3],
    step_stats: &mut StepStats,
    last_interactive_decode: &mut Instant,
) -> usize {
    let emitted = generated_after.saturating_sub(generated_before);
    if emitted == 0 {
        return 0;
    }
    *n_tokens_out += emitted as u64;
    lane_tokens[lane.idx()] += emitted as u64;
    if lane == Lane::Interactive {
        let per_token_ms = elapsed_ms / emitted as f32;
        for _ in 0..emitted {
            step_stats.record(per_token_ms);
        }
        *last_interactive_decode = Instant::now();
    }
    emitted
}

/// Prime one common cold prefix per same-window fanout group, then restore that snapshot
/// into every sibling. Returns sessions whose prefill budget was consumed by this stage so
/// the ordinary single-prime loop does not give them a second chunk in the same tick.
fn prefix_fanout_eligible(
    s: &Session,
    eager_only: &std::collections::HashSet<String>,
) -> bool {
    s.spec.is_none()
        && s.graph.is_none()
        && !s.prefill_done
        && s.lane == crate::lanes::Lane::Interactive
        && s.fed.is_empty()
        && s.n_cached == 0
        && s.prefix_pin.is_none()
        && s.prefix_miss_lcp.is_some()
        && s.snapshot_at.is_none()
        // a checkpoint-capturing session needs its own boundary-stopped prime — fanout
        // primes the shared prefix monolithically and cannot honor the per-session stop.
        && s.ckpt_at.is_none()
        && s.cache.as_ref().is_some_and(|c| c.pos == 0 && !c.has_swa_ring())
        && !eager_only.contains(&s.model)
        && s.prefill_queue.len() >= PREFIX_CACHE_MIN_TOKENS
}

#[allow(clippy::too_many_arguments)]
fn dedup_interactive_prefixes(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    eager_only: &std::collections::HashSet<String>,
    px: &mut PrefixCache,
    active: &mut [Session],
    finished: &mut Vec<usize>,
    prefix_cap: usize,
    n_cached_in: &mut u64,
    ns_tokens: &mut HashMap<String, [u64; 2]>,
) -> std::collections::HashSet<usize> {
    let mut advanced = std::collections::HashSet::new();
    if !prefix_dedup_enabled()
        || prefix_cap < PREFIX_CACHE_MIN_TOKENS
        || confidence_trace_enabled()
    {
        return advanced;
    }
    let candidates: Vec<PrefixFanoutCandidate> = active.iter().enumerate()
        .filter(|(i, s)| {
            !finished.contains(i) && prefix_fanout_eligible(s, eager_only)
        })
        .map(|(active_idx, s)| PrefixFanoutCandidate {
            active_idx,
            key: s.pool_key(),
            prompt: s.prefill_queue.iter().copied().collect(),
        })
        .collect();

    for group in prefix_fanout_groups(&candidates, prefix_cap) {
        let leader_i = group.members[0];
        if finished.contains(&leader_i) {
            continue;
        }
        let prefix: Vec<u32> = active[leader_i].prefill_queue.iter()
            .take(group.prefix_len)
            .copied()
            .collect();
        let queued_after = active[leader_i].prefill_queue.len() - group.prefix_len;
        let model = active[leader_i].model.clone();
        let key = active[leader_i].pool_key();
        let t0 = Instant::now();
        let leader_out = {
            let s = &mut active[leader_i];
            loaded[&model].model.prime_cache(
                engine,
                &prefix,
                s.cache.as_mut().unwrap(),
                queued_after,
            )
        };
        let (leader_logits, _h, _x) = match leader_out {
            Ok(out) => out,
            Err(err) => {
                let _ = active[leader_i].tx.send(Event::Error(EngineError::engine(
                    format!("prefix fanout prime failed: {err}"),
                )));
                finished.push(leader_i);
                eprintln!("[prefix-dedup] leader prime FAILED (model {model}): {err}");
                continue;
            }
        };
        advanced.insert(leader_i);
        let snapshot = prefix_snapshot(
            engine,
            active[leader_i].cache.as_ref().unwrap(),
            &prefix,
            &leader_logits,
        );
        {
            let s = &mut active[leader_i];
            s.last_logits = leader_logits;
            s.prefill_queue.drain(..group.prefix_len);
            for &tok in &prefix {
                s.fed.push(tok);
                s.sampler.accept(tok);
            }
            s.prefill_done = s.prefill_queue.is_empty();
            s.prefix_miss_lcp = None;
        }
        let entry = match snapshot {
            Ok(entry) => entry,
            Err(err) => {
                eprintln!("[prefix-dedup] snapshot failed ({err}); siblings prime cold");
                continue;
            }
        };

        let mut participants = vec![leader_i];
        for &i in group.members.iter().skip(1) {
            if finished.contains(&i) {
                continue;
            }
            let restored = prefix_restore(
                engine,
                active[i].cache.as_mut().unwrap(),
                &entry,
            );
            if let Err(err) = restored {
                let _ = active[i].tx.send(Event::Error(EngineError::engine(
                    format!("prefix fanout restore failed: {err}"),
                )));
                finished.push(i);
                eprintln!("[prefix-dedup] sibling restore FAILED (model {model}): {err}");
                continue;
            }
            // NOTE (code-audit-20260809 §2.5): this `.expect()` asserts a single-threaded
            // invariant (a fanout sibling always carries the provisional miss recorded at its
            // admission). This lane's new admission routes (plain-affinity resume) do NOT enter
            // the fanout path — an armed `ckpt_at` excludes a session from `prefix_fanout_eligible`
            // — so the invariant is untouched here and the assert stays. Continuing past a missing
            // miss AFTER a successful restore would double-prime the sibling (cache holds the
            // prefix, session state not advanced) — a worse failure than the assert. Left as-is.
            let miss_lcp = active[i].prefix_miss_lcp.take()
                .expect("prefix fanout sibling must carry its admission miss");
            {
                let s = &mut active[i];
                s.last_logits = entry.last_logits.clone();
                s.prefill_queue.drain(..group.prefix_len);
                for &tok in &prefix {
                    s.fed.push(tok);
                    s.sampler.accept(tok);
                }
                s.prefill_done = s.prefill_queue.is_empty();
                s.n_cached += group.prefix_len;
                s.seed_prefix = false;
            }
            px.promote_miss_to_hit(miss_lcp, group.prefix_len);
            *n_cached_in += group.prefix_len as u64;
            meter_cached_credit(
                ns_tokens,
                &active[i].cache_ns,
                group.prefix_len as u64,
            );
            participants.push(i);
            advanced.insert(i);
        }

        let pin = px.insert_pinned(&key, entry, "in-batch fanout", participants.len());
        for &i in &participants {
            active[i].seed_prefix = false;
            if let Some(pin) = &pin {
                debug_assert!(active[i].prefix_pin.is_none());
                active[i].prefix_pin = Some(pin.clone());
            }
        }
        eprintln!(
            "[prefix-dedup] B={} prefix={} saved={} hash={:016x} in {:.1}ms \
             retained={} (model {}{})",
            participants.len(),
            group.prefix_len,
            group.prefix_len * participants.len().saturating_sub(1),
            fnv1a(0xcbf29ce484222325, &prefix),
            t0.elapsed().as_secs_f64() * 1e3,
            pin.is_some(),
            model,
            ns_suffix(&key.1),
        );
    }
    advanced
}

/// One scheduler tick for one session. Returns Ok(true) if still running, Ok(false) if retired.
/// Decomposes `generate_with`'s loop body into a single per-session step (same semantics):
///   - prefill phase: consume ONE prompt token via decode_step, accept it into the sampler.
///   - decode phase: sample from last_logits, accept, stream the token, check EOS/stop/ctx, then
///     run ONE decode_step to produce the next logits.
/// One prefill tick for a session under a token budget. Returns tokens consumed.
/// Same chunking laws as step_session's prefill phase (PRIME_MIN_T floor, tail handling).
fn prefill_tick(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    px: &mut PrefixCache,
    s: &mut Session,
    budget: usize,
) -> Result<usize, Box<dyn std::error::Error>> {
    if let Some(trace) = s.ttft.as_ref() {
        trace.mark_prime_start();
    }
    let lm = &loaded[&s.model];
    let q = s.prefill_queue.len();
    if q == 0 {
        s.prefill_done = true;
        maybe_prefix_seed(engine, px, s);
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_end();
        }
        return Ok(0);
    }
    let mut consumed = 0usize;
    // EAGER-ONLY prime shape (lane/gemma4-serve-gaps, 2026-08-07): gemma4's prime is
    // fresh-monolithic ONLY — no chunked and no continuation prime (the engine refuses
    // pos > 0; before it refused, chunk 2 of a >tick-budget prompt KILLED the worker on
    // gemma4_prime's assert, in both scheduler modes). So: fresh prompts prime WHOLE
    // (budget uncapped — a long gemma4 prompt trades one long tick for correctness),
    // carried suffixes (reuse/prefix resume) ride the tokenwise decode_step path, and the
    // LCP split is skipped (its boundary-stop would turn the tail into a continuation).
    let eager_mono = eager_only_model(lm);
    let carried = s.cache.as_ref().is_some_and(|c| c.pos > 0);
    if eager_mono {
        s.snapshot_at = None;
        // eager-only models (gemma4) cannot continuation-prime a suffix over a rewound cache
        // (the engine refuses pos > 0 prime), so plain-affinity resume excludes them — no
        // point capturing a checkpoint they can never resume from.
        s.ckpt_at = None;
    }
    // BOUNDARY STOP: the prime must stop exactly at the NEXT of two pre-generation boundaries
    // ahead — the prefix-cache LCP split (`snapshot_at`) and the plain-affinity checkpoint
    // (`ckpt_at`). A residual below the prime floor rides the tokenwise path (unreachable at the
    // current PREFILL_TICK_T, guarded for smaller budgets). Taking the MIN keeps both captures
    // landing on their exact fed boundary; the same session rarely carries both, but when it
    // does the earlier boundary is honored first and the later one next tick.
    let fed_len = s.fed.len();
    let bound_rem = [s.snapshot_at, s.ckpt_at].into_iter()
        .flatten()
        .filter(|&b| b > fed_len)
        .map(|b| b - fed_len)
        .min();
    if !confidence_trace_enabled()
        && q >= memra_engine::hybrid_forward::PRIME_MIN_T.max(2)
        && budget >= memra_engine::hybrid_forward::PRIME_MIN_T
        && !(eager_mono && carried)
        && bound_rem.is_none_or(|r| r >= memra_engine::hybrid_forward::PRIME_MIN_T)
    {
        let mut take = if eager_mono { q } else { q.min(budget) };
        if q - take > 0 && q - take < memra_engine::hybrid_forward::PRIME_MIN_T {
            take = if q <= budget { q } else { take };
        }
        if let Some(r) = bound_rem {
            if take >= r {
                take = r; // stop exactly at the snapshot boundary
            } else if r - take < memra_engine::hybrid_forward::PRIME_MIN_T {
                // keep the boundary chunk itself primeable next tick
                take = (r - memra_engine::hybrid_forward::PRIME_MIN_T)
                    .max(memra_engine::hybrid_forward::PRIME_MIN_T);
            }
        }
        let chunk: Vec<u32> = s.prefill_queue.drain(..take).collect();
        // REQUEST-LEVEL seq_end (lane/tick-seg, 2026-08-07): the tokens still queued after this
        // tick are the SAME request — pass them so the engine's arm selection is keyed to the
        // request's end, not this tick's. Without it the tick budget (dark lanes: 256 AND
        // SLO-headroom-capped) and the LCP-split boundary steered step35's prefill arithmetic
        // (budgets 512/256/64 DIFFER 1.813e0 vs monolithic — tickinv35 gate).
        let (l, _h, _x) = lm.model.prime_cache(engine, &chunk, s.cache.as_mut().unwrap(),
                                               s.prefill_queue.len())?;
        s.last_logits = l;
        for &tok in &chunk { s.fed.push(tok); s.sampler.accept(tok); }
        consumed = take;
    } else if let Some(tok) = s.prefill_queue.pop_front() {
        s.last_logits = lm.model.decode_step(engine, tok, s.cache.as_mut().unwrap())?;
        if let Some(&target) = s.prefill_queue.front() {
            write_confidence_trace(s, tok, target, &s.last_logits)?;
        }
        s.fed.push(tok);
        s.sampler.accept(tok);
        consumed = 1;
    }
    // Boundary reached: snapshot the primed prefix into the cache, then keep priming the rest
    // of the prompt as a continuation (the LCP-split learning insert).
    if s.snapshot_at == Some(s.fed.len()) {
        s.snapshot_at = None;
        prefix_insert_from_session(engine, px, s, "lcp-split");
    }
    // PLAIN-AFFINITY: capture the pre-generation checkpoint the instant the prime reaches its
    // boundary (no-op unless s.ckpt_at == s.fed.len()). Cheap — one GDN-state snapshot.
    maybe_plain_checkpoint(engine, s);
    if s.prefill_queue.is_empty() {
        s.prefill_done = true;
        maybe_prefix_seed(engine, px, s);
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_end();
        }
    }
    Ok(consumed)
}

/// GRAMMAR MASK STAGING (constrained-full, 2026-08-03): compute the session's current
/// llguidance token mask and H2D the packed bitset into its STABLE device buffer for the
/// upcoming batched step. Runs AFTER advance_sample_emit consumed the tick's token — the
/// mask reflects the post-consume grammar state, exactly the set legal for the NEXT token.
/// No-op (mask_words = 0 -> host fallback) for unconstrained sessions, fallback sampler
/// configs (penalties/filters host-sample), and the MEMRA_CONSTRAIN_HOST=1 oracle.
/// EAGER-ONLY predicate (lane/gemma4-serve-gaps, 2026-08-07): models the batched scheduler
/// must serve through the per-session eager body. gemma4 (12B/26B/31B and E4B): the batched
/// decode bodies have no arm for its per-layer swa/global geometry + softcapped head (the
/// engine refuses), `prime_cache_batch` has no gemma4 core, `gemma4_prime` is fresh-only
/// (no chunked/continuation prime), and the step-wise graph capture walks the generic
/// qwen-class dc step. One predicate, consumed at every batched entry point, so a future
/// arch with the same gaps joins by predicate rather than scattered call-site checks.
fn eager_only_model(lm: &LoadedModel) -> bool {
    lm.model.cfg.gemma4.is_some() || lm.model.is_gemma4_e4b()
}

fn stage_grammar_mask(engine: &Engine, s: &mut Session) -> Result<(), String> {
    s.mask_words = 0;
    if s.constraint.is_none() || constrain_host() || devsample_meta(s).is_none() {
        return Ok(());
    }
    let mask = s.constraint.as_mut().unwrap().compute_mask()?;
    let words = mask.as_slice();
    match s.mask_dev.as_mut() {
        Some(d) if d.len() >= words.len() => {
            engine.htod_u32_into(d, words).map_err(|e| e.to_string())?;
        }
        _ => {
            let mut d = engine.alloc_u32_zeroed(words.len()).map_err(|e| e.to_string())?;
            engine.htod_u32_into(&mut d, words).map_err(|e| e.to_string())?;
            s.mask_dev = Some(d);
        }
    }
    s.mask_words = words.len();
    Ok(())
}

/// The decode tick's HOST half: sample from last_logits, emit the token, run the stop
/// battery. Returns (continue?, Some(next_token) to feed the next step). Extracted from
/// step_session so the batched scheduler can drive many sessions into ONE engine step.
fn advance_sample_emit(
    loaded: &HashMap<String, LoadedModel>,
    s: &mut Session,
) -> (bool, Option<u32>) {
    let lm = &loaded[&s.model];
    if s.generated.len() >= s.budget {
        finish(s, StopReason::MaxNew);
        return (false, None);
    }
    // Device-presampled token from the last batched tick (Session.device_next): skips the
    // O(n_vocab) host sample (measured 1.36 ms/row at 248k vocab). Greedy device rows are
    // bit-identical to host argmax; temp rows are the seeded device draw (gate3 contract).
    // CONSTRAINED rows never device-sample (their samp meta is None) — they host-sample
    // from a grammar-masked COPY of last_logits (the pristine row still parks into the
    // reuse pool at retire, so continuations resume unmasked).
    let next = match (s.device_next.take(), s.constraint.as_mut()) {
        (Some(t), _) => t,
        (None, Some(c)) => {
            let mut row = s.last_logits.clone();
            if let Err(err) = c.mask_logits(&mut row) {
                let _ = s.tx.send(Event::Error(EngineError::engine(format!("constraint mask: {err}"))));
                return (false, None);
            }
            s.sampler.sample(&row)
        }
        (None, None) => s.sampler.sample(&s.last_logits),
    };
    s.sampler.accept(next);
    s.generated.push(next);
    if let Some(trace) = s.ttft.as_ref() {
        trace.mark_first_decode();
    }
    if s.params.eos.contains(&next) {
        if !send_token_event(s, next, String::new()) {
            abort_log(s);
            return (false, None);
        }
        finish(s, StopReason::Eos);
        return (false, None);
    }
    // Advance the grammar with the accepted (non-EOS) token. The token came from this
    // state's own mask, so an error here is a real bug — stop LOUDLY, never emit
    // schema-violating text as if it conformed.
    if let Some(c) = s.constraint.as_mut() {
        if let Err(err) = c.consume(next) {
            let _ = s.tx.send(Event::Error(EngineError::engine(format!("constraint advance: {err}"))));
            return (false, None);
        }
    }
    let decoded = lm.tok.decode_bytes_special(&s.generated, true);
    let delta = utf8_delta(&decoded, &mut s.emitted_bytes);
    let full = String::from_utf8_lossy(&decoded);
    // DISCONNECT ABORT (gap-scan F8): a failed send = receiver dropped = client gone.
    // Stop generating THIS tick (the tick-top sweep would only catch it next tick).
    if !send_token_event(s, next, delta) {
        abort_log(s);
        return (false, None);
    }
    if !s.stop_strings.is_empty() && s.stop_strings.iter().any(|ss| full.contains(ss.as_str())) {
        finish(s, StopReason::Callback);
        return (false, None);
    }
    if s.cache.as_ref().map(|c| c.pos >= c.max_ctx).unwrap_or(false) {
        finish(s, StopReason::ContextFull);
        return (false, None);
    }
    (true, Some(next))
}

/// Token-driven twin of `advance_sample_emit` for the graph path: the token was produced
/// by the DEVICE argmax (greedy), so there is no sampling — accept, emit, stop battery.
/// Returns (continue?, ()).
fn advance_token_emit(
    loaded: &HashMap<String, LoadedModel>,
    s: &mut Session,
    tok: u32,
) -> (bool, ()) {
    let lm = &loaded[&s.model];
    if s.generated.len() >= s.budget {
        finish(s, StopReason::MaxNew);
        return (false, ());
    }
    s.sampler.accept(tok);
    s.generated.push(tok);
    if let Some(trace) = s.ttft.as_ref() {
        trace.mark_first_decode();
    }
    if s.params.eos.contains(&tok) {
        if !send_token_event(s, tok, String::new()) {
            abort_log(s);
            return (false, ());
        }
        finish(s, StopReason::Eos);
        return (false, ());
    }
    // CONSTRAINED graph sessions: the token came from the in-graph masked argmax — advance
    // the grammar (post-EOS-check, same ordering as advance_sample_emit). An error here is
    // a real bug: loud stop, never emit schema-violating text as if it conformed.
    if let Some(c) = s.constraint.as_mut() {
        if let Err(err) = c.consume(tok) {
            let _ = s.tx.send(Event::Error(EngineError::engine(format!("constraint advance: {err}"))));
            return (false, ());
        }
    }
    let decoded = lm.tok.decode_bytes_special(&s.generated, true);
    let delta = utf8_delta(&decoded, &mut s.emitted_bytes);
    let full = String::from_utf8_lossy(&decoded);
    // DISCONNECT ABORT (gap-scan F8): failed send = client gone, stop this tick.
    if !send_token_event(s, tok, delta) {
        abort_log(s);
        return (false, ());
    }
    if !s.stop_strings.is_empty() && s.stop_strings.iter().any(|ss| full.contains(ss.as_str())) {
        finish(s, StopReason::Callback);
        return (false, ());
    }
    (true, ())
}

/// Group ready (session_idx, token) pairs into batched-step chunks: same model, <= 8 rows
/// (the exactness-tier cap), input order preserved (caller sorted interactive first).
/// Device-side batched-tick sampling (default ON — measured 1.36 ms/row host temp-sample at
/// the 9B's 248k vocab, ~45% of the B=8 serving tick). MEMRA_SERVE_DEVSAMPLE=0 is the
/// rollback/A-B seam: every row host-samples from last_logits as before.
fn serve_devsample() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("MEMRA_SERVE_DEVSAMPLE").as_deref() != Ok("0"))
}

/// LEAN LOGITS (inc2 component 3, default ON): device-sampled rows skip the [n_vocab]
/// logits D2H; the last row parks on-device per cache and is D2H'd once at retire (the
/// reuse-pool consumer). MEMRA_SERVE_LEANLOGITS=0 is the rollback/A-B seam (full D2H,
/// the exact pre-change tick).
fn serve_leanlogits() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("MEMRA_SERVE_LEANLOGITS").as_deref() != Ok("0"))
}

/// MEMRA_CONSTRAIN_HOST=1 (rollback oracle): constrained rows keep the v1 host-side
/// masked-copy sample (full-row D2H + O(n_vocab) host sample) instead of the device
/// grammar mask. Diagnostics/A-B only — the device path is the shipped default.
fn constrain_host() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("MEMRA_CONSTRAIN_HOST").as_deref() == Ok("1"))
}

/// Device-sample meta for a session's row in the batched step (the ONE eligibility rule —
/// the samp closure and the grammar-mask staging pass must agree): greedy-no-penalties
/// (device argmax, bit-identical) or pure-temperature (seeded gumbel). Penalty/top-k/
/// top-p/min-p configs host-sample. Counter = generated.len() — a session-progress
/// function, independent of batch composition (the isolation contract, gate3).
fn devsample_meta(s: &Session) -> Option<(f32, u64, u32)> {
    if !serve_devsample() {
        return None;
    }
    let sm = &s.sampler;
    let no_pen = sm.penalty_repeat() == 1.0
        && sm.penalty_freq() == 0.0
        && sm.penalty_present() == 0.0;
    if !no_pen || sm.top_k() != 0 || sm.top_p() < 1.0 || sm.min_p() > 0.0 {
        return None;
    }
    if sm.is_greedy() {
        Some((0.0, 0, 0))
    } else {
        Some((sm.temperature(), sm.seed(), s.generated.len() as u32))
    }
}

/// Per-model decode chunk width. MEMRA_DECODE_BATCH_CAP (explicit door) wins; otherwise
/// models that qualify for the EXACT-16 tier (decode_batch_exact16_ok — every matmul has
/// a bit-exact b16-class kernel) default to chunk 16, the measured winner on the 5090
/// (+12% aggregate over chunk 8 at 32 seqs — research/batched-tick-inc3-20260801/
/// chunksweep.log); everything else keeps the chunk-8 exactness tier. Isolation contract
/// unchanged either way (gate2 bit-strength PASS at both widths).
///
/// The Q8_0 q8rp-mirror precondition was REMOVED 2026-08-06 (lane/rp-on-st): Q8_0's b16
/// twin existed only in `_rp` form, which made a bandwidth mirror a *correctness*
/// prerequisite for the tier. With `qmatvec_q8_0_mmvq_b16` (base layout) plus b16 twins
/// for NVFP4 / Q4_K / Q5_K, the predicate — an ALL over ~500 matmuls — finally admits
/// real MIXED checkpoints. Before that, one missing class refused the whole model, so
/// chunk 16 was unreachable for every shipped artifact, GGUF and FP8-ST alike.
fn chunk_cap_for(lm: &LoadedModel) -> usize {
    // step35 (lane/step35-batched-decode, 2026-08-08): the REAL batched arm exists —
    // `step35_decode_batch_layers` carries the per-layer n_head / partial rope / per-session
    // SWA views / head-wise gate the generic body lacked (the b2ab garbage receipt,
    // research/step-sku-20260807/raw/b2ab-pre-*.log, was the GENERIC arm running past the
    // ppn door; that arm is now unreachable for this arch at any B). Chunk cap 8: the
    // exactness-tier width (IQ4_XS trunk + 288-expert MoE refuse exact16 by predicate —
    // `decode_batch_exact16_ok` requires non-MoE — so 16 is structurally out). The
    // MEMRA_STEP35_BATCH=0 rollback seam caps at B=1. Since lane/cx-b1fix, PP-N B=1 also
    // fails closed rather than falling back to its load-history-dependent eager numeric
    // class; the cap still keeps the scheduler from forming wider doomed chunks.
    // MEMRA_DECODE_BATCH_CAP may narrow BELOW 8, never widen past it.
    if lm.model.cfg.step35.is_some() {
        if !HybridModel::step35_batch_on() {
            return 1;
        }
        let cap = std::env::var("MEMRA_DECODE_BATCH_CAP").ok()
            .and_then(|v| v.parse().ok()).unwrap_or(8usize);
        return cap.clamp(1, 8);
    }
    if let Some(c) = std::env::var("MEMRA_DECODE_BATCH_CAP").ok().and_then(|v| v.parse().ok()) {
        return usize::clamp(c, 1, 32);
    }
    if lm.model.decode_batch_exact16_ok() { 16 } else { 8 }
}

fn group_chunks(
    active: &[Session],
    ready: &[(usize, u32)],
    caps: &HashMap<String, usize>,
) -> Vec<Vec<(usize, u32)>> {
    let mut chunks: Vec<Vec<(usize, u32)>> = Vec::new();
    for &(i, t) in ready {
        let model = &active[i].model;
        let cap = caps.get(model).copied().unwrap_or(8);
        match chunks.last_mut() {
            Some(c) if c.len() < cap && active[c[0].0].model == *model => c.push((i, t)),
            _ => chunks.push(vec![(i, t)]),
        }
    }
    chunks
}

fn spec_pipe_pairable(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    a: &Session,
    b: &Session,
) -> bool {
    if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
        || a.model != b.model
        || a.spec_k == 0
        || a.spec_k != b.spec_k
        || a.spec.is_none()
        || b.spec.is_none()
        || !a.prefill_done
        || !b.prefill_done
        || !a.prefill_queue.is_empty()
        || !b.prefill_queue.is_empty()
        || a.generated.is_empty()
        || b.generated.is_empty()
        || !a.sampler.is_greedy()
        || !b.sampler.is_greedy()
        || a.constraint.is_some()
        || b.constraint.is_some()
        || a.generated.len() >= a.budget
        || b.generated.len() >= b.budget
    {
        return false;
    }
    for sess in [a.spec.as_ref().unwrap(), b.spec.as_ref().unwrap()] {
        if sess.committed_len() == 0 || (sess.next_pred.is_none() && !sess.has_pending()) {
            return false;
        }
    }
    loaded[&a.model].model.spec_pipe_available(engine)
}

fn finish_pipelined_spec_burst(
    lm: &LoadedModel,
    s: &mut Session,
    burst: Vec<u32>,
    drafted: usize,
    accepted: usize,
    telem_before: memra_engine::spec::SpecTelemetry,
    request_room: usize,
    spec_telem: &mut HashMap<String, memra_engine::spec::SpecTelemetry>,
) -> Result<bool, Box<dyn std::error::Error>> {
    if let Some(trace) = s.ttft.as_ref() {
        trace.mark_prime_end();
        if !burst.is_empty() {
            trace.mark_first_decode();
        }
    }
    let spec = s.spec.as_ref().expect("paired spec session disappeared");
    let telem_delta = spec.telem.delta_since(&telem_before);
    spec_telem.entry(s.model.clone()).or_default().merge(&telem_delta);
    s.spec_rounds += telem_delta.rounds;
    s.spec_drafted += drafted;
    s.spec_accepted += accepted;
    if drafted > 0 {
        eprintln!("[spec-acc] ctx={} burst={}/{} cum={}/{}={:.3}",
                  s.fed.len(), accepted, drafted, s.spec_accepted, s.spec_drafted,
                  s.spec_accepted as f64 / s.spec_drafted.max(1) as f64);
    }

    let tok_ref = &lm.tok;
    let eos_ids = s.params.eos.clone();
    let public_len = spec_visible_len(&burst, request_room, &eos_ids);
    let public_burst = &burst[..public_len];
    let mut decoded_visible = tok_ref.decode_bytes_special(&s.generated, true);
    let mut cursor = s.emitted_bytes;
    let mut emit_remaining = request_room;
    let mut eos_seen = false;
    let tx = s.tx.clone();
    let emitted = emit_spec_token_events(
        public_burst,
        &mut emit_remaining,
        &mut decoded_visible,
        &mut cursor,
        &eos_ids,
        &mut eos_seen,
        |id| tok_ref.decode_bytes_special(&[id], true),
        |event| tx.send(event).is_ok(),
    );
    if emitted.send_ok {
        debug_assert_eq!(emitted.sent, public_len, "one token event per public spec token");
    }
    let mut stop: Option<StopReason> = None;
    for &tok in public_burst {
        s.sampler.accept(tok);
        s.generated.push(tok);
        s.fed.push(tok);
        if eos_ids.contains(&tok) {
            stop = Some(StopReason::Eos);
            break;
        }
    }
    s.tokens_emitted += emitted.sent;
    s.emitted_bytes = cursor;
    if !emitted.send_ok {
        abort_log(s);
        return Ok(false);
    }
    let full = String::from_utf8_lossy(&decoded_visible);
    if stop.is_none()
        && !s.stop_strings.is_empty()
        && s.stop_strings.iter().any(|ss| full.contains(ss.as_str()))
    {
        stop = Some(StopReason::Callback);
    }
    if stop.is_none() && s.generated.len() >= s.budget {
        stop = Some(StopReason::MaxNew);
    }
    let context_full = s.spec.as_ref().is_some_and(|spec| {
        spec.committed.len() + s.spec_k + 3 >= spec.cache_max_ctx()
    });
    if stop.is_none() && context_full {
        stop = Some(StopReason::ContextFull);
    }
    if let Some(reason) = stop {
        finish(s, reason);
        return Ok(false);
    }
    Ok(true)
}

fn step_spec_pair(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    a: &mut Session,
    b: &mut Session,
    spec_telem: &mut HashMap<String, memra_engine::spec::SpecTelemetry>,
) -> Result<(bool, bool), Box<dyn std::error::Error>> {
    debug_assert!(spec_pipe_pairable(engine, loaded, a, b));
    let lm = &loaded[&a.model];
    for s in [&mut *a, &mut *b] {
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_start();
        }
    }
    let burst_t: usize = std::env::var("MEMRA_SPEC_BURST")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(32);
    let room_a = a.budget.saturating_sub(a.generated.len());
    let room_b = b.budget.saturating_sub(b.generated.len());
    let target_a = room_a.min(burst_t);
    let target_b = room_b.min(burst_t);
    let telem_a = a.spec.as_ref().unwrap().telem;
    let telem_b = b.spec.as_ref().unwrap().telem;
    let (burst_a, burst_b) = lm.model.generate_spec_session_pair(
        engine,
        a.spec.as_mut().unwrap(),
        target_a,
        a.spec_k,
        b.spec.as_mut().unwrap(),
        target_b,
        b.spec_k,
    )?;
    let (out_a, drafted_a, accepted_a) = burst_a;
    let (out_b, drafted_b, accepted_b) = burst_b;
    let keep_a = finish_pipelined_spec_burst(
        lm, a, out_a, drafted_a, accepted_a, telem_a, room_a, spec_telem,
    )?;
    let keep_b = finish_pipelined_spec_burst(
        lm, b, out_b, drafted_b, accepted_b, telem_b, room_b, spec_telem,
    )?;
    Ok((keep_a, keep_b))
}

fn step_session(
    engine: &Engine,
    loaded: &HashMap<String, LoadedModel>,
    s: &mut Session,
    spec_telem: &mut HashMap<String, memra_engine::spec::SpecTelemetry>,
) -> Result<bool, Box<dyn std::error::Error>> {
    let lm = &loaded[&s.model];

    // ---- SPEC-BURST arm (2026-07-05): MTP sessions decode in generate_spec_session
    // bursts — turn 1 primes the prompt (suffix = the whole prefill queue), later ticks are
    // ZERO-prime continuation bursts (SpecSession.next_pred). Each burst emits up to
    // SPEC_BURST_T tokens; between bursts the scheduler round-robins other sessions. Exactness:
    // GREEDY bursts — the session-gate oracle (4 turns incl empty-suffix) pins burst output ==
    // fresh greedy, byte-identical. SAMPLED bursts (temperature>0, `sampling` below) are
    // DISTRIBUTIONALLY exact instead: the rejection-sampling verify draws from the same
    // filtered/penalized target as plain sampled decode, but consumes its own Philox streams
    // (sess.sctr/uctr), so the token stream is reproducible per (seed, session) rather than
    // byte-equal to a plain-sampled run. That is the contract, not a gap.
    if let Some(spec) = s.spec.as_mut() {
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_start();
        }
        // Burst size trades round-robin latency (other sessions wait a whole burst) against
        // per-burst fixed cost. The dominant cost — the per-call draft-graph recapture,
        // measured ~16ms/burst on H100 q27 — is gone since 2026-08-01: the captured graph
        // persists on the SpecSession (spec.rs DraftGraphCtx) and later bursts replay it.
        // MEMRA_SPEC_BURST overrides for measurement; 32 = latency-safe default.
        let burst_t: usize = std::env::var("MEMRA_SPEC_BURST").ok()
            .and_then(|v| v.parse().ok()).unwrap_or(32);
        let k = s.spec_k;
        debug_assert!(k > 0, "plain sessions must not enter the spec round");
        let request_room = s.budget.saturating_sub(s.generated.len());
        if request_room == 0 { finish(s, StopReason::MaxNew); return Ok(false); }
        // The engine target is a scheduler cadence, not a public-output cap. Session mode may
        // return a cache-authoritative surplus token past this target; expose it when the request
        // still has room so worker generated/sampler/fed state stays aligned with SpecSession.
        let burst_target = request_room.min(burst_t);
        let suffix: Vec<u32> = s.prefill_queue.drain(..).collect();
        s.prefill_done = true;
        if suffix.is_empty() && spec.next_pred.is_none() && spec.pending_tok.is_none() {
            // nothing primed and nothing to prime — shouldn't happen (admit rejects empty prompts)
            finish(s, StopReason::MaxNew); return Ok(false);
        }
        let sampling = if s.sampler.temperature() > 0.0 {
            Some(memra_engine::spec::SpecSampling {
                temp: s.sampler.temperature(),
                seed: s.sampler.seed(),
                top_k: s.sampler.top_k() as i32,
                top_p: s.sampler.top_p(),
                min_p: s.sampler.min_p(),
                penalty_last_n: s.sampler.penalty_last_n(),
                penalty_repeat: s.sampler.penalty_repeat(),
                penalty_freq: s.sampler.penalty_freq(),
                penalty_present: s.sampler.penalty_present(),
            })
        } else { None };
        // SPEC x CONSTRAINED: greedy constrained bursts carry the grammar hook — verify-side
        // truncation + masked-argmax cut slots (engine contract; sampled never gets here).
        // Telemetry (lane/accept-telemetry): the session's counters are LIFETIME (a pool
        // resume carries prior requests' counts), so stash a copy and diff after the burst —
        // the delta is this burst's contribution, merged per-model for /metrics and summed
        // per-request for usage.spec.
        let telem_before = spec.telem;
        // SSE CADENCE (lane/sse-cadence, 2026-08-05): publish at ROUND cadence, not burst
        // cadence. Every committed id in the request-owned budget gets its own Event::Token;
        // UTF-8 fragments may make an individual event's text empty, but ids are never coalesced.
        // MEMRA_SSE_PER_BURST=1 retains the timing rollback (events wait for burst end), not the
        // old broken one-id-for-many-tokens event shape.
        let per_burst_emit = std::env::var("MEMRA_SSE_PER_BURST").as_deref() == Ok("1");
        // ADMISSION YIELD (lane/admission-latency, 2026-08-06): a request that arrives while
        // a burst is in flight used to wait the WHOLE burst out before the worker's tick-top
        // admission phase could even see it — contended first-text scaled with
        // MEMRA_SPEC_BURST (0.57s at B32, 1.67s at B128; sse-cadence VERDICT). The round-
        // boundary flush below now returns a continue-verdict: `false` (a request is waiting
        // in the cmd channel, PENDING_ADMITS > 0) ends the burst at the current round exactly
        // as if burst-count had been reached — burst size is content-neutral (spec-levers
        // battery), so this moves WHEN control returns, never what tokens say.
        // MEMRA_ADMIT_YIELD=0 = rollback seam (restores full-burst holds).
        let admit_yield = std::env::var("MEMRA_ADMIT_YIELD").as_deref() != Ok("0");
        let tok_ref = &lm.tok;
        let mut decoded_visible = tok_ref.decode_bytes_special(&s.generated, true);
        let mut cursor = s.emitted_bytes;
        let mut emit_remaining = request_room;
        let mut eos_seen = false;
        let mut send_ok = true;
        let mut token_events = 0usize;
        let flush_tx = s.tx.clone();
        let eos_ids = s.params.eos.clone();
        let mut flush_cb = |slice: &[u32]| -> bool {
            // Continue-verdict polled at EVERY round boundary (even empty/post-EOS flushes).
            let keep = !admit_yield
                || PENDING_ADMITS.load(std::sync::atomic::Ordering::Acquire) == 0;
            if per_burst_emit || eos_seen || emit_remaining == 0 || slice.is_empty() {
                // poll-only boundary: rollback seam / post-EOS (tokens never visible;
                // accounting happens post-burst) / nothing new committed this round.
                return keep;
            }
            if let Some(trace) = s.ttft.as_ref() {
                trace.mark_prime_end();
                trace.mark_first_decode();
            }
            if !send_ok {
                return keep; // client already gone — keep the cursor honest, stop sending
            }
            let emitted = emit_spec_token_events(
                slice,
                &mut emit_remaining,
                &mut decoded_visible,
                &mut cursor,
                &eos_ids,
                &mut eos_seen,
                |id| tok_ref.decode_bytes_special(&[id], true),
                |event| flush_tx.send(event).is_ok(),
            );
            token_events += emitted.sent;
            send_ok = emitted.send_ok;
            keep
        };
        let on_commit: Option<&mut dyn FnMut(&[u32]) -> bool> =
            if per_burst_emit && !admit_yield { None } else { Some(&mut flush_cb) };
        // Cold speculative sessions must enter decode with the same prompt state as the plain
        // policy they replace. Plain affinity stops at the stable live-turn boundary and primes
        // a sub-floor tail tokenwise; a monolithic spec prime can select different Step35 bytes.
        // Mirror only that first cold boundary. Warm continuation bursts remain zero-prime, and
        // MEMRA_AFFINITY=0 preserves the monolithic control arm.
        let prime_split = if spec.committed.is_empty()
            && !suffix.is_empty()
            && affinity_enabled()
            && (s.affinity.is_some()
                || plain_ckpt_nominatable(&suffix, &|t| lm.tok.token_is_control(t)))
        {
            plain_checkpoint_boundary(&suffix, &|t| lm.tok.token_is_control(t))
        } else {
            None
        };
        let (burst, d, a) = match s.constraint.as_mut() {
            Some(c) => {
                let mut g = crate::constrained::SpecGrammar::new(c, lm.eos_id);
                lm.model.generate_spec_session_constrained_prime_split(
                    engine, spec, &suffix, burst_target, k, sampling, Some(&mut g),
                    prime_split, on_commit)?
            }
            None => lm.model.generate_spec_session_sampled_prime_split(
                engine, spec, &suffix, burst_target, k, sampling, prime_split, on_commit)?,
        };
        drop(flush_cb);
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_end();
            if !burst.is_empty() {
                trace.mark_first_decode();
            }
        }
        let telem_delta = spec.telem.delta_since(&telem_before);
        spec_telem.entry(s.model.clone()).or_default().merge(&telem_delta);
        s.spec_rounds += telem_delta.rounds;
        s.spec_drafted += d;
        s.spec_accepted += a;
        if d > 0 {
            eprintln!("[spec-acc] ctx={} burst={}/{} cum={}/{}={:.3}",
                      s.fed.len() + suffix.len(), a, d, s.spec_accepted, s.spec_drafted,
                      s.spec_accepted as f64 / s.spec_drafted.max(1) as f64);
        }
        for &tok in &suffix { s.fed.push(tok); s.sampler.accept(tok); }
        let public_len = spec_visible_len(&burst, request_room, &eos_ids);
        let public_burst = &burst[..public_len];
        if per_burst_emit {
            let emitted = emit_spec_token_events(
                public_burst,
                &mut emit_remaining,
                &mut decoded_visible,
                &mut cursor,
                &eos_ids,
                &mut eos_seen,
                |id| tok_ref.decode_bytes_special(&[id], true),
                |event| s.tx.send(event).is_ok(),
            );
            token_events += emitted.sent;
            send_ok = emitted.send_ok;
        }
        if send_ok {
            debug_assert_eq!(token_events, public_len, "one token event per public spec token");
        }
        let mut stop: Option<StopReason> = None;
        for &tok in public_burst {
            s.sampler.accept(tok);
            s.generated.push(tok);
            s.fed.push(tok);
            if s.params.eos.contains(&tok) { stop = Some(StopReason::Eos); break; }
        }
        // EOS text is never streamed (serve-compat, 2026-08-03), but its empty-text token event
        // keeps the id/event/generated receipt 1:1. Engine-committed budget surplus remains only
        // in SpecSession committed/pending state; it never enters these public worker vectors.
        s.tokens_emitted += token_events;
        s.emitted_bytes = cursor;
        if !send_ok {
            // DISCONNECT ABORT (gap-scan F8): an in-burst flush hit a closed channel —
            // client gone, retire at the abort point (state consistent post-burst).
            abort_log(s);
            return Ok(false);
        }
        let full = String::from_utf8_lossy(&decoded_visible);
        if stop.is_none() && !s.stop_strings.is_empty()
            && s.stop_strings.iter().any(|ss| full.contains(ss.as_str())) {
            stop = Some(StopReason::Callback);
        }
        if stop.is_none() && s.generated.len() >= s.budget { stop = Some(StopReason::MaxNew); }
        // +3 (was +2): committed excludes a carried pending token (pending-carry, 2026-08-01).
        if stop.is_none() && spec.committed.len() + k + 3 >= spec.cache_max_ctx() {
            stop = Some(StopReason::ContextFull);
        }
        if let Some(r) = stop { finish(s, r); return Ok(false); }
        return Ok(true);
    }

    // ---- prefill phase: BATCHED chunk prime (2026-07-05). prime_cache now supports
    // continuation (cache.pos > 0 attends to the quantized past), so the worker primes up to
    // PREFILL_TICK_T prompt tokens per tick at prefill throughput (~2000-5900 tok/s) instead of
    // one decode_step (~38-100 tok/s) — a 32k prompt drops from ~15min of ticks to ~a minute,
    // while the per-tick cap keeps round-robin latency for concurrent sessions bounded.
    // Tails below PRIME_MIN_T keep the tokenwise decode_step path (prime_cache floor).
    if !s.prefill_done {
        if let Some(trace) = s.ttft.as_ref() {
            trace.mark_prime_start();
        }
        let q = s.prefill_queue.len();
        // EAGER-ONLY prime shape (lane/gemma4-serve-gaps): same law as prefill_tick —
        // gemma4 primes fresh prompts WHOLE (no chunked prime in the engine; chunk 2 used
        // to kill the worker) and carried suffixes tokenwise (no continuation prime).
        let eager_mono = eager_only_model(lm);
        let carried = s.cache.as_ref().is_some_and(|c| c.pos > 0);
        if !confidence_trace_enabled()
            && q >= memra_engine::hybrid_forward::PRIME_MIN_T.max(2)
            && !(eager_mono && carried)
        {
            // leave a tail chunk >= PRIME_MIN_T if this tick doesn't finish the queue
            let mut take = if eager_mono { q } else { q.min(PREFILL_TICK_T) };
            if q - take > 0 && q - take < memra_engine::hybrid_forward::PRIME_MIN_T { take = q; }
            let chunk: Vec<u32> = s.prefill_queue.drain(..take).collect();
            // REQUEST-LEVEL seq_end: the rest of prefill_queue is the same request's remainder
            // (see prefill_tick — the tick-budget segmentation must not steer arithmetic).
            let (l, _h, _x) = lm.model.prime_cache(engine, &chunk, s.cache.as_mut().unwrap(),
                                                   s.prefill_queue.len())?;
            s.last_logits = l;
            for &tok in &chunk { s.fed.push(tok); s.sampler.accept(tok); }
        } else if let Some(tok) = s.prefill_queue.pop_front() {
            s.last_logits = lm.model.decode_step(engine, tok, s.cache.as_mut().unwrap())?;
            if let Some(&target) = s.prefill_queue.front() {
                write_confidence_trace(s, tok, target, &s.last_logits)?;
            }
            s.fed.push(tok);
            s.sampler.accept(tok);
        }
        if s.prefill_queue.is_empty() {
            s.prefill_done = true;
            if let Some(trace) = s.ttft.as_ref() {
                trace.mark_prime_end();
            }
        }
        // If after this the prompt is fully primed AND budget==0, we still fall through to decode
        // (which will immediately hit MaxNew). Keep prefill and decode as distinct ticks otherwise.
        return Ok(true);
    }

    // ---- decode phase ----
    if s.generated.len() >= s.budget {
        finish(s, StopReason::MaxNew);
        return Ok(false);
    }
    // CONSTRAINED rows host-sample from a grammar-masked copy (same seam as
    // advance_sample_emit — the batched path; kept in lockstep).
    let next = match (s.device_next.take(), s.constraint.as_mut()) {
        (Some(t), _) => t,
        (None, Some(c)) => {
            let mut row = s.last_logits.clone();
            c.mask_logits(&mut row).map_err(|e| format!("constraint mask: {e}"))?;
            s.sampler.sample(&row)
        }
        (None, None) => s.sampler.sample(&s.last_logits),
    };
    s.sampler.accept(next);
    s.generated.push(next);
    if let Some(trace) = s.ttft.as_ref() {
        trace.mark_first_decode();
    }

    // EOS stop (before streaming the EOS token as text — we still report it in the count).
    if s.params.eos.contains(&next) {
        if !send_token_event(s, next, String::new()) {
            abort_log(s);
            return Ok(false);
        }
        finish(s, StopReason::Eos);
        return Ok(false);
    }
    if let Some(c) = s.constraint.as_mut() {
        c.consume(next).map_err(|e| format!("constraint advance: {e}"))?;
    }

    // Detokenize the full generated tail, compute the incremental text delta vs what we've emitted.
    let decoded = lm.tok.decode_bytes_special(&s.generated, true);
    let delta = utf8_delta(&decoded, &mut s.emitted_bytes);
    let full = String::from_utf8_lossy(&decoded);
    // DISCONNECT ABORT (gap-scan F8): failed send = client gone, retire at the abort point.
    if !send_token_event(s, next, delta) {
        abort_log(s);
        return Ok(false);
    }

    // stop-string match on the detokenized tail.
    if !s.stop_strings.is_empty() && s.stop_strings.iter().any(|ss| full.contains(ss.as_str())) {
        finish(s, StopReason::Callback);
        return Ok(false);
    }

    // context guard.
    if s.cache.as_ref().map(|c| c.pos >= c.max_ctx).unwrap_or(false) {
        finish(s, StopReason::ContextFull);
        return Ok(false);
    }

    // produce next logits (the ONE decode_step that advances this session).
    s.last_logits = lm.model.decode_step(engine, next, s.cache.as_mut().unwrap())?;
    s.fed.push(next);
    Ok(true)
}

fn confidence_trace_enabled() -> bool {
    std::env::var("MEMRA_CONFIDENCE_TRACE").is_ok()
}

#[derive(Debug)]
struct ConfidenceSummary {
    reference_logprob: f64,
    top1_token: u32,
    top1_correct: bool,
    top1_top2_margin: f32,
    entropy: f64,
}

fn summarize_confidence(logits: &[f32], target: u32) -> Result<ConfidenceSummary, String> {
    let target = target as usize;
    if logits.is_empty() || target >= logits.len() {
        return Err(format!("target token {target} outside {} logits", logits.len()));
    }
    let mut top1 = (0usize, f32::NEG_INFINITY);
    let mut top2 = f32::NEG_INFINITY;
    for (index, &logit) in logits.iter().enumerate() {
        if logit > top1.1 {
            top2 = top1.1;
            top1 = (index, logit);
        } else if logit > top2 {
            top2 = logit;
        }
    }
    let max_logit = top1.1 as f64;
    let mut sum_exp = 0.0f64;
    let mut weighted_logit = 0.0f64;
    for &logit in logits {
        let exp = ((logit as f64) - max_logit).exp();
        sum_exp += exp;
        weighted_logit += exp * logit as f64;
    }
    let logsumexp = max_logit + sum_exp.ln();
    Ok(ConfidenceSummary {
        reference_logprob: logits[target] as f64 - logsumexp,
        top1_token: top1.0 as u32,
        top1_correct: top1.0 == target,
        top1_top2_margin: top1.1 - top2,
        entropy: logsumexp - weighted_logit / sum_exp,
    })
}

fn write_confidence_trace(
    session: &Session,
    input_token: u32,
    target_token: u32,
    logits: &[f32],
) -> Result<(), Box<dyn std::error::Error>> {
    let Ok(path) = std::env::var("MEMRA_CONFIDENCE_TRACE") else { return Ok(()) };
    let summary = summarize_confidence(logits, target_token).map_err(std::io::Error::other)?;
    let record = serde_json::json!({
        "format": "memra-token-confidence-v1",
        "trace_id": session.trace_id,
        "input_position": session.fed.len(),
        "input_token": input_token,
        "target_token": target_token,
        "reference_logprob": summary.reference_logprob,
        "top1_token": summary.top1_token,
        "top1_correct": summary.top1_correct,
        "top1_top2_margin": summary.top1_top2_margin,
        "entropy": summary.entropy,
    });
    let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
    writeln!(file, "{record}")?;
    Ok(())
}

/// DISCONNECT ABORT metering record (gap-scan F8): one log line per aborted session —
/// prompt/cached/generated at the abort point (bill-to-abort). Called from every
/// send-failure retire; the tick-top sweep prints the same shape.
fn abort_log(s: &Session) {
    eprintln!("[abort] client disconnected: model {:?}, prompt {} ({} cached), \
               {} generated — billed to abort point, {:.2}s",
              s.model, s.n_prompt, s.n_cached, s.generated.len(),
              s.t0.elapsed().as_secs_f64());
}

fn finish(s: &Session, reason: StopReason) {
    let elapsed = s.t0.elapsed().as_secs_f64();
    assert_eq!(
        s.tokens_emitted,
        s.generated.len(),
        "terminal token receipt mismatch: Event::Token count != generated count",
    );
    // constrained-session mask-cost receipt (the perf ledger line): steps + total/mean
    // host-side mask compute time. Unconstrained sessions log nothing.
    if let Some(c) = s.constraint.as_ref() {
        if c.steps > 0 {
            eprintln!("[constrained] {}: {} masked steps, mask total {:.2} ms ({:.3} ms/step)",
                      s.model, c.steps, c.mask_ns as f64 / 1e6,
                      c.mask_ns as f64 / 1e6 / c.steps as f64);
        }
        // DRAFT-SIDE MASKING receipt (lane/draft-mask): the speculative Matcher clone (one per
        // spec round) and the draft-position masks computed on it — the two costs the lane adds.
        if c.spec_clones > 0 {
            eprintln!("[draft-mask] {}: {} clones {:.2} ms ({:.3} ms/clone), \
                       {} draft masks {:.2} ms ({:.3} ms/mask)",
                      s.model, c.spec_clones, c.spec_ns as f64 / 1e6,
                      c.spec_ns as f64 / 1e6 / c.spec_clones as f64,
                      c.draft_masks, c.draft_mask_ns as f64 / 1e6,
                      c.draft_mask_ns as f64 / 1e6 / c.draft_masks.max(1) as f64);
        }
    }
    let reason = format!("{reason:?}");
    // Per-request spec acceptance summary (lane/accept-telemetry): only when this request
    // actually ran spec rounds — plain sessions carry None and the usage block is unchanged.
    let spec = (s.spec_rounds > 0).then(|| SpecUsage {
        rounds: s.spec_rounds,
        drafted: s.spec_drafted as u64,
        accepted: s.spec_accepted as u64,
    });
    let _ = s.tx.send(Event::TokenSnapshot(s.generated.clone()));
    let _ = s.tx.send(Event::Done {
        stop_reason: reason,
        n_tokens: s.generated.len(),
        n_prompt: s.n_prompt,
        n_cached: s.n_cached,
        elapsed_s: elapsed,
        spec,
    });
}

/// FAULT INJECTION (`MEMRA_PANIC_AFTER=<n>`, off unless set): panic the GPU worker thread
/// after `n` served requests. An explicitly-blocked experimental door in the flags-doctrine
/// sense, and the ONLY way the G5 supervision path can be exercised against a REAL CUDA
/// worker — the alternative is trusting that a catch_unwind + respawn + exit-70 ladder built
/// around a live CUDA context behaves the way its unit tests (which use a fake worker) say it
/// does. That trust was already misplaced once on this lane: the first supervisor deadlocked
/// startup, and only a live gate found it. Costs one relaxed atomic load per completed request.
///
/// ONE-SHOT PER PROCESS. `n_completed` is per-`run()`, so a per-run trigger re-fires on the
/// respawned worker the moment it serves its first request — measured: the respawn reloaded
/// the weights, went green with `generation:1`, then immediately panicked again and exited 70,
/// which makes "did the recovery actually serve traffic?" unanswerable. Injecting exactly one
/// panic per process is what proves the recovery half.
fn panic_after() -> Option<u64> {
    static P: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
    *P.get_or_init(|| std::env::var("MEMRA_PANIC_AFTER").ok().and_then(|v| v.parse().ok()))
}

/// Set once the injected panic has fired, so it fires at most once per process (see above).
static PANIC_INJECTED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// True exactly once, on the `n`th completed request of the process's first worker run.
fn panic_injection_due(n_completed: u64) -> bool {
    match panic_after() {
        Some(n) if n_completed >= n =>
            !PANIC_INJECTED.swap(true, std::sync::atomic::Ordering::SeqCst),
        _ => false,
    }
}

/// Number of respawn attempts after a worker-thread PANIC before the process fails loudly.
/// ONE, deliberately: CUDA errors are sticky per process (after an OOM or an Xid the context
/// is poisoned), so an in-process retry is a long shot — worth exactly one try, because when
/// it works it saves a ~120 s weight reload, and worth no more, because a respawn loop against
/// a poisoned context is a box that looks alive and serves nothing. MEMRA_WORKER_RESPAWN=0
/// disables (straight to loud failure, i.e. let the supervisor restart the process).
const WORKER_RESPAWN_MAX: u32 = 1;

/// Base delay for the respawn ladder and the HTTP retry hint while the worker is unavailable.
pub(crate) const WORKER_RESPAWN_BACKOFF_BASE_S: u64 = 2;

fn worker_respawn_max() -> u32 {
    static R: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
    *R.get_or_init(|| std::env::var("MEMRA_WORKER_RESPAWN").ok()
        .and_then(|v| v.parse().ok()).unwrap_or(WORKER_RESPAWN_MAX))
}

/// Exit code when the worker is unrecoverable. `systemd Restart=on-failure` treats any nonzero
/// as failure; 70 is sysexits' EX_SOFTWARE, so an operator reading `systemctl status` can tell
/// "the engine died" from "bad config" (exit 1, the startup FATAL paths in main).
const EXIT_WORKER_UNRECOVERABLE: i32 = 70;

/// Convenience: spawn the worker thread and block until it reports ready (or fails). Returns the
/// command Sender (clone into the axum state) + the loaded model names + template caps.
///
/// SUPERVISION (G5c, lane/serve-hardening 2026-08-06). The worker thread used to be a bare
/// `spawn(move || run(..))`: a panic inside it unwound that thread ONLY, the process kept
/// serving HTTP, `/health` stayed green forever, and every request blocked or died on a closed
/// channel. Now the spawned thread is a SUPERVISOR that:
///   1. runs the scheduler inside `catch_unwind`, so a panic is caught instead of silently
///      ending the thread;
///   2. marks the shared health FAULTED on catch — /health and /readyz flip within
///      milliseconds, no staleness threshold to wait out;
///   3. attempts `worker_respawn_max()` respawns with backoff (weights reload; the health
///      generation counter increments so the recovery is observable);
///   4. and if that fails, exits the PROCESS loudly — because a memra-server without a GPU
///      worker cannot serve anything, and `Restart=` restarting the unit whole is the only
///      reliable CUDA recovery (see `deploy/systemd/memra-server.service`).
/// A CLEAN return (the command channel closed = every HTTP handler dropped = shutdown) is not
/// a fault and never respawns.
#[allow(clippy::type_complexity)]
pub fn spawn(models: Vec<(String, String, Option<String>)>, health: crate::health::SharedHealth)
    -> Result<(
        Sender<Cmd>,
        Arc<Vec<String>>,
        Arc<HashMap<String, ModelCaps>>,
        SharedMetrics,
        std::thread::JoinHandle<()>,
    ), String> {
    // (#87's parse-time spec-over-PP-2 preflight refusal lived here — CLOSED 2026-08-08.
    // The ppN reverse-publication fences make spec+PP-2 serve; receipts and the crash gate
    // are in research/pp2spec-crash-20260807/.)
    let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<Cmd>();
    let (ready_tx, ready_rx) =
        std::sync::mpsc::channel::<Result<(Vec<String>, HashMap<String, ModelCaps>), String>>();
    let metrics: SharedMetrics = Default::default();
    let m2 = metrics.clone();
    let h2 = health.clone();
    let worker_thread = std::thread::Builder::new()
        .name("memra-gpu-worker".into())
        .spawn(move || {
            // The supervisor OWNS the receiver across restarts: `run` borrows it, so a
            // panicking scheduler cannot take the command channel down with it (dropping the
            // Receiver would make every future handler send fail with no way back).
            let rx = cmd_rx;
            let mut ready_tx = Some(ready_tx);
            let mut attempt: u32 = 0;
            loop {
                let (models, m, h) = (models.clone(), m2.clone(), h2.clone());
                // A fresh ready channel per attempt; only the FIRST one is the caller's.
                //
                // THE VERDICT MUST BE RELAYED CONCURRENTLY, NOT AFTER `run` RETURNS. `run`
                // sends its load verdict and then blocks in the scheduler for the life of the
                // process — so reading `rrx` on this thread after `catch_unwind` deadlocks the
                // whole server: main blocks in `ready_rx.recv()`, never binds the socket, and
                // the box loads the model and then answers nothing. (Found by serve-smoke,
                // which timed out waiting for /health with the worker log showing a fully
                // loaded model — the exact failure class this lane exists to remove, so it is
                // fitting that the gate caught it.)
                let (rtx, rrx) = std::sync::mpsc::channel();
                let caller = ready_tx.take();
                let load_failed = Arc::new(std::sync::atomic::AtomicBool::new(false));
                let (lf, hr) = (load_failed.clone(), h2.clone());
                let relay = std::thread::Builder::new()
                    .name("memra-worker-ready".into())
                    .spawn(move || {
                        let verdict = rrx.recv()
                            .unwrap_or_else(|_| Err("worker died during init".into()));
                        if let Err(why) = &verdict {
                            lf.store(true, std::sync::atomic::Ordering::SeqCst);
                            hr.mark_dead(format!("model load failed: {why}"));
                        }
                        // Only the first attempt has a caller waiting; a respawn's verdict is
                        // observable on /health (phase + generation) instead.
                        if let Some(tx) = caller {
                            let _ = tx.send(verdict);
                        }
                    });
                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    run(models, &rx, rtx, m, h)
                }));
                // `run` has returned, so its `rtx` is dropped and the relay cannot block.
                if let Ok(t) = relay { let _ = t.join(); }
                match outcome {
                    Ok(()) if load_failed.load(std::sync::atomic::Ordering::SeqCst) => {
                        // Not a shutdown: the model load itself failed, so `run` returned
                        // without ever entering the scheduler.
                        if attempt == 0 {
                            // The caller (main) got the error and reports it as a startup
                            // FATAL — do not race it with an exit code of our own.
                            return;
                        }
                        eprintln!("[worker] FATAL: respawn attempt {attempt} could not reload \
                                   the models — exiting the process so the supervisor can \
                                   restart it whole");
                        crate::health::sd_notify("STATUS=respawn load failed; exiting");
                        std::io::stderr().flush().ok();
                        std::process::exit(EXIT_WORKER_UNRECOVERABLE);
                    }
                    Ok(()) => {
                        // Clean scheduler exit = the command channel closed (shutdown).
                        h2.set_phase(crate::health::PHASE_DEAD);
                        return;
                    }
                    Err(payload) => {
                        // QUOTED, never inferred: the panic message as the panic handler saw
                        // it (String / &str payloads; anything else says so).
                        let why = payload.downcast_ref::<String>().cloned()
                            .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
                            .unwrap_or_else(|| "non-string panic payload".into());
                        attempt += 1;
                        h2.mark_dead(format!("worker thread panicked: {why}"));
                        eprintln!("[worker] PANIC in the GPU worker thread: {why}");
                        if attempt > worker_respawn_max() {
                            eprintln!("[worker] FATAL: worker unrecoverable after {} respawn \
                                       attempt(s) — exiting the process so the supervisor can \
                                       restart it whole (CUDA errors are sticky per process; a \
                                       live HTTP listener with a dead worker serves nothing)",
                                      attempt - 1);
                            crate::health::sd_notify("STATUS=worker unrecoverable; exiting");
                            std::io::stderr().flush().ok();
                            std::process::exit(EXIT_WORKER_UNRECOVERABLE);
                        }
                        // Backoff before reloading weights: a panic caused by a transient
                        // device condition needs the driver to settle, and an immediate
                        // reload would just re-hit it.
                        let backoff = std::time::Duration::from_secs(
                            WORKER_RESPAWN_BACKOFF_BASE_S * attempt as u64);
                        eprintln!("[worker] respawn attempt {attempt}/{} in {:?} \
                                   (reloading weights)", worker_respawn_max(), backoff);
                        std::thread::sleep(backoff);
                        h2.mark_respawning();
                    }
                }
            }
        })
        .map_err(|e| format!("spawn worker thread: {e}"))?;
    match ready_rx.recv() {
        Ok(Ok((names, caps))) => Ok((
            cmd_tx,
            Arc::new(names),
            Arc::new(caps),
            metrics,
            worker_thread,
        )),
        Ok(Err(err)) => Err(err),
        Err(_) => Err("worker died during init".into()),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        emit_spec_token_events, interactive_prefill_budget, record_output_progress,
        spec_visible_len, summarize_confidence, utf8_delta, Event,
    };
    use super::{
        PoolKey, PrefixCache, PrefixEntry, PrefixFanoutCandidate, PrefixFanoutGroup,
        PREFIX_CACHE_MIN_TOKENS, prefix_fanout_groups, retire_prefix_pin,
    };
    use super::{meter_account, meter_cached_credit, HashMap, METER_TENANT_CAP};
    use super::{
        AdsdDetector, ADSD_MIN_RATE_DROP, ADSD_SUSTAINED_OBSERVATIONS,
        ADSD_TENANT_WINDOW, ADSD_Z_THRESHOLD,
    };
    use super::{draft_verdict, draft_verdict_message, DraftVerdict};
    use super::{
        admission_reserve, alloc_with_single_reclaim_retry, context_cache_bytes, is_cuda_oom,
        oldest_parked_candidate, request_ctx_cap, AdmissionCostModel, ParkedCandidate,
        ParkedPool, MAX_NEW_CTX_BOUNDED, SPEC_SHRINK_RESERVE,
    };
    use super::{
        choose_spec_k, parse_spec_k_pin, resolve_spec_gate_thresholds, spec_gate_defaults,
        SpecKDecision, SpecKReason, SPEC_K_CACHED_LONG, SPEC_K_COLD_LONG, SPEC_K_COLD_SHORT,
        SPEC_K_LONG_CACHE_MIN, SPEC_K_LONG_PROMPT_MIN,
    };
    use super::{optipipe_controller_threshold, worker_device};
    use crate::lanes::{Lane, StepStats};

    fn ascii_decode(id: u32) -> Vec<u8> {
        vec![b'a' + id as u8]
    }

    #[test]
    fn admission_cost_scales_with_each_requests_context() {
        let cost = AdmissionCostModel {
            plain_bytes_per_token: 12_288,
            spec_bytes_per_token: 16_384,
            plain_ring_bytes_per_token: 0,
            spec_ring_bytes_per_token: 0,
            ring_rows: 0,
            activation_bytes: 64 << 20,
            last_logged: None,
        };
        let cost_128k = cost.estimate(131_072, false);
        let cost_256k = cost.estimate(262_144, false);

        assert_ne!(cost_128k, cost_256k, "128k must not inherit a 256k scalar");
        assert_eq!(
            cost_256k - cost_128k,
            cost.plain_bytes_per_token * 131_072,
        );
        assert_eq!(
            cost.estimate(131_072, true) - cost_128k,
            (cost.spec_bytes_per_token - cost.plain_bytes_per_token) * 131_072,
            "the spec scratch coefficient is charged only on the spec-shaped path",
        );
    }

    #[test]
    fn admission_caps_only_the_step35_swa_byte_class() {
        let ctx = 262_144;
        let rows = 512 + 4096 + 31;
        let full = 83_520usize;
        let swa = 61_248usize;
        let got = context_cache_bytes(full, swa, rows, ctx);
        let expected = (full - swa) * ctx + swa * rows;
        assert_eq!(got, expected);
        assert!(got * 3 < full * ctx, "the physical cache must deliver the ~3.5x geometry");
    }

    #[test]
    fn plain_reserve_is_capped_at_the_measured_transient_floor() {
        // Below the floor: byte-identical to the old `reserve = cost` contract (the
        // admit-oom no-regression cell — small models, c<=64).
        let small_cost = 192 << 20;
        assert_eq!(admission_reserve(false, small_cost, None), small_cost);
        // At a 262,144-token Step-3.7-Flash charge (21,894 MB) the plain path must NOT
        // reserve a second whole session; it pays the same measured constant the spec
        // path pays, because the plain transient class is chunk-bounded, not ctx-scaled.
        let big_cost = 21_894 << 20;
        assert_eq!(admission_reserve(false, big_cost, None), SPEC_SHRINK_RESERVE);
        assert!(SPEC_SHRINK_RESERVE < big_cost);
    }

    #[test]
    fn spec_reserve_keeps_the_full_transient_floor() {
        // The spec path's floor is independent of cost in BOTH directions: a small spec
        // request still reserves the full capture-arena transient…
        assert_eq!(admission_reserve(true, 64 << 20, None), SPEC_SHRINK_RESERVE);
        // …and a huge one adds nothing beyond it.
        assert_eq!(admission_reserve(true, 21_894 << 20, None), SPEC_SHRINK_RESERVE);
    }

    #[test]
    fn reserve_override_door_binds_both_paths() {
        // The teeth arm (MEMRA_ADMIT_RESERVE_MB) must be able to force a tiny reserve on
        // whichever path the stress gate exercises, or the teeth prove nothing.
        let forced = 16 << 20;
        assert_eq!(admission_reserve(true, 21_894 << 20, Some(forced)), forced);
        assert_eq!(admission_reserve(false, 21_894 << 20, Some(forced)), forced);
        // A plain request smaller than the forced floor still pays only its own cost.
        assert_eq!(admission_reserve(false, 8 << 20, Some(forced)), 8 << 20);
    }

    #[test]
    fn admission_activation_residual_is_a_high_water_not_a_new_scalar() {
        let mut cost = AdmissionCostModel {
            plain_bytes_per_token: 4_096,
            spec_bytes_per_token: 6_144,
            plain_ring_bytes_per_token: 0,
            spec_ring_bytes_per_token: 0,
            ring_rows: 0,
            activation_bytes: 0,
            last_logged: None,
        };
        let ctx_8k = 8_192;
        let linear_8k = cost.plain_bytes_per_token * ctx_8k;

        assert_eq!(cost.observe(linear_8k + 32_000_000, ctx_8k, false), Some(32_000_000));
        assert_eq!(cost.observe(linear_8k + 8_000_000, ctx_8k, false), None);
        assert_eq!(cost.activation_bytes, 32_000_000, "the residual never moves down");
        assert_eq!(
            cost.estimate(131_072, false),
            cost.plain_bytes_per_token * 131_072 + 32_000_000,
            "an 8k observation contributes only its fixed residual to a later 128k request",
        );
    }

    #[test]
    fn admission_reclaim_selects_the_global_oldest_across_both_pools() {
        let now = std::time::Instant::now();
        let plain_key: PoolKey = ("model".into(), "plain-ns".into());
        let spec_key: PoolKey = ("model".into(), "spec-ns".into());
        let oldest = oldest_parked_candidate([
            ParkedCandidate {
                pool: ParkedPool::Plain,
                key: plain_key,
                index: 0,
                parked_at: now - std::time::Duration::from_secs(2),
            },
            ParkedCandidate {
                pool: ParkedPool::Spec,
                key: spec_key.clone(),
                index: 1,
                parked_at: now - std::time::Duration::from_secs(3),
            },
            ParkedCandidate {
                pool: ParkedPool::Plain,
                key: ("model".into(), "newer-ns".into()),
                index: 2,
                parked_at: now - std::time::Duration::from_secs(1),
            },
        ]).expect("a parked candidate exists");

        assert_eq!(oldest.pool, ParkedPool::Spec);
        assert_eq!(oldest.key, spec_key);
        assert_eq!(oldest.index, 1);
        assert!(oldest_parked_candidate(Vec::new()).is_none());
    }

    #[test]
    fn cache_alloc_oom_reclaim_retries_exactly_once() {
        let attempts = std::cell::Cell::new(0usize);
        let reclaims = std::cell::Cell::new(0usize);
        let result: Result<(), &'static str> = alloc_with_single_reclaim_retry(
            || {
                attempts.set(attempts.get() + 1);
                Err("DriverError(CUDA_ERROR_OUT_OF_MEMORY, out of memory)")
            },
            |err| {
                assert!(is_cuda_oom(err));
                reclaims.set(reclaims.get() + 1);
                true // models one oldest parked entry released
            },
        );

        assert!(result.is_err());
        assert_eq!(attempts.get(), 2, "one initial allocation plus one retry");
        assert_eq!(reclaims.get(), 1, "reclaim runs only after the first failure");

        let non_oom_attempts = std::cell::Cell::new(0usize);
        let result: Result<(), &'static str> = alloc_with_single_reclaim_retry(
            || {
                non_oom_attempts.set(non_oom_attempts.get() + 1);
                Err("CUDA_ERROR_INVALID_VALUE")
            },
            |err| is_cuda_oom(err),
        );
        assert!(result.is_err());
        assert_eq!(
            non_oom_attempts.get(),
            1,
            "a failure without reclaimed state is not retried",
        );
    }

    #[test]
    fn admission_request_context_uses_the_requests_own_bound() {
        assert_eq!(
            request_ctx_cap(262_144, 262_144, 128, Some(131_072), 64),
            131_072,
            "an explicit 128k request must not inherit the 262k server default",
        );
        assert_eq!(request_ctx_cap(8_192, 262_144, 128, Some(4_096), 64), 4_096);
        assert_eq!(
            request_ctx_cap(8_192, 262_144, 260_000, None, MAX_NEW_CTX_BOUNDED),
            262_144,
            "omitted max_tokens uses the server default and remains model-capped",
        );
    }

    #[test]
    fn admission_finite_request_does_not_inherit_large_server_default() {
        assert_eq!(
            request_ctx_cap(262_144, 262_144, 8_120, None, 64),
            8_192,
            "a finite 8k request must be charged from prompt + output + margin",
        );
        assert_eq!(request_ctx_cap(8_192, 262_144, 128, None, 64), 200);
        let shape = super::RequestShape {
            ctx_cap: 45_466,
            budget: 32_768,
            need: 45_522,
        };
        assert_eq!(
            shape.admission_cap(),
            45_522,
            "the bounded affinity growth margin is charged to this request",
        );
    }

    #[test]
    fn spec_emission_keeps_intermediate_scheduler_surplus_public() {
        let requested_max = 64usize;
        let prior_generated: [u32; 0] = [];
        let burst_target = 32usize;
        let burst: Vec<u32> = (0..=burst_target as u32).collect();
        let request_room = requested_max - prior_generated.len();
        let public_len = spec_visible_len(&burst, request_room, &[]);
        let mut decoded = Vec::new();
        let mut cursor = 0usize;
        let mut remaining = request_room;
        let mut eos_seen = false;
        let mut events = Vec::new();
        let result = emit_spec_token_events(
            &burst,
            &mut remaining,
            &mut decoded,
            &mut cursor,
            &[],
            &mut eos_seen,
            ascii_decode,
            |event| {
                if let Event::Token { id, text } = event {
                    events.push((id, text));
                }
                true
            },
        );

        assert_eq!(burst.len(), burst_target + 1, "engine crossed its scheduler target");
        assert_eq!(public_len, burst.len(), "surplus still fits the request budget");
        assert_eq!(result.sent, burst.len());
        assert_eq!(events.len(), burst.len());
        assert_eq!(remaining, requested_max - burst.len());
    }

    #[test]
    fn spec_emission_clamps_engine_overshoot_to_the_request_budget() {
        let requested_max = 5usize;
        let prior_generated = [7, 8];
        let mut decoded: Vec<u8> = prior_generated.iter()
            .flat_map(|&id| ascii_decode(id)).collect();
        let mut cursor = decoded.len();
        let burst = [0, 1, 2, 3, 4]; // engine-committed cache truth, including surplus
        let request_room = requested_max - prior_generated.len();
        let public_len = spec_visible_len(&burst, request_room, &[]);
        let mut remaining = request_room;
        let mut eos_seen = false;
        let mut events = Vec::new();
        let result = emit_spec_token_events(
            &burst,
            &mut remaining,
            &mut decoded,
            &mut cursor,
            &[],
            &mut eos_seen,
            ascii_decode,
            |event| {
                if let Event::Token { id, text } = event {
                    events.push((id, text));
                }
                true
            },
        );

        assert_eq!(burst.len(), 5, "engine commit remains untouched");
        assert_eq!(public_len, 3);
        assert_eq!(prior_generated.len() + public_len, requested_max);
        assert_eq!(events.len(), request_room);
        assert_eq!(result.sent, request_room);
        assert_eq!(remaining, 0);
        assert_eq!(&burst[public_len..], &[3, 4], "surplus is not public output");
    }

    #[test]
    fn spec_emission_publishes_one_event_per_visible_token_id() {
        let burst = [0, 1, 9, 2];
        let mut remaining = burst.len();
        let mut decoded = Vec::new();
        let mut cursor = 0usize;
        let mut eos_seen = false;
        let mut events = Vec::new();
        let result = emit_spec_token_events(
            &burst,
            &mut remaining,
            &mut decoded,
            &mut cursor,
            &[9],
            &mut eos_seen,
            ascii_decode,
            |event| {
                if let Event::Token { id, text } = event {
                    events.push((id, text));
                }
                true
            },
        );

        assert_eq!(events, vec![(0, "a".into()), (1, "b".into()), (9, "".into())]);
        assert_eq!(result.sent, spec_visible_len(&burst, burst.len(), &[9]));
        assert!(result.send_ok);
        assert!(eos_seen);
    }

    #[test]
    fn spec_path_accounts_tokens_and_timing_per_emitted_token() {
        let mut total = 0u64;
        let mut lanes = [0u64; 3];
        let mut stats = StepStats::new(30.0);
        let old_decode = std::time::Instant::now() - std::time::Duration::from_secs(1);
        let mut last_decode = old_decode;

        let emitted = record_output_progress(
            10,
            14,
            Lane::Interactive,
            20.0,
            &mut total,
            &mut lanes,
            &mut stats,
            &mut last_decode,
        );

        assert_eq!(emitted, 4, "a four-token spec commit is not one output token");
        assert_eq!(total, 4);
        assert_eq!(lanes, [4, 0, 0]);
        assert_eq!(stats.p(50.0), Some(5.0), "20 ms / 4 emitted tokens");
        assert!(last_decode > old_decode);
    }

    #[test]
    fn legacy_round_robin_accounts_decode_but_not_prefill_steps() {
        let mut total = 0u64;
        let mut lanes = [0u64; 3];
        let mut stats = StepStats::new(30.0);
        let mut last_decode = std::time::Instant::now();

        assert_eq!(
            record_output_progress(
                0, 0, Lane::Interactive, 12.0, &mut total, &mut lanes, &mut stats,
                &mut last_decode,
            ),
            0,
        );
        assert_eq!(stats.p(50.0), None, "prefill-only calls are not output steps");
        assert_eq!(
            record_output_progress(
                0, 1, Lane::Interactive, 7.0, &mut total, &mut lanes, &mut stats,
                &mut last_decode,
            ),
            1,
        );
        assert_eq!(total, 1);
        assert_eq!(lanes, [1, 0, 0]);
        assert_eq!(stats.p(50.0), Some(7.0));
    }

    #[test]
    fn naked_solo_fresh_prefill_uses_one_bounded_outer_call() {
        assert_eq!(interactive_prefill_budget(1024, false, true, true, 4107), 4107);
        assert_eq!(interactive_prefill_budget(1024, false, true, true, 20_000), 8192);
        // Do not strand a sub-PRIME_MIN_T tail on the tokenwise path.
        assert_eq!(interactive_prefill_budget(1024, false, true, true, 8200), 8200);
    }

    #[test]
    fn solo_prefill_widening_preserves_operator_and_fairness_caps() {
        assert_eq!(interactive_prefill_budget(1024, true, true, true, 4107), 1024);
        assert_eq!(interactive_prefill_budget(1024, false, false, true, 4107), 1024);
        assert_eq!(interactive_prefill_budget(1024, false, true, false, 4107), 1024);
    }

    #[test]
    fn spec_gate_defaults_follow_placement() {
        assert_eq!(spec_gate_defaults(false), (2, 4));
        assert_eq!(spec_gate_defaults(true), (0, 1));
    }

    #[test]
    fn spec_gate_threshold_overrides_remain_explicit_and_clamped() {
        let pp2_c1 = resolve_spec_gate_thresholds(true, Some(1), Some(2));
        assert_eq!((pp2_c1.low, pp2_c1.high), (1, 2));
        assert!(pp2_c1.low_overridden);
        assert!(pp2_c1.high_overridden);
        assert!(!pp2_c1.high_clamped);

        let bad = resolve_spec_gate_thresholds(false, Some(4), Some(4));
        assert_eq!((bad.low, bad.raw_high, bad.high), (4, 4, 5));
        assert!(bad.high_clamped);
    }

    #[test]
    fn spec_k_pin_parsing_is_explicit_and_supports_plain() {
        assert_eq!(parse_spec_k_pin(None), Ok(None));
        assert_eq!(parse_spec_k_pin(Some("0")), Ok(Some(0)));
        assert_eq!(parse_spec_k_pin(Some("5")), Ok(Some(5)));
        assert!(parse_spec_k_pin(Some("all")).unwrap_err().contains("non-negative integer"));
        assert!(parse_spec_k_pin(Some("-1")).is_err());
    }

    #[test]
    fn spec_k_operator_pin_wins_over_every_policy_row() {
        let pp2 = resolve_spec_gate_thresholds(true, None, None);
        assert_eq!(
            choose_spec_k(Some(5), true, pp2, 8, 16, 0),
            SpecKDecision { k: 5, reason: SpecKReason::OperatorPin },
        );
        let single = resolve_spec_gate_thresholds(false, None, None);
        assert_eq!(
            choose_spec_k(Some(0), true, single, 1, 8192, 8192),
            SpecKDecision { k: 0, reason: SpecKReason::OperatorPin },
        );
    }

    #[test]
    fn spec_k_policy_maps_placement_and_concurrency_to_plain() {
        let pp2 = resolve_spec_gate_thresholds(true, None, None);
        assert_eq!(
            choose_spec_k(None, true, pp2, 1, 28, 0),
            SpecKDecision { k: 0, reason: SpecKReason::Placement },
        );

        let single = resolve_spec_gate_thresholds(false, None, None);
        assert_eq!(
            choose_spec_k(None, true, single, 3, 28, 0),
            SpecKDecision { k: 0, reason: SpecKReason::Concurrency },
        );

        // An explicit PP-2 threshold override restores the measured gate semantics:
        // c=1 may speculate; the next arrival is K=0.
        let pp2_c1 = resolve_spec_gate_thresholds(true, Some(1), Some(2));
        assert_eq!(
            choose_spec_k(None, true, pp2_c1, 1, 28, 0),
            SpecKDecision { k: SPEC_K_COLD_SHORT, reason: SpecKReason::ColdShort },
        );
        assert_eq!(
            choose_spec_k(None, true, pp2_c1, 2, 28, 0),
            SpecKDecision { k: 0, reason: SpecKReason::Concurrency },
        );
    }

    #[test]
    fn spec_k_prompt_cache_table_has_exact_boundaries() {
        assert_eq!(
            (SPEC_K_COLD_SHORT, SPEC_K_COLD_LONG, SPEC_K_CACHED_LONG),
            (3, 3, 2),
        );
        let single = resolve_spec_gate_thresholds(false, None, None);
        assert_eq!(
            choose_spec_k(None, true, single, 1, SPEC_K_LONG_PROMPT_MIN - 1, 9999),
            SpecKDecision { k: SPEC_K_COLD_SHORT, reason: SpecKReason::ColdShort },
        );
        assert_eq!(
            choose_spec_k(
                None, true, single, 1, SPEC_K_LONG_PROMPT_MIN, SPEC_K_LONG_CACHE_MIN - 1,
            ),
            SpecKDecision { k: SPEC_K_COLD_LONG, reason: SpecKReason::ColdLong },
        );
        assert_eq!(
            choose_spec_k(
                None, true, single, 1, SPEC_K_LONG_PROMPT_MIN, SPEC_K_LONG_CACHE_MIN,
            ),
            SpecKDecision { k: SPEC_K_CACHED_LONG, reason: SpecKReason::CachedLong },
        );
        // MEMRA_SPEC_GATE=0 retains its rollback meaning: placement/concurrency are
        // ignored, while the prompt/cache table remains active.
        assert_eq!(
            choose_spec_k(None, false, resolve_spec_gate_thresholds(true, None, None),
                          8, SPEC_K_LONG_PROMPT_MIN, SPEC_K_LONG_CACHE_MIN),
            SpecKDecision { k: SPEC_K_CACHED_LONG, reason: SpecKReason::CachedLong },
        );
    }

    #[test]
    fn worker_device_defaults_to_cuda_visible_zero_and_follows_the_pp_head_stage() {
        assert_eq!(worker_device(None), Ok(0));
        assert_eq!(worker_device(Some("")), Ok(0));
        // The primary follows the LAST stage (the lm head's device — the spec round's draft
        // chain reads it every token; see worker_device's doc). The 5f27c55c stage-0 pin was
        // the v0.72 tag-blocker-2 regressor: 112.5 -> 17.5 agg tok/s on spec+PP-2 serving.
        assert_eq!(worker_device(Some("1,0")), Ok(0));
        assert_eq!(worker_device(Some("0,1")), Ok(1));
        assert_eq!(worker_device(Some(" 3 , 4 ")), Ok(4));
    }

    #[test]
    fn worker_device_rejects_an_invalid_pp_device() {
        // EVERY position is validated (a bad string must refuse at boot, wherever it is).
        let err = worker_device(Some("gpu0,1")).unwrap_err();
        assert!(err.contains("invalid device"), "{err}");
        assert!(err.contains("gpu0"), "{err}");
        let err = worker_device(Some("1,gpu0")).unwrap_err();
        assert!(err.contains("gpu0"), "{err}");
    }

    #[test]
    fn optipipe_controller_door_is_absent_by_default_and_bounds_thresholds() {
        assert_eq!(optipipe_controller_threshold(None), Ok(None));
        assert_eq!(optipipe_controller_threshold(Some("0")), Ok(Some(0.0)));
        assert_eq!(optipipe_controller_threshold(Some("0.7")), Ok(Some(0.7)));
        assert_eq!(optipipe_controller_threshold(Some("1")), Ok(Some(1.0)));
        for invalid in ["-0.01", "1.01", "NaN", "not-a-number"] {
            let err = optipipe_controller_threshold(Some(invalid)).unwrap_err();
            assert!(err.contains("MEMRA_OPTI_CONTROLLER_Q"), "unexpected error: {err}");
        }
    }

    // ---- drafter attachment: the loud-failure semantics (lane/step-draft, 2026-08-07) ----
    //
    // These pin the class of bug that NO gate in this repo could catch: a step35 model served
    // without its external MTP drafter runs plain decode and produces CORRECT output, so
    // kernel-check is model-free, run-gen argmax MATCHes, and run-spec is never even reached.
    // Only a log line can flag it, so the log line is what gets tested.

    #[test]
    fn step35_without_drafter_warns_and_names_the_attach_spelling() {
        let v = draft_verdict(false, true);
        assert_eq!(v, DraftVerdict::NoDrafterExternalMtpArch);
        let msg = draft_verdict_message(&v, "step", "/m/Step-3.7-flash-IQ4_XS-00001-of-00003.gguf")
            .expect("a step35 model with no drafter MUST produce a line");
        // The defect is silence, so the line has to be findable and actionable.
        assert!(msg.contains("no MTP drafter attached"), "{msg}");
        assert!(msg.contains("plain decode"), "{msg}");
        // ACTIONABLE: the exact attach spelling, not just a complaint.
        assert!(msg.contains("MEMRA_MODELS"), "{msg}");
        assert!(msg.contains("+/path/to/"), "the '+draft' convention must be spelled: {msg}");
        // And it must not read as a defect in the artifact — nextn=0 is CORRECT here.
        assert!(msg.contains("SEPARATE GGUF"), "{msg}");
        assert!(msg.contains("does NOT mean"), "{msg}");
    }

    #[test]
    fn attached_drafter_is_quiet_and_so_is_a_non_step35_model_without_one() {
        // Attached: nothing to warn about; spec_eligible arbitrates per request from here.
        // (#87 CLOSED 2026-08-08: a drafter over sharded cross-device PP-2 used to refuse
        // here — the ppN reverse-publication fences made the regime serve, receipts
        // research/pp2spec-crash-20260807/. Attached is now unconditional.)
        let v = draft_verdict(true, true);
        assert_eq!(v, DraftVerdict::Attached);
        assert!(draft_verdict_message(&v, "step", "/m.gguf").is_none());

        // A non-step35 model with no head: `nextn=0` there genuinely means no head, and the
        // existing load line already says the layer count. Warning would be noise on every
        // plain model the server has ever hosted — which is how a real warning gets ignored.
        let v = draft_verdict(false, false);
        assert_eq!(v, DraftVerdict::NoDrafterQuiet);
        assert!(draft_verdict_message(&v, "q27", "/m.gguf").is_none());
    }

    // (#87's refusal tests — `spec_over_sharded_pp_refuses_and_points_at_87`,
    // `the_quarantine_binds_only_where_all_three_conditions_hold`, and
    // `the_87_refusal_lands_before_the_load_when_a_draft_was_attached` — retired with the
    // quarantine itself, 2026-08-08. The regime they refused now serves: root cause was the
    // ppN reverse-publication hole, fixed by `PpNRt::fence_stages_behind`; crash gate
    // 212/212 at c=2..8, run-spec K=1..8 PASS. research/pp2spec-crash-20260807/.)

    /// Device-free PrefixEntry (empty kv/conv/ssm planes) — the namespace-visibility laws
    /// under test live entirely in the host-side key/toks matching.
    fn entry(toks: Vec<u32>) -> PrefixEntry {
        PrefixEntry {
            toks,
            kv: Vec::new(),
            conv: Vec::new(),
            ssm: Vec::new(),
            pos: 0,
            last_logits: vec![0.0],
            bytes: 1,
            last_use: std::time::Instant::now(),
            id: 0,
            pins: 0,
        }
    }

    fn key(ns: &str) -> PoolKey {
        ("m".to_string(), ns.to_string())
    }

    fn toks(n: usize) -> Vec<u32> {
        (0..n as u32).collect()
    }

    #[test]
    fn prefix_fanout_groups_only_inside_exact_model_tenant_and_salt() {
        let mut a = toks(96);
        a.extend([10_001, 10_002]);
        let mut b = toks(96);
        b.extend([20_001, 20_002, 20_003]);
        let mut other_prefix = toks(96);
        other_prefix[63] = u32::MAX;
        let acme_s1 = crate::auth::scope_namespace("acme", "s1");
        let candidates = vec![
            PrefixFanoutCandidate {
                active_idx: 3,
                key: ("m".into(), acme_s1.clone()),
                prompt: a,
            },
            PrefixFanoutCandidate {
                active_idx: 7,
                key: ("m".into(), acme_s1.clone()),
                prompt: b,
            },
            PrefixFanoutCandidate {
                active_idx: 8,
                key: ("m".into(), crate::auth::scope_namespace("acme", "s2")),
                prompt: toks(96),
            },
            PrefixFanoutCandidate {
                active_idx: 9,
                key: ("m".into(), crate::auth::scope_namespace("blue", "s1")),
                prompt: toks(96),
            },
            PrefixFanoutCandidate {
                active_idx: 10,
                key: ("other-model".into(), acme_s1.clone()),
                prompt: toks(96),
            },
            PrefixFanoutCandidate {
                active_idx: 11,
                key: ("m".into(), acme_s1),
                prompt: other_prefix,
            },
        ];
        assert_eq!(
            prefix_fanout_groups(&candidates, 80),
            vec![PrefixFanoutGroup {
                members: vec![3, 7],
                prefix_len: 80,
            }],
        );
        assert!(prefix_fanout_groups(&candidates, PREFIX_CACHE_MIN_TOKENS - 1).is_empty());
    }

    #[test]
    fn prefix_fanout_rewrites_one_provisional_miss_exactly_once() {
        let mut px = PrefixCache::default();
        px.misses = 2;
        px.record_lcp(0);
        px.record_lcp(0);
        px.promote_miss_to_hit(0, 256);
        assert_eq!(px.misses, 1);
        assert_eq!(px.hits, 1);
        assert_eq!(px.hit_tokens, 256);
        assert_eq!(px.lcp_hist[PrefixCache::lcp_bucket(0)], 1);
        assert_eq!(px.lcp_hist[PrefixCache::lcp_bucket(256)], 1);
        assert_eq!(px.lcp_hist.iter().sum::<u64>(), 2);
    }

    #[test]
    fn prefix_cache_same_namespace_same_prefix_hits() {
        let mut px = PrefixCache::default();
        let prefix = toks(PREFIX_CACHE_MIN_TOKENS);
        px.insert(&key("tenant-a"), entry(prefix.clone()), "test");
        // same namespace + same prefix (prompt extends the entry) -> hit.
        assert!(px.lookup(&key("tenant-a"), &toks(PREFIX_CACHE_MIN_TOKENS + 32)).is_some());
        assert!(px.has_covering(&key("tenant-a"), &prefix));
        assert_eq!(px.best_lcp(&key("tenant-a"), &prefix), prefix.len());
    }

    /// LCP histogram bucketing (lane/cache-metering): edges are lower bounds, the last
    /// bucket is unbounded, and the [64,512) tick-seg window is exactly buckets 4..=6.
    #[test]
    fn lcp_histogram_buckets_are_lower_edge_and_record_samples() {
        assert_eq!(PrefixCache::lcp_bucket(0), 0);
        assert_eq!(PrefixCache::lcp_bucket(1), 1);
        assert_eq!(PrefixCache::lcp_bucket(15), 1);
        assert_eq!(PrefixCache::lcp_bucket(16), 2);
        assert_eq!(PrefixCache::lcp_bucket(63), 3);
        assert_eq!(PrefixCache::lcp_bucket(64), 4);   // tick-seg window opens
        assert_eq!(PrefixCache::lcp_bucket(127), 4);
        assert_eq!(PrefixCache::lcp_bucket(128), 5);
        assert_eq!(PrefixCache::lcp_bucket(256), 6);
        assert_eq!(PrefixCache::lcp_bucket(511), 6);  // tick-seg window closes
        assert_eq!(PrefixCache::lcp_bucket(512), 7);
        assert_eq!(PrefixCache::lcp_bucket(4095), 9);
        assert_eq!(PrefixCache::lcp_bucket(4096), 10);
        assert_eq!(PrefixCache::lcp_bucket(1 << 20), 10); // unbounded tail
        let mut px = PrefixCache::default();
        px.record_lcp(0);
        px.record_lcp(100);
        px.record_lcp(100);
        assert_eq!(px.lcp_hist[0], 1);
        assert_eq!(px.lcp_hist[4], 2);
        assert_eq!(px.lcp_hist.iter().sum::<u64>(), 3);
    }

    /// Per-tenant metering rows (lane/cache-metering): keyring namespaces collapse to
    /// their tenant (salts within a tenant share a row), raw salts pass through, and the
    /// row cap saturates into "(other)" without losing tokens.
    #[test]
    fn meter_account_keys_by_tenant_and_bounds_rows() {
        let mut m: HashMap<String, [u64; 2]> = HashMap::new();
        // keyring: two salts of one tenant share the row; another tenant gets its own.
        meter_account(&mut m, &crate::auth::scope_namespace("acme", "u1"), 100, 40);
        meter_account(&mut m, &crate::auth::scope_namespace("acme", "u2"), 50, 10);
        meter_account(&mut m, &crate::auth::scope_namespace("blue", ""), 30, 0);
        meter_cached_credit(&mut m, &crate::auth::scope_namespace("acme", "u3"), 25);
        assert_eq!(m["t:acme"], [150, 75]);
        assert_eq!(m["t:blue"], [30, 0]);
        // no keyring: the raw salt is the row key; "" is the default namespace.
        meter_account(&mut m, "session-7", 20, 20);
        meter_account(&mut m, "", 10, 5);
        assert_eq!(m["session-7"], [20, 20]);
        assert_eq!(m[""], [10, 5]);
        // cap: fill to METER_TENANT_CAP distinct rows, then overflow lands in "(other)"
        // while an EXISTING row keeps accumulating under its own key.
        let mut m: HashMap<String, [u64; 2]> = HashMap::new();
        for i in 0..METER_TENANT_CAP {
            meter_account(&mut m, &format!("s{i}"), 1, 0);
        }
        meter_account(&mut m, "one-too-many", 7, 3);
        meter_account(&mut m, "s0", 2, 1);
        assert_eq!(m.len(), METER_TENANT_CAP + 1);
        assert_eq!(m["(other)"], [7, 3]);
        assert_eq!(m["s0"], [3, 1]);
        // totals stay exact: sum over rows == sum over requests.
        let total: u64 = m.values().map(|r| r[0]).sum();
        assert_eq!(total, METER_TENANT_CAP as u64 + 7 + 2);
    }

    fn seed_adsd_baseline(detector: &mut AdsdDetector) {
        for i in 0..24u64 {
            let accepted = [70, 73, 71, 74][i as usize % 4];
            assert!(detector.observe("model-a", "t:baseline", accepted, 100).is_none());
        }
    }

    #[test]
    fn adsd_detector_fires_once_on_sustained_acceptance_collapse() {
        let mut detector = AdsdDetector::default();
        seed_adsd_baseline(&mut detector);

        let mut events = Vec::new();
        for _ in 0..(ADSD_TENANT_WINDOW + ADSD_SUSTAINED_OBSERVATIONS as usize + 4) {
            if let Some(event) = detector.observe("model-a", "t:attacker", 8, 100) {
                events.push(event);
            }
        }
        assert_eq!(events.len(), 1, "one sustained incident must not count every request");
        let event = &events[0];
        assert_eq!(event.tenant, "t:attacker");
        assert!(event.baseline_rate - event.tenant_rate >= ADSD_MIN_RATE_DROP);
        assert!(event.z_score <= ADSD_Z_THRESHOLD);
        assert_eq!(detector.suspect_total["t:attacker"], 1);
    }

    #[test]
    fn adsd_detector_does_not_fire_on_normal_acceptance_noise() {
        let mut detector = AdsdDetector::default();
        seed_adsd_baseline(&mut detector);

        for i in 0..64usize {
            let accepted = [65, 76, 69, 74, 71, 78, 67, 73][i % 8];
            assert!(
                detector.observe("model-a", "t:noisy", accepted, 100).is_none(),
                "ordinary acceptance variation must not become an ADSD incident",
            );
        }
        assert!(!detector.suspect_total.contains_key("t:noisy"));
    }

    #[test]
    fn prefix_cache_namespaces_isolate_both_directions() {
        let mut px = PrefixCache::default();
        let prompt = toks(PREFIX_CACHE_MIN_TOKENS + 32);
        // tenant-a seeds; the identical prefix is INVISIBLE to tenant-b and to the
        // default namespace (a -> b direction).
        px.insert(&key("tenant-a"), entry(toks(PREFIX_CACHE_MIN_TOKENS)), "test");
        assert!(px.lookup(&key("tenant-b"), &prompt).is_none());
        assert!(px.lookup(&key(""), &prompt).is_none());
        // ... and the learning/seed signals stay scoped too (no cross-ns LCP split).
        assert_eq!(px.best_lcp(&key("tenant-b"), &prompt), 0);
        assert!(!px.has_covering(&key("tenant-b"), &prompt));
        // tenant-b seeds its OWN copy (no cross-ns dedupe: has_key is per key) and hits
        // it, while tenant-a still hits only its own (b -> a direction).
        px.insert(&key("tenant-b"), entry(toks(PREFIX_CACHE_MIN_TOKENS)), "test");
        assert_eq!(px.n_entries(), 2);
        assert!(px.lookup(&key("tenant-a"), &prompt).is_some());
        assert!(px.lookup(&key("tenant-b"), &prompt).is_some());
        assert!(px.lookup(&key("tenant-c"), &prompt).is_none());
    }

    #[test]
    fn prefix_cache_default_namespace_preserves_single_tenant_behavior() {
        // No salt = the "" namespace on every request: inserts, covering dedupe, LCP
        // learning, and longest-match lookup all behave exactly as the pre-PC-ISO
        // model-keyed cache.
        let mut px = PrefixCache::default();
        let short = toks(PREFIX_CACHE_MIN_TOKENS);
        let long = toks(PREFIX_CACHE_MIN_TOKENS + 16);
        px.insert(&key(""), entry(short.clone()), "test");
        px.insert(&key(""), entry(long.clone()), "test");
        px.insert(&key(""), entry(long.clone()), "test"); // exact-key dedupe still holds
        assert_eq!(px.n_entries(), 2);
        // longest entry prefixing the prompt wins, floor PREFIX_CACHE_MIN_TOKENS.
        let hit = px.lookup(&key(""), &toks(PREFIX_CACHE_MIN_TOKENS + 64)).unwrap();
        assert_eq!(px.entries[&key("")][hit].toks.len(), long.len());
        assert!(px.lookup(&key(""), &toks(PREFIX_CACHE_MIN_TOKENS - 1)).is_none());
    }

    // ---------------- Q3 EVICTION (audit 2026-08-05): recency-index LRU ----------------
    //
    // The insert-time eviction loop moved from a per-victim full rescan (O(E) per victim —
    // the vLLM #50992 shape) to a BTreeMap recency index (O(log E)). POLICY must be
    // IDENTICAL: global minimum `last_use` (timestamp-LRU). These tests drive the real
    // cache and an in-test reimplementation of the OLD algorithm with the same recorded
    // access pattern and require the same victim sequence, plus a large-E flush smoke the
    // old quadratic loop could not pass.

    /// Entry with an explicit identity + byte size (identity = the single token, so the
    /// exact-key dedupe never collides and survivors are readable back out of the pools).
    fn entry_b(ident: u32, bytes: usize) -> PrefixEntry {
        PrefixEntry {
            toks: vec![ident],
            kv: Vec::new(),
            conv: Vec::new(),
            ssm: Vec::new(),
            pos: 0,
            last_logits: vec![0.0],
            bytes,
            last_use: next_instant(),
            id: 0,
            pins: 0,
        }
    }

    /// Strictly-monotonic clock step: spins (ns-resolution CLOCK_MONOTONIC — exits on the
    /// first or second read) until `Instant::now()` has advanced, so every recorded
    /// timestamp in the property test is distinct and the old algorithm's strict-<
    /// comparison has one unambiguous global minimum (the old tie-break was HashMap-order
    /// nondeterminism — distinct timestamps are the only pattern where its victim choice
    /// was even well-defined to compare against).
    fn next_instant() -> std::time::Instant {
        let t = std::time::Instant::now();
        loop {
            let u = std::time::Instant::now();
            if u > t {
                return u;
            }
        }
    }

    /// Old-algorithm reference model: (ident, bytes, logical last-use order) per entry;
    /// eviction re-picks the global minimum order until under budget — verbatim the
    /// pre-Q3 loop's semantics.
    struct OldModel {
        entries: Vec<(u32, usize, u64)>,
        total: usize,
        clock: u64,
        victims: Vec<u32>,
    }
    impl OldModel {
        fn insert(&mut self, ident: u32, bytes: usize, budget: usize) {
            if bytes > budget {
                return;
            }
            self.clock += 1;
            self.entries.push((ident, bytes, self.clock));
            self.total += bytes;
            while self.total > budget {
                let Some(&(v, b, _)) = self.entries.iter().min_by_key(|&&(_, _, o)| o) else {
                    break;
                };
                self.entries.retain(|&(i, _, _)| i != v);
                self.total -= b;
                self.victims.push(v);
            }
        }
        fn touch(&mut self, ident: u32) {
            self.clock += 1;
            if let Some(e) = self.entries.iter_mut().find(|e| e.0 == ident) {
                e.2 = self.clock;
            }
        }
        fn survivors(&self) -> Vec<u32> {
            let mut v: Vec<u32> = self.entries.iter().map(|e| e.0).collect();
            v.sort_unstable();
            v
        }
    }

    fn px_survivors(px: &PrefixCache) -> Vec<u32> {
        let mut v: Vec<u32> = px.entries.values().flatten().map(|e| e.toks[0]).collect();
        v.sort_unstable();
        v
    }

    #[test]
    fn prefix_cache_eviction_matches_old_policy_on_recorded_pattern() {
        const BUDGET: usize = 24;
        let mut px = PrefixCache::default();
        let mut old = OldModel { entries: Vec::new(), total: 0, clock: 0, victims: Vec::new() };
        // Deterministic LCG-driven pattern over 3 namespaces: inserts of varying sizes
        // (forcing multi-victim evictions) interleaved with recency touches.
        let mut rng: u64 = 0x9E3779B97F4A7C15;
        let mut step = || {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            (rng >> 33) as usize
        };
        let namespaces = ["", "tenant-a", "tenant-b"];
        let mut ident: u32 = 0;
        let mut placed: Vec<(u32, PoolKey)> = Vec::new(); // insert-ordered identities
        for _ in 0..400 {
            let survivors = px_survivors(&px);
            if step() % 3 == 2 && !survivors.is_empty() {
                // TOUCH a surviving entry (the lookup-hit recency refresh).
                let tgt = survivors[step() % survivors.len()];
                let k = placed.iter().find(|(i, _)| *i == tgt).unwrap().1.clone();
                let idx = px.entries[&k].iter().position(|e| e.toks[0] == tgt).unwrap();
                next_instant(); // keep every recorded timestamp distinct
                px.touch(&k, idx);
                old.touch(tgt);
            } else {
                // INSERT: 1..=8 bytes into one of the namespaces.
                let k = key(namespaces[step() % namespaces.len()]);
                let bytes = 1 + step() % 8;
                px.insert_with_budget(&k, entry_b(ident, bytes), "test", BUDGET);
                old.insert(ident, bytes, BUDGET);
                placed.push((ident, k));
                ident += 1;
            }
            // SAME-VICTIM PROPERTY: after every operation the surviving sets (and the
            // byte accounting) agree — evictions only happen inside insert, so equal
            // survivors at every step means the exact same victim sequence.
            assert_eq!(px_survivors(&px), old.survivors());
            assert_eq!(px.total_bytes, old.total);
        }
        assert_eq!(px.evictions as usize, old.victims.len());
        assert!(old.victims.len() > 50, "pattern too tame to prove anything: {} evictions",
                old.victims.len());
    }

    #[test]
    fn prefix_cache_touch_rescues_the_would_be_victim() {
        // Recency semantics end-to-end: the oldest entry, once touched, survives an
        // eviction that takes the second-oldest instead.
        let mut px = PrefixCache::default();
        px.insert_with_budget(&key(""), entry_b(0, 4), "test", 8);
        px.insert_with_budget(&key(""), entry_b(1, 4), "test", 8);
        let idx = px.entries[&key("")].iter().position(|e| e.toks[0] == 0).unwrap();
        next_instant();
        px.touch(&key(""), idx);
        px.insert_with_budget(&key(""), entry_b(2, 4), "test", 8);
        assert_eq!(px_survivors(&px), vec![0, 2], "touched 0 must survive, untouched 1 evicts");
    }

    #[test]
    fn prefix_cache_pin_refcount_blocks_eviction_until_last_release() {
        let k = key("");
        let mut px = PrefixCache::default();
        px.insert_with_budget(&k, entry_b(0, 4), "test", 8);
        px.insert_with_budget(&k, entry_b(1, 4), "test", 8);
        let idx = px.entries[&k].iter().position(|e| e.toks[0] == 0).unwrap();
        let pin = px.pin_n(&k, idx, 2).unwrap();

        // Both leases name one stable entry. While either is live, ordinary inserts
        // evict the oldest UNPINNED entry instead.
        px.insert_with_budget(&k, entry_b(2, 4), "test", 8);
        assert_eq!(px_survivors(&px), vec![0, 2]);
        assert_eq!(px.entries[&k].iter().find(|e| e.id == pin.id).unwrap().pins, 2);
        assert!(px.unpin(&pin));
        px.insert_with_budget(&k, entry_b(3, 4), "test", 8);
        assert_eq!(px_survivors(&px), vec![0, 3]);

        // Last release returns the entry to LRU. It is recent at release, survives the
        // first insert, then becomes the oldest evictable entry on the next insert.
        assert!(px.unpin(&pin));
        px.insert_with_budget(&k, entry_b(4, 4), "test", 8);
        assert_eq!(px_survivors(&px), vec![0, 4]);
        px.insert_with_budget(&k, entry_b(5, 4), "test", 8);
        assert_eq!(px_survivors(&px), vec![4, 5]);
        assert!(!px.unpin(&pin), "an evicted lease id must not release another entry");
    }

    #[test]
    fn retiring_session_releases_prefix_pin_in_release() {
        let k = key("");
        let mut px = PrefixCache::default();
        px.insert_with_budget(&k, entry_b(0, 4), "test", 8);
        let idx = px.entries[&k].iter().position(|e| e.toks[0] == 0).unwrap();
        let pin = px.pin(&k, idx).unwrap();
        let pin_id = pin.id;
        let mut session_pin = Some(pin);

        retire_prefix_pin(&mut px, &mut session_pin);
        // The session owns one lease: a repeated retire hook must not release twice.
        retire_prefix_pin(&mut px, &mut session_pin);

        assert!(session_pin.is_none(), "retirement consumes the session's one lease");
        let entry = px.entries[&k].iter().find(|e| e.id == pin_id).unwrap();
        assert_eq!(entry.pins, 0, "retirement must release the cache pin in release builds");
    }

    #[test]
    fn prefix_cache_emergency_flush_preserves_inflight_pins() {
        let k = key("");
        let mut px = PrefixCache::default();
        px.insert_with_budget(&k, entry_b(0, 4), "test", 8);
        px.insert_with_budget(&k, entry_b(1, 4), "test", 8);
        let idx = px.entries[&k].iter().position(|e| e.toks[0] == 0).unwrap();
        let pin = px.pin(&k, idx).unwrap();

        assert_eq!(px.evict_all(), 1);
        assert_eq!(px_survivors(&px), vec![0]);
        assert_eq!(px.total_bytes, 4);
        assert!(px.unpin(&pin));
        assert_eq!(px.evict_all(), 1);
        assert!(px_survivors(&px).is_empty());
        assert_eq!(px.total_bytes, 0);
    }

    #[test]
    fn prefix_cache_eviction_large_pool_flush_smoke() {
        // The old loop was O(E) per victim (O(E^2) on a flush) — at E = 10k victims that
        // is ~5e7 scanned entries with a PoolKey clone per candidate. The index makes the
        // same flush O(k log E); the bound below is generous CI headroom, not a benchmark.
        const E: usize = 10_000;
        let mut px = PrefixCache::default();
        for i in 0..E {
            px.insert_with_budget(&key(""), entry_b(i as u32, 1), "test", E);
        }
        assert_eq!(px.n_entries(), E);
        let t0 = std::time::Instant::now();
        px.insert_with_budget(&key(""), entry_b(u32::MAX, E / 2), "test", E);
        let dt = t0.elapsed();
        // half the pool evicted in ONE insert, oldest-first
        assert_eq!(px.n_entries(), E / 2 + 1);
        assert_eq!(px.evictions as usize, E / 2);
        assert_eq!(px.total_bytes, E);
        let survivors = px_survivors(&px);
        assert!(survivors.contains(&u32::MAX));
        assert!(!survivors.contains(&0) && !survivors.contains(&((E / 2 - 1) as u32)),
                "victims must be the oldest half");
        assert!(survivors.contains(&((E / 2) as u32)), "newest half survives");
        assert!(dt < std::time::Duration::from_secs(2),
                "large-E flush took {dt:?} — eviction is scaling with pool size again");
    }

    // ---------------- SESSION AFFINITY (lane/session-affinity, 2026-08-05) ----------------

    /// Token-stream stand-in for a chat-template-rendered conversation. `IM` plays the
    /// template's turn-marker (control) token; every other id is ordinary text.
    const IM: u32 = 1000;
    fn is_marker(t: u32) -> bool {
        t == IM
    }
    /// Render a conversation as the flat token stream a client-side template would post:
    /// each segment = marker + its body tokens.
    fn convo(segs: &[&[u32]]) -> Vec<u32> {
        let mut v = Vec::new();
        for s in segs {
            v.push(IM);
            v.extend_from_slice(s);
        }
        v
    }
    /// Fingerprint chain of a REQUEST (the live turn is excluded from identity).
    fn fp(toks: &[u32]) -> Vec<u64> {
        super::conversation_fingerprint(toks, &is_marker, true)
    }
    /// Fingerprint chain of a PARKED session's committed stream (no live tail to drop).
    fn fp_parked(toks: &[u32]) -> Vec<u64> {
        super::conversation_fingerprint(toks, &is_marker, false)
    }
    fn shared(a: &[u64], b: &[u64]) -> usize {
        super::fingerprint_affinity(a, b)
    }
    /// A body long enough that head and tail windows do not overlap (so interior edits are
    /// genuinely invisible to the fingerprint rather than trivially absent).
    fn body(tag: u32, n: usize) -> Vec<u32> {
        (0..n as u32).map(|i| tag * 100 + i).collect()
    }

    #[test]
    fn fingerprint_survives_an_assistant_interior_rewrite() {
        // THE lane's target case: the client strips a <think> block out of a PRIOR assistant
        // turn. Segment boundaries, roles, opening and closing tokens are unchanged; only the
        // interior shrinks. Same conversation => same fingerprint => the parked session is
        // nominated instead of discarded.
        let sys = body(1, 24);
        let user1 = body(2, 24);
        let mut asst1 = body(3, 40);
        let user2 = body(4, 24);
        let live = body(9, 8);
        let before = convo(&[&sys, &user1, &asst1, &user2, &live]);
        // strip the interior (keep >= FP_WINDOW head and tail tokens intact).
        asst1.drain(super::FP_WINDOW..asst1.len() - super::FP_WINDOW);
        let after = convo(&[&sys, &user1, &asst1, &user2, &live]);
        assert_ne!(before, after, "the rewrite must actually change the token stream");
        assert!(!after.starts_with(&before[..before.len() - 1]),
                "the rewrite must break plain prefix-extension (else the old probe would hit)");
        assert_eq!(fp(&before), fp(&after));
        assert!(fp(&before).len() >= super::FP_MIN_SEGMENTS);
    }

    #[test]
    fn fingerprint_nominates_the_parked_session_across_a_rewritten_turn() {
        // END TO END on the lane's actual case. Parked session committed turns 1-2 of a
        // conversation; the next request re-sends that history with the assistant turn's
        // interior stripped AND a new user turn appended. Plain prefix-extension is broken,
        // but the fingerprint chains share their whole leading run -> nominated.
        let (sys, user1, user2, live) = (body(1, 24), body(2, 24), body(4, 24), body(9, 8));
        let mut asst1 = body(3, 40);
        let parked = convo(&[&sys, &user1, &asst1]);
        asst1.drain(super::FP_WINDOW..asst1.len() - super::FP_WINDOW);
        let request = convo(&[&sys, &user1, &asst1, &user2, &live]);
        let n = shared(&fp(&request), &fp_parked(&parked));
        assert_eq!(n, 3, "system + user1 + rewritten assistant1 all match");
        assert!(n >= super::FP_MIN_SEGMENTS, "clears the nomination bar");
    }

    #[test]
    fn fingerprint_degrades_gracefully_when_a_rewrite_reaches_a_head_window() {
        // A think-strip can start right after the role marker, inside the head window. That
        // segment's hash changes — but identity is a PREFIX relation, so the stable opener
        // (system + early user turns, which no client rewrites) still nominates. Nomination
        // is a guess; affinity_match decides on bytes.
        let (sys, user1, user2, live) = (body(1, 24), body(2, 24), body(4, 24), body(9, 8));
        let asst1 = body(3, 40);
        let parked = convo(&[&sys, &user1, &asst1, &user2]);
        let mut wrecked = asst1.clone();
        wrecked.drain(..super::FP_WINDOW); // rewrite eats the head window too
        let request = convo(&[&sys, &user1, &wrecked, &user2, &live]);
        let n = shared(&fp(&request), &fp_parked(&parked));
        assert_eq!(n, 2, "shared run ends at the damaged segment, not at zero");
    }

    #[test]
    fn fingerprint_ignores_the_live_turn() {
        // A request's last segment is the turn being generated — new every turn by
        // construction. Two consecutive turns of one conversation share a chain.
        let (sys, user1, asst1) = (body(1, 24), body(2, 24), body(3, 24));
        let turn_a = convo(&[&sys, &user1, &asst1, &body(7, 12)]);
        let turn_b = convo(&[&sys, &user1, &asst1, &body(8, 30)]);
        assert_eq!(fp(&turn_a), fp(&turn_b));
    }

    #[test]
    fn fingerprint_separates_different_conversations() {
        // A different system prompt or a different first user turn must not clear the
        // nomination bar — affinity must never cross-link unrelated conversations.
        let (sys, user1, asst1, live) = (body(1, 24), body(2, 24), body(3, 24), body(9, 8));
        let base = fp(&convo(&[&sys, &user1, &asst1, &live]));
        let other_sys = fp(&convo(&[&body(5, 24), &user1, &asst1, &live]));
        let other_user = fp(&convo(&[&sys, &body(6, 24), &asst1, &live]));
        assert_eq!(shared(&base, &other_sys), 0, "different system prompt: nothing shared");
        assert_eq!(shared(&base, &other_user), 1, "only the system prompt is shared");
        assert!(shared(&base, &other_user) < super::FP_MIN_SEGMENTS, "below the bar");
    }

    #[test]
    fn fingerprint_declines_short_generic_openers() {
        // A bare system prompt (+ first user turn) is the SAME opener for every fresh
        // conversation with this client, so its shared run must stay under the bar.
        let sys = body(1, 24);
        let a = fp(&convo(&[&sys, &body(2, 24)]));
        let b = fp(&convo(&[&sys, &body(7, 24)]));
        assert!(shared(&a, &b) < super::FP_MIN_SEGMENTS);
        // a real multi-turn conversation does clear it.
        let long = convo(&[&sys, &body(2, 24), &body(3, 24), &body(9, 8)]);
        assert!(shared(&fp(&long), &fp(&long)) >= super::FP_MIN_SEGMENTS);
    }

    #[test]
    fn fingerprint_handles_a_prompt_with_no_markers() {
        // Raw non-chat completions (no template markers) have no segment structure: a
        // 1-segment chain, which for a request is also the live turn -> empty. Never clears
        // the bar, so those callers keep the plain prefix probes exactly as before.
        assert!(fp(&toks(512)).is_empty());
        assert!(shared(&fp(&toks(512)), &fp_parked(&toks(512))) < super::FP_MIN_SEGMENTS);
    }

    #[test]
    fn affinity_resume_requires_the_whole_committed_prefix() {
        use super::{affinity_match, AffinityMatch};
        // EXACT: the prompt carries every committed token, then new text -> prime the tail only.
        assert_eq!(
            affinity_match(&toks(100), &toks(60)),
            AffinityMatch::Exact { suffix_from: 60 }
        );
        // EXACT, empty suffix: pure continuation burst (nothing left to prime).
        assert_eq!(
            affinity_match(&toks(60), &toks(60)),
            AffinityMatch::Exact { suffix_from: 60 }
        );
    }

    #[test]
    fn affinity_refuses_to_resume_across_a_committed_range_divergence() {
        use super::{affinity_match, AffinityMatch};
        // The rewrite reached text the session ALREADY committed: the parked caches hold
        // recurrent state for tokens this request does not have, and a parked session carries
        // no checkpoint at the divergence boundary. Full re-prime — exactness over speed.
        let mut prompt = toks(100);
        prompt[42] = 999;
        assert_eq!(
            affinity_match(&prompt, &toks(60)),
            AffinityMatch::Diverged { at: 42 }
        );
        // A prompt SHORTER than committed (client dropped its own tail) is divergence too:
        // the extra committed rows cannot be trimmed away.
        assert_eq!(
            affinity_match(&toks(40), &toks(60)),
            AffinityMatch::Diverged { at: 40 }
        );
    }

    #[test]
    fn affinity_room_test_preserves_f5_right_sized_sessions() {
        // F5 INTERACTION. On a VRAM-tight rig the right-size ladder lands sessions BELOW the
        // request's ctx_cap — and those are exactly the rigs where every turn is a miss. The
        // affinity probe therefore tests `need` (prompt + budget + slack), not ctx_cap; this
        // pins the arithmetic that makes a laddered session eligible.
        let (prompt_len, budget, ctx_cap) = (12_000usize, 512usize, 131_072usize);
        let need = prompt_len + budget + super::SPEC_SHRINK_SLACK;
        let laddered = 16_384usize; // a plausible ladder landing
        assert!(laddered < ctx_cap, "the ladder lands below the cap (else no interaction)");
        assert!(laddered >= need, "and still covers what this request needs");
        let committed = toks(11_500);
        let prompt = toks(prompt_len);
        assert_eq!(
            super::affinity_resume_target(&prompt, &committed, 11_000, laddered, need, true),
            Ok(laddered),
            "a sufficient ladder landing must not be inflated back to ctx_cap",
        );
        assert_eq!(
            super::affinity_resume_target(&prompt, &committed, 11_000, 8_192, need, true),
            Ok(need),
            "an undersized landing grows only to this request's need",
        );
    }

    // ---------- PLAIN-SESSION AFFINITY (lane/plain-affinity, 2026-08-09) ----------

    #[test]
    fn plain_checkpoint_boundary_lands_before_the_live_generation_header() {
        use super::plain_checkpoint_boundary;
        // A pi-shaped chat prompt: stable history, then the template's live assistant-generation
        // header (marker + "assistant\n<think>\n"-class body). The boundary must sit at the START
        // of that final header segment — the stable point turn N+1 shares — NOT at prompt-end
        // (which the forced-spec control disproved) and NEVER at a hardcoded offset.
        let sys = body(1, 40);
        let user1 = body(2, 40);
        let asst1 = body(3, 40);
        let user2 = body(4, 40);
        // the live generation header: a marker, then a short body (role name + <think> opener).
        let prompt = {
            let mut v = convo(&[&sys, &user1, &asst1, &user2]);
            v.push(IM);
            v.extend_from_slice(&body(9, 4));
            v
        };
        let b = plain_checkpoint_boundary(&prompt, &is_marker)
            .expect("a multi-turn chat prompt has a locatable boundary");
        // the boundary is the index of the final marker (start of the live header segment).
        let last_marker = prompt.iter().rposition(|&t| t == IM).unwrap();
        assert_eq!(b, last_marker, "checkpoint sits at the start of the live header segment");
        assert!(b < prompt.len() && b > super::REUSE_MIN_PREFIX);
        // and it is STRICTLY before prompt-end (the boundary the control disproved).
        assert!(b < prompt.len() - 1);
    }

    #[test]
    fn plain_checkpoint_boundary_uses_a_guard_window_for_raw_prompts() {
        use super::{plain_checkpoint_boundary, PLAIN_CKPT_RAW_GUARD};
        // A markerless raw-completion prompt has no header to find: trim a conservative guard
        // window off the end so the live tail (which a re-ask may extend/rewrite) is never inside
        // the checkpoint. The exact diff still decides on bytes. (Arming for such a prompt
        // additionally requires an EXPLICIT session id — see the nominatable test below.)
        let prompt = toks(512);
        let b = plain_checkpoint_boundary(&prompt, &is_marker).expect("long raw prompt has one");
        assert_eq!(b, 512 - PLAIN_CKPT_RAW_GUARD);
    }

    #[test]
    fn plain_ckpt_capture_requires_a_nominatable_identity() {
        use super::plain_ckpt_nominatable;
        // THE CACHE-METERING REGRESSION (tip battery 2026-08-09, 13 checks red). An armed
        // ckpt_at excludes a session from the in-batch fanout / prime-batch paths (they prime
        // monolithically and cannot honor the per-session boundary stop). A markerless anonymous
        // prompt can NEVER be nominated by the implicit tier (its fingerprint chain cannot reach
        // FP_MIN_SEGMENTS), so arming it bought nothing and cost the serve-smoke 5-way
        // shared-prefix prompt_ids fanout every hit: 0 prefix hits, 6 misses, 6 inserts, empty
        // tick-seg LCP window. Capture is armed for such prompts ONLY with an explicit id.
        assert!(!plain_ckpt_nominatable(&toks(512), &is_marker),
                "markerless raw prompt must NOT arm an implicit-tier capture");
        // A real multi-turn chat prompt clears the bar and keeps the capture.
        let chat = convo(&[&body(1, 24), &body(2, 24), &body(3, 24), &body(9, 8)]);
        assert!(plain_ckpt_nominatable(&chat, &is_marker),
                "multi-turn chat traffic keeps the implicit-tier capture");
        // A one-segment opener (bare system prompt) stays below the bar — nominating on it
        // would cross-link unrelated conversations, so no capture either.
        let opener = convo(&[&body(1, 24)]);
        assert!(!plain_ckpt_nominatable(&opener, &is_marker));
    }

    #[test]
    fn plain_checkpoint_boundary_declines_short_prompts() {
        use super::plain_checkpoint_boundary;
        // Below the floor there is nothing worth a checkpoint (cold prime is cheaper than the
        // bookkeeping), so no boundary is armed.
        assert!(plain_checkpoint_boundary(&toks(super::REUSE_MIN_PREFIX + 4), &is_marker).is_none());
        assert!(plain_checkpoint_boundary(&toks(8), &is_marker).is_none());
    }

    #[test]
    fn plain_affinity_resume_decision_is_bytes_over_identity() {
        use super::{affinity_match, AffinityMatch, fingerprint_affinity};
        // END TO END on the decision the admit probe makes, exercised through the two functions
        // that make it: IDENTITY nominates (fingerprint chain shares >= the bar), BYTES decide
        // (the prompt reproduces the committed tokens through the checkpoint exactly).
        let (sys, user1, user2) = (body(1, 40), body(2, 40), body(4, 40));
        let mut asst1 = body(3, 60);
        // parked session committed [sys, user1, asst1]; its checkpoint sits at the pre-generation
        // boundary of THAT turn — model it as the whole committed stream (the resume only needs
        // committed[..pos] to match).
        let committed = convo(&[&sys, &user1, &asst1]);
        let pos = committed.len();
        let parked_fp = fp_parked(&committed);
        // turn N+1: the client strips asst1's interior and appends a new user turn + live header.
        asst1.drain(super::FP_WINDOW..asst1.len() - super::FP_WINDOW);
        let request = {
            let mut v = convo(&[&sys, &user1, &asst1, &user2]);
            v.push(IM);
            v.extend_from_slice(&body(9, 4));
            v
        };
        // The rewrite broke plain prefix-extension...
        assert!(!request.starts_with(&committed), "exact-extension would miss (rewritten history)");
        // ...but the fingerprint chains still share their leading run -> NOMINATED.
        assert!(fingerprint_affinity(&fp(&request), &parked_fp) >= super::FP_MIN_SEGMENTS);
        // BYTES DECIDE: does the request reproduce the committed tokens up to a boundary? The
        // stripped assistant turn shortened `committed`, so the FULL committed stream diverges —
        // which is exactly why the checkpoint must sit BEFORE that turn's generated text. At a
        // boundary of [sys, user1] (before asst1) the request matches exactly and leaves a suffix.
        let early_pos = convo(&[&sys, &user1]).len();
        assert!(early_pos < pos);
        match affinity_match(&request, &committed[..early_pos]) {
            AffinityMatch::Exact { suffix_from } => assert_eq!(suffix_from, early_pos),
            other => panic!("expected exact match at the pre-generation boundary, got {other:?}"),
        }
        assert!(request.len() > early_pos, "non-empty suffix to prime");
    }

    #[test]
    fn plain_affinity_declines_a_divergence_below_the_checkpoint() {
        use super::{affinity_match, AffinityMatch};
        // If the rewrite reached text BELOW the checkpoint boundary, the parked caches hold state
        // for tokens this request does not have — correctness first, full re-prime. This is the
        // one decline expected by design; the offset is the diagnostic.
        let committed = toks(80);
        let mut request = toks(120);
        request[30] = 7777; // diverges inside committed[..50]
        match affinity_match(&request, &committed[..50]) {
            AffinityMatch::Diverged { at } => assert_eq!(at, 30),
            other => panic!("a below-boundary rewrite must decline, got {other:?}"),
        }
    }

    #[test]
    fn plain_affinity_fingerprint_collision_cannot_force_a_wrong_resume() {
        use super::{affinity_match, AffinityMatch, fingerprint_affinity};
        // The safety argument: a fingerprint match only NOMINATES; the exact token diff is the
        // sole authority. Construct two DIFFERENT conversations that (by the boundary-window
        // hashing) could share a leading run, and show the byte diff still vetoes the resume.
        let (sys, user1) = (body(1, 40), body(2, 40));
        let committed = convo(&[&sys, &user1, &body(3, 40)]);
        // a request that shares the fingerprintable opener but whose actual bytes differ inside
        // the committed range (a genuine different conversation that happens to nominate).
        let mut request = committed.clone();
        request[5] = 4242; // byte-level divergence inside the very first segment
        request.extend_from_slice(&body(9, 8));
        // Even if identity nominated (same chain length), bytes veto:
        let _nominated = fingerprint_affinity(&fp(&request), &fp_parked(&committed));
        match affinity_match(&request, &committed) {
            AffinityMatch::Diverged { at } => assert_eq!(at, 5, "the exact diff catches it"),
            other => panic!("a byte divergence must never resume, got {other:?}"),
        }
    }

    #[test]
    fn plain_affinity_pi_shape_grows_instead_of_declining() {
        use super::affinity_resume_target;

        // Live pi shape after request-owned context sizing: the parked cache was allocated for
        // the preceding turn, while the next turn's prompt makes its charged cap a few hundred
        // rows larger. Identity and bytes match through the checkpoint, so capacity selects a
        // grow target; it must never veto the resume as "no room".
        let committed = toks(12_640);
        let prompt = toks(12_690);
        let checkpoint_pos = 12_000;
        let parked_cap = 45_064;
        let incoming_request_need = 45_522;
        assert_eq!(
            affinity_resume_target(
                &prompt,
                &committed,
                checkpoint_pos,
                parked_cap,
                incoming_request_need,
                true,
            ),
            Ok(incoming_request_need),
            "a nominated exact checkpoint must grow to the next request instead of declining",
        );
    }

    #[test]
    fn streaming_utf8_waits_for_a_complete_multibyte_sequence() {
        let mut emitted = 0;
        assert_eq!(utf8_delta(b"caf\xc3", &mut emitted), "caf");
        assert_eq!(emitted, 3);
        assert_eq!(utf8_delta(b"caf\xc3\xa9\n", &mut emitted), "é\n");
        assert_eq!(emitted, 6);
    }

    #[test]
    fn streaming_utf8_consumes_truly_invalid_bytes_once() {
        let mut emitted = 0;
        assert_eq!(utf8_delta(b"a\xffb", &mut emitted), "a\u{fffd}b");
        assert_eq!(emitted, 3);
        assert_eq!(utf8_delta(b"a\xffbc", &mut emitted), "c");
    }

    #[test]
    fn confidence_summary_tracks_reference_and_margin() {
        let summary = summarize_confidence(&[0.0, 2.0, 1.0], 1).unwrap();
        assert_eq!(summary.top1_token, 1);
        assert!(summary.top1_correct);
        assert!((summary.top1_top2_margin - 1.0).abs() < 1e-6);
        let expected = 2.0f64 - (0.0f64.exp() + 2.0f64.exp() + 1.0f64.exp()).ln();
        assert!((summary.reference_logprob - expected).abs() < 1e-12);
        assert!(summary.entropy > 0.0);
    }
}