memra-server 0.72.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
//! memra-server (BASE-4): a minimal OpenAI-ish HTTP server that serves 2-4 concurrent agents across
//! DIFFERENT models on one endpoint via a single GPU worker thread + step-interleave scheduler.
//!
//! Architecture (see worker.rs): axum runs on a tokio runtime; ONE dedicated std::thread owns the
//! Engine + every loaded HybridModel (CUDA context is thread-affine). Handlers submit `Cmd`s over a
//! std mpsc channel and receive tokens back over a per-request tokio mpsc channel.
//!
//! Endpoints (the full set — `router()` below is the authority):
//!   GET  /health, GET /livez     -> the SAME handler (`health_live`): INFERENCE liveness, not
//!                                     process liveness. {"status":"ok"|"draining"|"unhealthy",
//!                                     "models":[...], "worker":{phase, beat_age_ms, tick_max_ms,
//!                                     stall_threshold_ms, generation, xid_warnings}} + a
//!                                     top-level "detail" on a red. Draining stays 200; dead /
//!                                     GPU-faulted / stalled / loading is 503 (serve-hardening
//!                                     2026-08-06).
//!   GET  /readyz                 -> routability, same payload shape with
//!                                     "status":"ready"|"not_ready". Unready is NOT a restart
//!                                     request — draining and loading are healthy-but-unroutable.
//!   GET  /models                 -> {"data":[{"id":name},...]}  (OpenAI-ish);
//!                                     ?schema=openrouter -> Provider Monitor schema 2.4.
//!   GET  /v1/models              -> existing catalog-style model list (context_length,
//!                                     architecture, pricing stub, top_provider; serve-tail).
//!   GET  /metrics                -> flat serving counters + step latency percentiles.
//!   GET  /yield/metrics          -> per-lane x-lane QoS counters + engine-truth step p50/p99
//!                                     (lane/qos-p95 2026-08-02).
//!   POST /v1/completions         -> {model,prompt|prompt_ids,max_tokens,temperature?,top_p?,top_k?,
//!                                     seed?,stop?,chat?,stream?,cache_salt?}. stream=true => SSE
//!                                     token-by-token; else a single JSON {text,tokens,stop_reason}.
//!   POST /v1/chat/completions    -> OpenAI chat messages rendered by the GGUF chat template;
//!                                     OpenAI message/chunk response shapes. `tools`/`tool_choice`
//!                                     (auto|none) + role:"tool" turns render through the
//!                                     template's own <tools> branch; emitted <tool_call> blocks
//!                                     parse into OpenAI `tool_calls` (+"tool_calls" finish);
//!                                     `reasoning_effort`/`reasoning` map onto the template's
//!                                     think switch (serve-tools lane, 2026-08-02).
//!
//! CONFIG: MEMRA_MODELS="name=/path.gguf[+/draft.gguf],name2=hf:owner/repo,name3=/hf_ckpt_dir"
//! (comma-separated; `+draft.gguf` attaches that model's regime draft — docs/DRAFT-REGIME.md).
//! A model path may be a GGUF file OR an HF safetensors checkpoint directory
//! (config.json + model.safetensors[.index.json] — the run-safetensors load path; serve-st
//! lane 2026-08-04). Defaults to the BASE-4 test pair (main=27B, judge=9B) if unset.
//! MEMRA_ADDR sets the bind addr.
//!
//! LIFECYCLE: SIGTERM = graceful drain (gap-scan F11) — new completion requests 503 with
//! Retry-After, /health reports "draining", in-flight requests (streams included) finish
//! up to MEMRA_DRAIN_S (default 30s), then the process exits 0. Completion responses carry
//! X-RateLimit-Limit/-Remaining/-Reset (concurrency-slot semantics; gap-scan F12).

/// x-lane QoS (lane/dl-metering gate, QoS-only extraction 2026-08-02): lane types, SLO
/// admission policy, engine-truth step stats live in the memra-lanes crate so out-of-process
/// controllers (the sidecar shape) can share them.
pub(crate) mod auth;
pub(crate) mod constrained;
/// Dead-darklane background jobs (lane/darklane-training, 2026-08-07): valley detection over
/// worker truth (phase + beat age + pending admits) and a yield-first background job runner —
/// a lane class BELOW every serving lane. Engine mechanics only; policy lives product-side.
pub(crate) mod darklane;
/// Inference-liveness state (lane/serve-hardening, gaps G5 + G24): the worker heartbeat every
/// health answer is derived from, the Xid/GPU-fault watcher, and the sd_notify half of the
/// systemd contract. Process liveness is NOT inference liveness — this module is the difference.
pub(crate) mod health;
pub(crate) mod lanes { pub use memra_lanes::*; }
mod toolcall;
mod worker;

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::Sender;

use axum::{
    Json, Router,
    extract::{Query, State},
    http::StatusCode,
    response::{sse::{Event as SseEvent, Sse}, IntoResponse, Response},
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use serde_json::json;

use memra_engine::decode::GenParams;
use memra_engine::sampler::SamplerConfig;
use memra_tokenizer::chat::{ThinkMode, ToolCall as TmplToolCall, Turn as TmplTurn};
use toolcall::{ParsedToolCall, Piece, ToolStreamParser};
use worker::{Cmd, Event, ModelCaps, Request, SharedMetrics};

const OPENROUTER_SCHEMA_VERSION: &str = "2.4";
const JSON_SAFE_INTEGER_MAX: u64 = 9_007_199_254_740_991;

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenRouterMetadataFile {
    #[serde(default)]
    models: HashMap<String, OpenRouterModelMetadata>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenRouterModelMetadata {
    #[serde(default)]
    hugging_face_id: Option<String>,
    #[serde(default)]
    created: Option<u64>,
    #[serde(default)]
    quantization: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    max_prompt_length: Option<u64>,
    #[serde(default)]
    max_output_length: Option<u64>,
    #[serde(default)]
    pricing: OpenRouterPricing,
    #[serde(default)]
    capacity: OpenRouterCapacity,
    #[serde(default)]
    is_ready: Option<bool>,
    #[serde(default)]
    is_free: Option<bool>,
    #[serde(default)]
    discount_to_user: Option<f64>,
    #[serde(default)]
    openrouter_slug: Option<String>,
    #[serde(default)]
    datacenters: Vec<OpenRouterDatacenter>,
    #[serde(default)]
    zdr: Option<bool>,
    #[serde(default)]
    hipaa: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenRouterPricing {
    #[serde(default)]
    prompt: Option<String>,
    #[serde(default)]
    cached_prompt: Option<String>,
    #[serde(default)]
    cache_write: Option<String>,
    #[serde(default)]
    completion: Option<String>,
    #[serde(default)]
    internal_reasoning: Option<String>,
    #[serde(default)]
    request: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenRouterCapacity {
    #[serde(default)]
    prompt_tpm: Option<u64>,
    #[serde(default)]
    cached_prompt_tpm: Option<u64>,
    #[serde(default)]
    completion_tpm: Option<u64>,
    #[serde(default)]
    request_rpm: Option<u64>,
    #[serde(default)]
    concurrency: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct OpenRouterDatacenter {
    country_code: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    region: Option<String>,
}

impl OpenRouterMetadataFile {
    fn from_toml(text: &str) -> Result<HashMap<String, OpenRouterModelMetadata>, String> {
        let file: Self = toml::from_str(text)
            .map_err(|e| format!("models metadata TOML parse: {e}"))?;
        for (alias, metadata) in &file.models {
            validate_openrouter_metadata(alias, metadata)?;
        }
        Ok(file.models)
    }
}

fn valid_price_string(value: &str) -> bool {
    let mut parts = value.split('.');
    let whole = parts.next().unwrap_or_default();
    let fraction = parts.next();
    !whole.is_empty()
        && whole.bytes().all(|b| b.is_ascii_digit())
        && fraction.is_none_or(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
        && parts.next().is_none()
}

fn validate_openrouter_metadata(
    alias: &str,
    metadata: &OpenRouterModelMetadata,
) -> Result<(), String> {
    if alias.is_empty() {
        return Err("models metadata contains an empty model alias".into());
    }
    if let Some(q) = metadata.quantization.as_deref()
        && !matches!(
            q,
            "int4" | "int8" | "fp4" | "mxfp4" | "nvfp4" | "fp6" | "fp8" | "mxfp8"
                | "fp16" | "bf16" | "fp32"
        )
    {
        return Err(format!(
            "model {alias:?}: quantization {q:?} is not in the OpenRouter schema 2.4 enum"
        ));
    }
    for (field, value) in [
        ("pricing.prompt", metadata.pricing.prompt.as_deref()),
        (
            "pricing.cached_prompt",
            metadata.pricing.cached_prompt.as_deref(),
        ),
        (
            "pricing.cache_write",
            metadata.pricing.cache_write.as_deref(),
        ),
        (
            "pricing.completion",
            metadata.pricing.completion.as_deref(),
        ),
        (
            "pricing.internal_reasoning",
            metadata.pricing.internal_reasoning.as_deref(),
        ),
        ("pricing.request", metadata.pricing.request.as_deref()),
    ] {
        if let Some(value) = value
            && !valid_price_string(value)
        {
            return Err(format!(
                "model {alias:?}: {field} must be a non-negative per-unit USD decimal string"
            ));
        }
    }
    for (field, value) in [
        ("created", metadata.created),
        ("max_prompt_length", metadata.max_prompt_length),
        ("max_output_length", metadata.max_output_length),
        ("capacity.prompt_tpm", metadata.capacity.prompt_tpm),
        (
            "capacity.cached_prompt_tpm",
            metadata.capacity.cached_prompt_tpm,
        ),
        (
            "capacity.completion_tpm",
            metadata.capacity.completion_tpm,
        ),
        ("capacity.request_rpm", metadata.capacity.request_rpm),
        ("capacity.concurrency", metadata.capacity.concurrency),
    ] {
        if let Some(value) = value
            && value > JSON_SAFE_INTEGER_MAX
        {
            return Err(format!(
                "model {alias:?}: {field} exceeds OpenRouter's JSON safe-integer maximum"
            ));
        }
    }
    for (field, value) in [
        ("max_prompt_length", metadata.max_prompt_length),
        ("max_output_length", metadata.max_output_length),
        ("capacity.prompt_tpm", metadata.capacity.prompt_tpm),
        (
            "capacity.cached_prompt_tpm",
            metadata.capacity.cached_prompt_tpm,
        ),
        (
            "capacity.completion_tpm",
            metadata.capacity.completion_tpm,
        ),
        ("capacity.request_rpm", metadata.capacity.request_rpm),
        ("capacity.concurrency", metadata.capacity.concurrency),
    ] {
        if value == Some(0) {
            return Err(format!(
                "model {alias:?}: {field} must be greater than zero when declared"
            ));
        }
    }
    if let Some(discount) = metadata.discount_to_user
        && (!discount.is_finite() || discount >= 1.0)
    {
        return Err(format!(
            "model {alias:?}: discount_to_user must be finite and less than 1"
        ));
    }
    if metadata
        .openrouter_slug
        .as_deref()
        .is_some_and(str::is_empty)
    {
        return Err(format!(
            "model {alias:?}: openrouter_slug must not be empty when declared"
        ));
    }
    for dc in &metadata.datacenters {
        if dc.country_code.len() != 2
            || !dc.country_code.bytes().all(|b| b.is_ascii_uppercase())
        {
            return Err(format!(
                "model {alias:?}: datacenter country_code {:?} must be two uppercase ASCII letters",
                dc.country_code
            ));
        }
    }
    Ok(())
}

fn load_openrouter_metadata(
    models: &[(String, String, Option<String>)],
) -> Result<HashMap<String, OpenRouterModelMetadata>, String> {
    let path = match std::env::var("MEMRA_MODEL_METADATA") {
        Ok(path) => path,
        Err(_) => return Ok(HashMap::new()),
    };
    let p = std::path::Path::new(&path);
    if !p.is_file() {
        return Err(format!(
            "MEMRA_MODEL_METADATA={path:?} is not an existing TOML file"
        ));
    }
    let text = std::fs::read_to_string(p)
        .map_err(|e| format!("MEMRA_MODEL_METADATA {path:?}: {e}"))?;
    let metadata = OpenRouterMetadataFile::from_toml(&text)
        .map_err(|e| format!("MEMRA_MODEL_METADATA {path:?}: {e}"))?;
    for alias in metadata.keys() {
        if !models.iter().any(|(name, _, _)| name == alias) {
            return Err(format!(
                "MEMRA_MODEL_METADATA {path:?}: model alias {alias:?} is not present in MEMRA_MODELS"
            ));
        }
    }
    eprintln!(
        "[server] OpenRouter metadata loaded: {} model(s) from {path}",
        metadata.len()
    );
    Ok(metadata)
}

#[derive(Clone)]
struct AppState {
    cmd_tx: Sender<Cmd>,
    models: Arc<Vec<String>>,
    caps: Arc<HashMap<String, ModelCaps>>,
    openrouter_metadata: Arc<HashMap<String, OpenRouterModelMetadata>>,
    metrics: SharedMetrics,
    /// unix seconds at worker-ready — the /v1/models `created` value (when this server
    /// instance made the model available; the honest timestamp we actually know).
    started: u64,
    /// live per-lane in-flight request gauge (HTTP-layer view: submitted and not yet
    /// finished, queued-at-worker included) — drives the X-RateLimit-* headers and the
    /// graceful-drain completion barrier (serve-tail lane, gap-scan F11/F12).
    inflight: InflightCounts,
    /// per-tenant in-flight gauge (lane/api-keys): keyed by tenant id, same RAII life as
    /// the lane gauge — drives per-key rate-limit overrides + their headers.
    tenant_inflight: TenantGauge,
    /// inference liveness (lane/serve-hardening, G5): the GPU worker's heartbeat + phase +
    /// fault latches, shared with the worker thread and the Xid watcher. /health, /livez and
    /// /readyz read ONLY this — never "the process is up".
    health: health::SharedHealth,
    /// dead-darklane background job observability (lane/darklane-training): the runner's
    /// shared counters + its yield mode, for the /metrics "bg" block. None when MEMRA_BG_JOB
    /// is unset — the block is absent and the payload byte-identical to pre-lane.
    bg: Option<(Arc<darklane::BgJobState>, &'static str)>,
}

// ---- rate-limit headers (serve-tail lane, 2026-08-04; gap-scan F12) ----
//
// X-RateLimit-Limit / -Remaining / -Reset on /v1/completions and /v1/chat/completions,
// with CONCURRENCY-SLOT semantics (this server admission-caps concurrent sessions; it has
// no request/min or token/min budget to report — inventing one would be dishonest):
//   Limit     = the lane's configured admission cap — the same values the worker's own
//               admission gate enforces (interactive: MEMRA_MAX_SESSIONS batched /
//               MAX_ACTIVE legacy; judge/harvest: LanePolicy max_sessions).
//   Remaining = free slots at submission time (cap minus in-flight, this request
//               included). Interactive beyond the cap QUEUES (never shed), so Remaining 0
//               means "you will wait", not "you will be rejected".
//   Reset     = seconds until a slot is ESTIMATED free: 0 while slots are free; else the
//               live meter's mean service time (tokens/request x p50 step latency) when
//               it has signal, else MEMRA_RL_RESET_S (default 2). Honestly coarse — a
//               hint, not a promise.
// Dark-lane 429 sheds carry the same trio (Retry-After was already there).

type InflightCounts = Arc<[std::sync::atomic::AtomicUsize; 3]>;

/// Per-tenant in-flight gauge (lane/api-keys): tenant id -> live request count. Entries
/// are removed at zero so the map stays bounded by concurrent tenants, not tenant history.
type TenantGauge = Arc<std::sync::Mutex<HashMap<String, usize>>>;

/// RAII in-flight slot: increments the lane + tenant gauges at submission, decrements
/// both when the response is complete — dropped at handler exit (blocking) or when the
/// SSE stream finishes/disconnects (moved into the stream).
struct InflightGuard {
    counts: InflightCounts,
    idx: usize,
    tenants: TenantGauge,
    tenant: String,
}

impl InflightGuard {
    /// Atomically enforce a binding tenant cap, then return the guard + the (lane, tenant)
    /// in-flight counts INCLUDING this request. The tenant mutex closes the two-arrivals-at-
    /// once race: at cap, exactly one request wins and the other returns the existing count.
    fn try_acquire(counts: InflightCounts, lane: lanes::Lane, tenants: TenantGauge,
                   tenant: &str, tenant_cap: Option<usize>)
        -> Result<(Self, usize, usize), usize>
    {
        let idx = lane.idx();
        let nt = {
            let mut m = tenants.lock().unwrap();
            let e = m.entry(tenant.to_string()).or_insert(0);
            if tenant_cap.is_some_and(|cap| *e >= cap) {
                return Err(*e);
            }
            *e += 1;
            *e
        };
        let n = counts[idx].fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
        Ok((InflightGuard { counts, idx, tenants, tenant: tenant.to_string() }, n, nt))
    }
}

impl Drop for InflightGuard {
    fn drop(&mut self) {
        self.counts[self.idx].fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        let mut m = self.tenants.lock().unwrap();
        if let Some(e) = m.get_mut(&self.tenant) {
            *e -= 1;
            if *e == 0 {
                m.remove(&self.tenant);
            }
        }
    }
}

/// The lane's configured admission cap — mirrors the worker's admission gate exactly
/// (worker.rs step 2): interactive = MEMRA_MAX_SESSIONS (64) batched / MAX_ACTIVE legacy;
/// judge/harvest = LanePolicy::from_env().max_sessions. Read once.
fn lane_cap(lane: lanes::Lane) -> usize {
    static CAPS: std::sync::OnceLock<[usize; 3]> = std::sync::OnceLock::new();
    CAPS.get_or_init(|| {
        let batching = std::env::var("MEMRA_SERVE_BATCH").map(|v| v != "0").unwrap_or(true);
        let interactive = if batching {
            std::env::var("MEMRA_MAX_SESSIONS").ok()
                .and_then(|v| v.parse().ok()).unwrap_or(64)
        } else {
            worker::MAX_ACTIVE
        };
        let p = lanes::LanePolicy::from_env();
        [interactive, p.max_sessions[1], p.max_sessions[2]]
    })[lane.idx()]
}

/// Coarse next-slot estimate (seconds): mean tokens/request x p50 step latency from the
/// live meter when it has signal, else the MEMRA_RL_RESET_S static (default 2).
fn reset_estimate_s(m: &worker::Metrics) -> u64 {
    if m.completed > 0 && m.step_p50_ms > 0.0 {
        let mean_toks = m.tokens_out as f64 / m.completed as f64;
        return ((mean_toks * m.step_p50_ms as f64 / 1000.0).ceil() as u64).clamp(1, 600);
    }
    static D: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
    *D.get_or_init(|| std::env::var("MEMRA_RL_RESET_S").ok()
        .and_then(|v| v.parse().ok()).unwrap_or(2))
}

// ---- graceful drain (serve-tail lane, 2026-08-04; gap-scan F11) ----
//
// SIGTERM flips the drain flag: new requests on the completion routes get an immediate
// 503 + Retry-After (never queued), /health reports "draining" (the LB is_ready signal),
// and the drain task waits on the in-flight gauge (the same HTTP-layer counts the
// rate-limit headers use — streams hold their slot until fully written) up to
// MEMRA_DRAIN_S (default 30s), then shuts the listener down and the process exits 0.
// Fleet restarts stop being SIGKILL-class in-flight loss (the chaos-receipt gap).

/// Process-wide drain flag (set by the SIGTERM task, read by every admission gate).
static DRAINING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

fn draining() -> bool {
    DRAINING.load(std::sync::atomic::Ordering::SeqCst)
}

/// MEMRA_DRAIN_S (default 30): how long a draining server waits for in-flight requests.
fn drain_deadline_s() -> u64 {
    static D: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
    *D.get_or_init(|| std::env::var("MEMRA_DRAIN_S").ok()
        .and_then(|v| v.parse().ok()).unwrap_or(30))
}

/// 503 for a request that arrived during drain: OpenAI error object + Retry-After
/// (the drain window — by then this instance is gone and its replacement is up).
///
/// Goes through the SAME retry contract as every engine-fault class (G6): a `code` clients can
/// branch on, the `retry-after-ms` twin openai-python reads FIRST, and the value clamped to
/// 60 s because litellm ignores anything above that and openai-python abandons the retry past
/// 120 s. It predates the taxonomy and was the one 503 on the surface still emitting a bare
/// `Retry-After` with no code and no ms twin — i.e. a client that trusted `retry-after-ms`
/// exclusively saw no window at all on the most predictable outage memra has.
fn drain_response() -> Response {
    let resp = (StatusCode::SERVICE_UNAVAILABLE,
        Json(error_body("server is draining (shutdown in progress); retry",
                        "server_error", None, Some("draining")))).into_response();
    retry_contract_response(resp, Some(drain_deadline_s()))
}

/// One request's header values, computed at submission time (the "at admit" snapshot).
struct RateLimit {
    limit: usize,
    remaining: usize,
    reset_s: u64,
}

impl RateLimit {
    /// Per-tenant override law (lane/api-keys): the effective cap is
    /// min(tenant_override, global lane cap) — the GLOBAL cap stays authoritative (an
    /// override can only narrow, never widen). Remaining is the tighter of the two
    /// headrooms (tenant cap minus tenant in-flight vs lane cap minus lane in-flight).
    fn at_admit(lane: lanes::Lane, n_inflight: usize, metrics: &SharedMetrics,
                tenant: &auth::TenantCtx, n_tenant: usize) -> Self {
        let global = lane_cap(lane);
        let Some(t) = tenant.rate_limit.filter(|&t| t < global) else {
            return Self::compute(global, n_inflight, metrics);
        };
        let headroom = t.saturating_sub(n_tenant)
            .min(global.saturating_sub(n_inflight));
        // compute() derives remaining as limit - n; feed it the effective occupancy.
        Self::compute(t, t - headroom, metrics)
    }

    fn compute(limit: usize, n_inflight: usize, metrics: &SharedMetrics) -> Self {
        let remaining = limit.saturating_sub(n_inflight);
        let reset_s = if remaining > 0 {
            0
        } else {
            let m = metrics.lock().map(|m| m.clone()).unwrap_or_default();
            reset_estimate_s(&m)
        };
        RateLimit { limit, remaining, reset_s }
    }

    /// Stamp the X-RateLimit-* trio onto a response.
    fn attach(&self, mut resp: Response) -> Response {
        let h = resp.headers_mut();
        for (k, v) in [
            ("x-ratelimit-limit", self.limit as u64),
            ("x-ratelimit-remaining", self.remaining as u64),
            ("x-ratelimit-reset", self.reset_s),
        ] {
            if let Ok(v) = axum::http::HeaderValue::from_str(&v.to_string()) {
                h.insert(axum::http::HeaderName::from_static(k), v);
            }
        }
        resp
    }
}

/// Take the HTTP-layer request slot or reject a tenant whose configured override is already
/// full. Global interactive capacity still queues as before; this gate exists only when the
/// key's override is narrower than the lane cap.
fn acquire_request_slot(st: &AppState, lane: lanes::Lane, tenant: &auth::TenantCtx,
                        env: &Envelope) -> Result<(InflightGuard, RateLimit), Response> {
    let global = lane_cap(lane);
    let tenant_cap = tenant.rate_limit.filter(|&cap| cap < global);
    match InflightGuard::try_acquire(
        st.inflight.clone(), lane, st.tenant_inflight.clone(), &tenant.tenant, tenant_cap,
    ) {
        Ok((guard, n_inflight, n_tenant)) => {
            let rl = RateLimit::at_admit(lane, n_inflight, &st.metrics, tenant, n_tenant);
            Ok((guard, rl))
        }
        Err(n_tenant) => {
            let n_inflight =
                st.inflight[lane.idx()].load(std::sync::atomic::Ordering::SeqCst);
            let rl = RateLimit::at_admit(
                lane, n_inflight, &st.metrics, tenant, n_tenant);
            let error = worker::EngineError::rate_limit(
                "api key concurrent request limit reached; retry");
            Err(rl.attach(with_request_id(&env.id, engine_error_response(&error))))
        }
    }
}

/// POST /v1/completions request body.
#[derive(Deserialize)]
struct CompletionReq {
    model: String,
    #[serde(default)]
    prompt: String,
    /// raw token-id prompt (the exact-token validation-gate path; bypasses the tokenizer).
    #[serde(default)]
    prompt_ids: Vec<u32>,
    /// Omitted (gap-scan F2) => context-bounded (session ctx - prompt, model-capped), the
    /// OpenAI default-when-omitted semantics — NOT a silent 128-token truncation.
    #[serde(default)]
    max_tokens: Option<usize>,
    /// Omitted (dogfood F4) => 1.0, the OpenAI default-when-omitted — NOT 0.0/greedy.
    /// `serde(default)` on an f32 yielded 0.0, which silently locked every
    /// temperature-omitting client (the owner's own agentic pill) into deterministic
    /// argmax: same context in, same token out, identical tool-call cycles forever.
    /// Explicit `"temperature": 0` still means greedy — that's a caller decision.
    #[serde(default = "default_temperature")]
    temperature: f32,
    #[serde(default = "one")]
    top_p: f32,
    /// Not an OpenAI parameter (OpenRouter/HF convention); 0 = disabled = keep all.
    #[serde(default)]
    top_k: usize,
    /// Not an OpenAI parameter (OpenRouter/HF convention); 0.0 = disabled.
    #[serde(default)]
    min_p: f32,
    /// OpenAI penalties (gap-scan F3): implemented in SamplerConfig all along, now plumbed.
    #[serde(default)]
    frequency_penalty: f32,
    #[serde(default)]
    presence_penalty: f32,
    /// OpenRouter/HF-convention multiplicative penalty (1.0 = off).
    #[serde(default = "one")]
    repetition_penalty: f32,
    /// Omitted (dogfood F4, second half) => a FRESH RANDOM seed per request. `Option`, not
    /// `u64`: `serde(default)` gave 0, which is a perfectly valid FIXED seed, so every
    /// seed-omitting client replayed one single sampled stream — the same loop the
    /// temperature default caused, surviving the temperature fix. OpenAI's `seed` is
    /// explicitly best-effort determinism WHEN SUPPLIED; omitting it must not pin the RNG.
    #[serde(default)]
    seed: Option<u64>,
    #[serde(default)]
    stop: StopSequences,
    /// Unsupported-but-semantic fields (gap-scan F4): captured so they 400 loudly instead
    /// of being silently swallowed by serde (policy: clean 400s, not silent downgrades).
    #[serde(default)]
    logit_bias: Option<serde_json::Value>,
    #[serde(default)]
    logprobs: Option<serde_json::Value>,
    #[serde(default)]
    n: Option<usize>,
    #[serde(default)]
    best_of: Option<usize>,
    /// wrap the prompt in the model's chat template (single user turn).
    #[serde(default)]
    chat: bool,
    /// stream tokens via SSE; else return one JSON when done.
    #[serde(default)]
    stream: bool,
    /// optional hard context cap.
    #[serde(default)]
    max_ctx: Option<usize>,
    /// Stable calibration-record identity written only when confidence tracing is enabled.
    #[serde(default)]
    trace_id: Option<String>,
    /// PC-ISO prefix-cache namespace (vLLM `cache_salt` convention, optional): requests
    /// only share cached prefixes with requests carrying the SAME salt. Absent/"" = the
    /// default single-tenant namespace (pre-PC-ISO behavior). See `cache_namespace`.
    #[serde(default)]
    cache_salt: Option<String>,
    /// SESSION AFFINITY explicit tier (lane/session-affinity): the caller's own name for
    /// this conversation. See `affinity_key`. `session_id` is the explicit spelling;
    /// `user` is OpenAI's field that real clients already send.
    #[serde(default)]
    session_id: Option<String>,
    #[serde(default)]
    user: Option<String>,
}

#[derive(Deserialize)]
struct ChatMessage {
    role: String,
    /// string, null, or an array of `{type:"text",text}` parts (OpenAI content shapes).
    #[serde(default)]
    content: serde_json::Value,
    /// OpenAI assistant-history tool calls, re-rendered into the template on the next turn.
    #[serde(default)]
    tool_calls: Vec<ReqToolCall>,
    /// Accepted for OpenAI-shape compat; result pairing in the template is positional.
    #[serde(default)]
    #[allow(dead_code)]
    tool_call_id: Option<String>,
}

#[derive(Deserialize)]
struct ReqToolCall {
    #[serde(default)]
    #[allow(dead_code)]
    id: Option<String>,
    function: ReqToolFunction,
}

#[derive(Deserialize)]
struct ReqToolFunction {
    name: String,
    /// OpenAI sends a JSON-encoded STRING; inline objects are accepted too.
    #[serde(default)]
    arguments: serde_json::Value,
}

#[derive(Clone, Default, Deserialize)]
#[serde(untagged)]
enum StopSequences {
    One(String),
    Many(Vec<String>),
    #[default]
    None,
}

impl StopSequences {
    fn into_vec(self) -> Vec<String> {
        match self {
            Self::One(stop) => vec![stop],
            Self::Many(stops) => stops,
            Self::None => Vec::new(),
        }
    }
}

/// OpenAI-compatible multi-turn chat request. `tools`/`tool_choice`/role:"tool" are accepted
/// (serve-tools lane, 2026-08-02): tool schemas render into the model chat template's own
/// <tools> branch and emitted `<tool_call>` blocks parse back into OpenAI `tool_calls` — the
/// model's GGUF chat template remains the sole source of prompt formatting, and the tools
/// path is TEMPLATE + PARSING only (zero engine changes).
#[derive(Deserialize)]
struct ChatCompletionReq {
    model: String,
    messages: Vec<ChatMessage>,
    /// Omitted (gap-scan F2) => context-bounded (session ctx - prompt, model-capped), the
    /// OpenAI default-when-omitted semantics — NOT a silent 128-token truncation.
    #[serde(default, alias = "max_completion_tokens")]
    max_tokens: Option<usize>,
    /// Omitted (dogfood F4) => 1.0, the OpenAI default-when-omitted. See CompletionReq.
    #[serde(default = "default_temperature")]
    temperature: f32,
    #[serde(default = "one")]
    top_p: f32,
    /// Not an OpenAI parameter (OpenRouter/HF convention); 0 = disabled = keep all.
    #[serde(default)]
    top_k: usize,
    /// Not an OpenAI parameter (OpenRouter/HF convention); 0.0 = disabled.
    #[serde(default)]
    min_p: f32,
    /// OpenAI penalties (gap-scan F3): implemented in SamplerConfig all along, now plumbed.
    #[serde(default)]
    frequency_penalty: f32,
    #[serde(default)]
    presence_penalty: f32,
    /// OpenRouter/HF-convention multiplicative penalty (1.0 = off).
    #[serde(default = "one")]
    repetition_penalty: f32,
    /// Omitted (dogfood F4, second half) => a FRESH RANDOM seed per request. See CompletionReq.
    #[serde(default)]
    seed: Option<u64>,
    #[serde(default)]
    stop: StopSequences,
    #[serde(default)]
    stream: bool,
    #[serde(default)]
    max_ctx: Option<usize>,
    /// OpenAI `response_format` (constrained decoding, lane/constrained 2026-08-03):
    /// `{"type":"text"}` (no-op), `{"type":"json_object"}`, and
    /// `{"type":"json_schema","json_schema":{...,"schema":{...}}}` are supported — the
    /// grammar masks logits per decode step (llguidance). Unknown types 400 loudly.
    #[serde(default)]
    response_format: Option<serde_json::Value>,
    #[serde(default)]
    logit_bias: Option<serde_json::Value>,
    #[serde(default)]
    logprobs: Option<serde_json::Value>,
    #[serde(default)]
    top_logprobs: Option<usize>,
    #[serde(default)]
    n: Option<usize>,
    /// OpenAI tool schemas: `[{"type":"function","function":{name,description?,parameters?}}]`.
    #[serde(default)]
    tools: Vec<serde_json::Value>,
    /// "auto" (default) | "none". "required"/named-function need constrained decoding -> 400.
    #[serde(default)]
    tool_choice: Option<serde_json::Value>,
    /// OpenAI reasoning effort — ONE surface, per-arch native mapping (see `parse_think`'s
    /// table): low|medium|high = thinking ON at that budget, none|minimal = thinking OFF,
    /// absent = the model's own default. Binary-switch templates (qwen enable_thinking,
    /// gemma4) take the on/off half; level-consuming templates (step35 `Reasoning:`,
    /// hy3 `reasoning_effort:`) also receive the level.
    #[serde(default)]
    reasoning_effort: Option<String>,
    /// OpenRouter object form: {"effort": "...", "enabled": bool, "exclude": bool}
    /// (max_tokens etc ignored).
    #[serde(default)]
    reasoning: Option<serde_json::Value>,
    /// OpenRouter legacy switch: false = think text is separated AND dropped from the
    /// response (`reasoning.exclude` in the object form does the same).
    #[serde(default)]
    include_reasoning: Option<bool>,
    /// PC-ISO prefix-cache namespace (vLLM `cache_salt` convention, optional): requests
    /// only share cached prefixes with requests carrying the SAME salt. Absent/"" = the
    /// default single-tenant namespace (pre-PC-ISO behavior). See `cache_namespace`.
    #[serde(default)]
    cache_salt: Option<String>,
    /// SESSION AFFINITY explicit tier — see `CompletionReq::session_id` / `affinity_key`.
    #[serde(default)]
    session_id: Option<String>,
    #[serde(default)]
    user: Option<String>,
}
fn one() -> f32 { 1.0 }
/// OpenAI's documented default for an omitted `temperature` on both completion surfaces.
/// Kept distinct from `one()` so the intent is greppable: this is a COMPAT default, not a
/// coincidence that it equals the top_p disable value.
fn default_temperature() -> f32 { 1.0 }

#[derive(Serialize)]
struct CompletionResp {
    model: String,
    text: String,
    tokens: Vec<u32>,
    stop_reason: String,
    n_tokens: usize,
    /// worker-truth prompt accounting (prompt caching): total prompt tokens, and how many
    /// were served from cache (continuation pool / spec resume / cross-request prefix cache).
    prompt_tokens: usize,
    cached_tokens: usize,
    elapsed_s: f64,
}

/// OpenAI-schema usage object, shared by every response shape. `prompt_tokens_details.
/// cached_tokens` is the marketplace prompt-caching field (cache reads bill at a discount;
/// the value is worker-truth — tokens whose KV was resumed instead of computed).
/// `spec` (lane/accept-telemetry) is an ADDITIVE extension: this request's spec-decode
/// rounds/drafted/accepted + acceptance rate. Present only when the request actually ran
/// spec rounds — official SDKs ignore unknown usage fields (extra fields ok, existing
/// fields untouched), and spec-off responses are byte-identical to before.
fn usage_json(n_prompt: usize, n_tokens: usize, n_cached: usize, elapsed_s: f64,
              spec: Option<worker::SpecUsage>) -> serde_json::Value {
    let mut u = json!({
        "prompt_tokens": n_prompt,
        "completion_tokens": n_tokens,
        "total_tokens": n_prompt + n_tokens,
        "prompt_tokens_details": { "cached_tokens": n_cached },
        "elapsed_s": elapsed_s,
    });
    if let Some(sp) = spec {
        u["spec"] = json!({
            "rounds": sp.rounds,
            "drafted": sp.drafted,
            "accepted": sp.accepted,
            "acceptance_rate": if sp.drafted > 0 {
                sp.accepted as f64 / sp.drafted as f64 } else { 0.0 },
        });
    }
    u
}

// ---- OpenAI response envelope (serve-compat lane, 2026-08-03; gap-scan F1) ----
//
// The official `openai` SDKs pydantic-validate every response: `ChatCompletion` /
// `ChatCompletionChunk` REQUIRE `id: str` and `created: int`, so a response without them
// is rejected client-side before the caller ever sees the content. Every OpenAI-shape
// completion and every stream chunk therefore carries `id` + `created` +
// `system_fingerprint`; the id doubles as the `x-request-id` response header (vLLM
// convention, serving_engine.py) for support/tracing. The memra-native response shape
// (non-chat, MEMRA_COMPAT unset) is untouched — validation harnesses depend on it.

/// Backend-config fingerprint: the build's git SHA (baked by build.rs). Together with
/// `seed`, responses are checkable for determinism across deploys — the OpenAI
/// `system_fingerprint` contract.
const SYSTEM_FINGERPRINT: &str = concat!("memra-", env!("MEMRA_BUILD_SHA"));

/// 128 random-ish hex bits: two RandomState-seeded hashes over a process counter + time.
/// Uniqueness class (request ids), not crypto.
fn gen_hex128() -> String {
    use std::hash::{BuildHasher, Hasher};
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let t = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    let mut h1 = std::collections::hash_map::RandomState::new().build_hasher();
    h1.write_u64(n);
    h1.write_u64(t);
    let mut h2 = std::collections::hash_map::RandomState::new().build_hasher();
    h2.write_u64(t.rotate_left(17));
    h2.write_u64(n);
    format!("{:016x}{:016x}", h1.finish(), h2.finish())
}

/// One request's envelope identity: the completion `id` (`chatcmpl-…` chat, `cmpl-…`
/// text) + `created` unix seconds, shared by the response and every chunk of its stream.
#[derive(Clone)]
struct Envelope {
    id: String,
    created: u64,
}

impl Envelope {
    fn new(chat: bool) -> Self {
        Envelope {
            id: format!("{}-{}", if chat { "chatcmpl" } else { "cmpl" }, gen_hex128()),
            created: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
        }
    }

    /// Stamp the envelope fields onto one completion/chunk payload.
    fn stamp(&self, mut v: serde_json::Value) -> serde_json::Value {
        v["id"] = json!(self.id);
        v["created"] = json!(self.created);
        v["system_fingerprint"] = json!(SYSTEM_FINGERPRINT);
        v
    }
}

/// Attach the request id as the `x-request-id` response header.
fn with_request_id(id: &str, mut resp: Response) -> Response {
    if let Ok(v) = axum::http::HeaderValue::from_str(id) {
        resp.headers_mut()
            .insert(axum::http::HeaderName::from_static("x-request-id"), v);
    }
    resp
}

/// OpenAI-compat mapping (2026-07-05, serve-parity arc): the pi daily client speaks
/// `openai-completions` — POST /v1/completions with the OpenAI body, expecting
/// `{choices:[{text, finish_reason, index}], usage:{...}}` and, when streaming, OpenAI SSE
/// chunks (`data: {choices:[{text}]}` ... `data: [DONE]`). pi renders the chat template
/// CLIENT-side (thinkingFormat qwen-chat-template), so raw-prompt completions is the whole
/// contract. MEMRA_COMPAT=openai (default when MEMRA_API_KEY is set — the pi setup) switches the
/// response shape; the native memra shape stays default otherwise (validation harnesses use it).
fn openai_compat() -> bool {
    static C: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *C.get_or_init(|| {
        match std::env::var("MEMRA_COMPAT").as_deref() {
            Ok("openai") => true,
            Ok(_) => false,
            Err(_) => std::env::var("MEMRA_API_KEY").is_ok(),
        }
    })
}

/// PC-ISO (lane/pc-iso, 2026-08-02): the RAW cache namespace for a request — the vLLM
/// `cache_salt` design (research/cache-tools-20260802/REPORT.md §4): the explicit
/// `cache_salt` body field (OpenAI-compatible extension), else "" — the default
/// single-tenant namespace, byte-identical to pre-PC-ISO behavior. When a keyring is
/// configured (MEMRA_API_KEYS) the handlers wrap this in the tenant scope —
/// `tenant_namespace` -> `t:<tenant>\x1f<salt>` (lane/api-keys) — so per-key identity
/// DOES fold in now; without a keyring the raw form passes through unchanged.
/// Cross-request KV reuse (prefix cache, continuation pool, spec pool)
/// only ever matches entries with an IDENTICAL namespace, so the `cached_tokens` hit oracle
/// can only reveal the caller's own namespace's history (CacheProbe/PROMPTPEEK mitigation).
fn cache_namespace(cache_salt: &Option<String>) -> String {
    cache_salt.clone().unwrap_or_default()
}

/// SESSION AFFINITY explicit tier (lane/session-affinity, 2026-08-05): the caller's own name
/// for this conversation, if it supplies one. A named conversation resumes its parked session
/// directly — no fingerprint guess needed. Accepted conventions, in priority order:
///   1. `session_id` body field — the explicit spelling.
///   2. `user` body field — OpenAI's own field; real clients already send a stable per-user
///      (often per-conversation) value here, so honoring it costs the caller nothing.
///   3. `x-session-id` request header — the convention proxies in front of vLLM/TGI use.
/// Body beats header: the body is the caller's own statement of identity, while a header can
/// be rewritten by an intermediary. Blank/whitespace values are treated as absent (a client
/// sending `"user": ""` must not collapse every conversation onto one session).
///
/// The key is NOT authoritative over tokens. It only NOMINATES a parked session for the exact
/// token-diff test in the worker (`affinity_match`), and only within the request's own
/// (model, cache_ns) pool — so a reused or guessed id can cost a wasted probe, never a wrong
/// resume and never cross-tenant reach.
fn affinity_key(
    session_id: &Option<String>,
    user: &Option<String>,
    headers: &axum::http::HeaderMap,
) -> Option<String> {
    let clean = |s: &str| -> Option<String> {
        let t = s.trim();
        if t.is_empty() { None } else { Some(t.to_string()) }
    };
    session_id.as_deref().and_then(clean)
        .or_else(|| user.as_deref().and_then(clean))
        .or_else(|| headers.get("x-session-id")
            .and_then(|v| v.to_str().ok())
            .and_then(clean))
}

/// OpenAI error body: `{"error": {"message", "type", "param", "code"}}` — the object
/// shape every OpenAI SDK parses (gap-scan F1; the old `{"error": "<string>"}` made
/// clients show a blank error). `type` follows the OpenAI vocabulary:
/// invalid_request_error / authentication_error / not_found_error / server_error.
fn error_body(message: &str, etype: &str, param: Option<&str>, code: Option<&str>)
    -> serde_json::Value {
    json!({ "error": {
        "message": message,
        "type": etype,
        "param": param,
        "code": code,
    } })
}

fn error_response(status: StatusCode, message: &str, etype: &str, param: Option<&str>)
    -> Response {
    error_response_coded(status, message, etype, param, None)
}

/// Same, with an explicit OpenAI `code`. Handler-layer refusals (auth, lane, request parsing)
/// land here; engine-produced faults land in `engine_error_response`. Both attach
/// `x-should-retry: false` on a 4xx that retrying the identical bytes cannot fix, so the two
/// halves of the surface behave identically to a client that retries by status alone.
fn error_response_coded(status: StatusCode, message: &str, etype: &str,
                        param: Option<&str>, code: Option<&str>) -> Response {
    let mut resp = (status, Json(error_body(message, etype, param, code))).into_response();
    if status.is_client_error() && status != StatusCode::TOO_MANY_REQUESTS
        && status != StatusCode::REQUEST_TIMEOUT && status != StatusCode::CONFLICT {
        resp.headers_mut()
            .insert("x-should-retry", axum::http::HeaderValue::from_static("false"));
    }
    resp
}

fn bad_request(message: &str, param: Option<&str>) -> Response {
    error_response(StatusCode::BAD_REQUEST, message, "invalid_request_error", param)
}

// ---- engine-fault taxonomy -> HTTP (lane/serve-hardening, G6) --------------------------
//
// WHAT THIS REPLACES. Every worker failure — CUDA errors, VRAM exhaustion, admission sheds,
// tokenizer failures, graph faults — used to funnel into ONE line: `bad_request(&msg, None)`,
// i.e. HTTP 400 invalid_request_error. That is wrong in both directions and both directions
// cost money:
//   * a client SDK never retries a 400 (openai-python retries 408/409/429/>=500 only), so a
//     transient capacity blip became a hard user-visible failure with no retry;
//   * a router cannot tell "your request was malformed" from "my GPU fell over", so it keeps
//     sending traffic to a broken box instead of failing over.
// The class now comes from the PRODUCER (worker.rs::EngineError), not from re-guessing at the
// HTTP layer, with exactly one deliberate text rule (`is_cuda_oom` -> Overloaded).
//
// THE RETRY CONTRACT, verified against the client code rather than the docs:
//   * `Retry-After` is INTEGER seconds (RFC 9110 §10.2.3 delay-seconds — a float here is
//     simply unparseable), and openai-python ABANDONS the retry entirely if the value exceeds
//     its MAX_RETRY_AFTER_DELAY of 120 s. litellm honors the header only for 0 < v <= 60.
//     So every value memra emits is an integer and <= 60.
//   * `retry-after-ms` is read FIRST by openai-python, which lets us express sub-second
//     backoff to SDKs that support it while the integer header stays correct for everyone
//     else. Both are sent; they agree.
//   * `x-should-retry: false` is openai-python's explicit override, used where retrying is
//     provably pointless (a 400-class fault), so a client that retries by status alone does
//     not hammer a request that can never succeed.
const RETRY_AFTER_S_RATE_LIMIT: u64 = 2;   // QoS shed: the lane's own budget window
const RETRY_AFTER_S_OVERLOADED: u64 = 5;   // VRAM/capacity: needs a session to finish first

/// Status + OpenAI `type` + `code` for one engine error class.
fn class_http(class: worker::ErrClass) -> (StatusCode, &'static str, Option<&'static str>) {
    use worker::ErrClass as C;
    match class {
        C::InvalidRequest => (StatusCode::BAD_REQUEST, "invalid_request_error", None),
        C::ContextLength => (StatusCode::BAD_REQUEST, "invalid_request_error",
                             Some("context_length_exceeded")),
        C::ModelNotFound => (StatusCode::BAD_REQUEST, "invalid_request_error",
                             Some("model_not_found")),
        C::RateLimit => (StatusCode::TOO_MANY_REQUESTS, "rate_limit_error", Some("rate_limit_exceeded")),
        C::Overloaded => (StatusCode::SERVICE_UNAVAILABLE, "server_error", Some("overloaded")),
        C::Engine => (StatusCode::INTERNAL_SERVER_ERROR, "server_error", Some("engine_error")),
    }
}

/// Retry-After seconds for a class, or None when retrying cannot help.
fn class_retry_after_s(class: worker::ErrClass) -> Option<u64> {
    use worker::ErrClass as C;
    match class {
        C::RateLimit => Some(RETRY_AFTER_S_RATE_LIMIT),
        C::Overloaded => Some(RETRY_AFTER_S_OVERLOADED),
        // An engine fault is not time-bounded: this process may need to be restarted. Say
        // nothing rather than promise a window we cannot honor — the SDK's own exponential
        // backoff (500s are retryable by default) is the honest behavior here.
        C::Engine | C::InvalidRequest | C::ContextLength | C::ModelNotFound => None,
    }
}

/// The JSON body for an engine error, shared by the blocking and the streaming paths so a
/// client sees the SAME object either way.
fn engine_error_body(e: &worker::EngineError) -> serde_json::Value {
    let (_, etype, code) = class_http(e.class);
    error_body(&e.message, etype, e.param, code)
}

/// Full HTTP response for an engine error: status, OpenAI body, and the retry headers.
fn engine_error_response(e: &worker::EngineError) -> Response {
    engine_error_response_with_retry_after(e, class_retry_after_s(e.class))
}

fn engine_error_response_with_retry_after(
    e: &worker::EngineError,
    retry_after_s: Option<u64>,
) -> Response {
    let (status, _, _) = class_http(e.class);
    let resp = (status, Json(engine_error_body(e))).into_response();
    retry_contract_response(resp, retry_after_s)
}

/// Apply memra's retry headers to any response body.
fn retry_contract_response(mut resp: Response, retry_after_s: Option<u64>) -> Response {
    let status = resp.status();
    let h = resp.headers_mut();
    match retry_after_s {
        Some(secs) => {
            // Integer seconds in the SDK-honored 1..=60 window (see the contract note above).
            let secs = secs.clamp(1, 60);
            if let Ok(v) = axum::http::HeaderValue::from_str(&secs.to_string()) {
                h.insert(axum::http::header::RETRY_AFTER, v);
            }
            if let Ok(v) = axum::http::HeaderValue::from_str(&(secs * 1000).to_string()) {
                h.insert("retry-after-ms", v);
            }
        }
        None if status.is_client_error() => {
            // A malformed request, an unknown model, an over-long prompt: retrying the
            // identical bytes cannot succeed. Say so explicitly.
            h.insert("x-should-retry", axum::http::HeaderValue::from_static("false"));
        }
        None => {}
    }
    resp
}

fn worker_unavailable_response() -> Response {
    engine_error_response_with_retry_after(
        &worker::EngineError::overloaded("worker unavailable"),
        Some(worker::WORKER_RESPAWN_BACKOFF_BASE_S),
    )
}

fn stop_reason_to_finish(r: &str) -> &'static str {
    match r {
        "Eos" | "Callback" => "stop",
        "MaxNew" | "ContextFull" => "length",
        _ => "stop",
    }
}

// ---- tools surface helpers (serve-tools lane, 2026-08-02) ----

/// Flatten an OpenAI `content` value to text: string, null (-> ""), or `{type:"text"}` parts.
fn content_to_text(v: &serde_json::Value) -> Result<String, String> {
    match v {
        serde_json::Value::Null => Ok(String::new()),
        serde_json::Value::String(s) => Ok(s.clone()),
        serde_json::Value::Array(parts) => {
            let mut out = String::new();
            for p in parts {
                match p.get("type").and_then(|t| t.as_str()) {
                    Some("text") | None => match p.get("text").and_then(|t| t.as_str()) {
                        Some(t) => out.push_str(t),
                        None => return Err("content part has no text field".into()),
                    },
                    Some(other) => {
                        return Err(format!("unsupported content part type {other:?} (text only)"));
                    }
                }
            }
            Ok(out)
        }
        _ => Err("content must be a string, null, or an array of text parts".into()),
    }
}

/// Render a JSON value the way the reference template's `tojson` does (python json.dumps:
/// `", "` / `": "` separators, insertion-order keys — serde_json preserve_order — non-ASCII
/// left raw). The tools block is prompt bytes, so the training-time convention is the law.
fn pyjson(v: &serde_json::Value, out: &mut String) {
    match v {
        serde_json::Value::Object(m) => {
            out.push('{');
            for (i, (k, val)) in m.iter().enumerate() {
                if i > 0 { out.push_str(", "); }
                out.push_str(&serde_json::Value::String(k.clone()).to_string());
                out.push_str(": ");
                pyjson(val, out);
            }
            out.push('}');
        }
        serde_json::Value::Array(a) => {
            out.push('[');
            for (i, val) in a.iter().enumerate() {
                if i > 0 { out.push_str(", "); }
                pyjson(val, out);
            }
            out.push(']');
        }
        scalar => out.push_str(&scalar.to_string()),
    }
}

fn pyjson_str(v: &serde_json::Value) -> String {
    let mut s = String::new();
    pyjson(v, &mut s);
    s
}

/// Sampler wiring shared by both bodies (gap-scan F3): the penalties existed in
/// SamplerConfig end-to-end (host sampler + spec rejection-sampling verify) — this is
/// pure request-struct plumbing. OpenAI penalties apply over the full context window;
/// SamplerConfig models that as a last-n history window, so an active penalty arms the
/// whole-history window (usize::MAX — `saturating_sub` makes it the full history).
fn sampler_config(temperature: f32, top_k: usize, top_p: f32, min_p: f32,
                  frequency_penalty: f32, presence_penalty: f32, repetition_penalty: f32,
                  seed: Option<u64>) -> SamplerConfig {
    let penalties_on = frequency_penalty != 0.0 || presence_penalty != 0.0
        || repetition_penalty != 1.0;
    SamplerConfig {
        temperature,
        top_k,
        top_p,
        min_p,
        penalty_last_n: if penalties_on { usize::MAX } else { 0 },
        penalty_repeat: repetition_penalty,
        penalty_freq: frequency_penalty,
        penalty_present: presence_penalty,
        // Omitted seed => fresh entropy per request (dogfood F4). An explicit seed — including
        // an explicit 0 — is honored exactly, so every determinism gate keeps its behavior.
        seed: seed.unwrap_or_else(fresh_seed),
    }
}

/// Non-zero per-request entropy for seed-omitting clients. Nanosecond clock mixed with a
/// process-lifetime counter through SplitMix64's finalizer: two requests in the same
/// nanosecond tick (batched arrivals) still get distinct streams, which a bare clock read
/// would not guarantee. Not crypto — this only has to avoid replaying one stream forever.
fn fresh_seed() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    let mut z = nanos
        .wrapping_add(n.wrapping_mul(0x9E3779B97F4A7C15))
        .wrapping_add(0x9E3779B97F4A7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
    z ^= z >> 31;
    // seed 0 is a legal explicit value but a poor accidental one; keep it reachable only
    // when the caller asks for it.
    if z == 0 { 0x9E3779B97F4A7C15 } else { z }
}

/// Honesty gate (gap-scan F4): semantic params we cannot honor are explicit 400s with the
/// offending param named — never silent downgrades (a client sending response_format:
/// json_object would get unvalidated free text and no error). Cosmetic fields (`user`,
/// `stream_options`) stay accept-and-ignore.
fn reject_unsupported(fields: &[(&str, bool, &str)]) -> Result<(), (String, String)> {
    for (param, present, why) in fields {
        if *present {
            return Err((format!("{param} is not supported{why}"), param.to_string()));
        }
    }
    Ok(())
}

#[derive(PartialEq)]
enum ToolChoice { Auto, None }

fn parse_tool_choice(v: &Option<serde_json::Value>) -> Result<ToolChoice, String> {
    match v {
        None | Some(serde_json::Value::Null) => Ok(ToolChoice::Auto),
        Some(serde_json::Value::String(s)) => match s.as_str() {
            "auto" => Ok(ToolChoice::Auto),
            "none" => Ok(ToolChoice::None),
            "required" => Err("tool_choice \"required\" is not supported (no constrained \
                               decoding); use \"auto\"".into()),
            other => Err(format!("bad tool_choice {other:?} (auto|none)")),
        },
        Some(serde_json::Value::Object(_)) =>
            Err("named-function tool_choice is not supported; use \"auto\"".into()),
        Some(other) => Err(format!("bad tool_choice: {other}")),
    }
}

/// Map OpenAI `reasoning_effort` / OpenRouter `reasoning` onto the model's native thinking
/// control — ONE serve surface, per-arch mechanism (owner directive 2026-08-07: every
/// supported model is a thinking model).
///
/// The OpenAI/OpenRouter convention for reasoning-capable models: `low|medium|high` all mean
/// reasoning ON at that budget; `none|minimal` request (near-)zero reasoning; OpenRouter's
/// `reasoning: {enabled: false}` is the explicit off. Absent means the MODEL'S OWN default —
/// never overridden here (no silent behavior change for existing deployments):
///
/// | field value        | ThinkMode | effort level | qwen class      | gemma4        | hy3        | step35            |
/// |--------------------|-----------|--------------|-----------------|---------------|------------|-------------------|
/// | (absent)           | Default   | None         | think ON (tmpl) | think OFF     | no_think   | tail always open  |
/// | none / minimal     | NoThink   | "low"        | closed <think>  | closed channel| no_think   | Reasoning: low    |
/// | low                | Think     | "low"        | open <think>    | <\|think\|> ON| low        | Reasoning: low    |
/// | medium             | Think     | "medium"     | open <think>    | <\|think\|> ON| low (clamp)| Reasoning: medium |
/// | high               | Think     | "high"       | open <think>    | <\|think\|> ON| high       | Reasoning: high   |
/// | {enabled: false}   | NoThink   | "low"        | closed <think>  | closed channel| no_think   | Reasoning: low    |
/// | {enabled: true}    | Think     | None         | open <think>    | <\|think\|> ON| low        | (tmpl default)    |
///
/// Returns `(think, effort_level)`. `effort_level` rides `Request::reasoning_effort` only
/// for templates that consume a level string (`ModelCaps::effort_levels`: step35, hy3);
/// binary-switch templates are carried by `ThinkMode` alone, so their prompts cannot be
/// perturbed by a level they never read.
fn parse_think(reasoning_effort: &Option<String>, reasoning: &Option<serde_json::Value>)
    -> Result<(ThinkMode, Option<String>), String> {
    let mut effort = reasoning_effort.clone();
    let mut enabled = None;
    if let Some(r) = reasoning {
        match r {
            serde_json::Value::Null => {}
            serde_json::Value::Object(obj) => {
                enabled = obj.get("enabled").and_then(|v| v.as_bool());
                if let Some(e) = obj.get("effort").and_then(|v| v.as_str()) {
                    effort = Some(e.to_string());
                }
            }
            _ => return Err("reasoning must be an object".into()),
        }
    }
    if enabled == Some(false) {
        // OpenRouter "thinking off": the strongest off-request either surface can express.
        return Ok((ThinkMode::NoThink, Some("low".to_string())));
    }
    let (think, level) = match effort.as_deref() {
        None => (
            if enabled == Some(true) { ThinkMode::Think } else { ThinkMode::Default },
            None,
        ),
        Some("none") | Some("minimal") => (ThinkMode::NoThink, Some("low".to_string())),
        Some("low") => (ThinkMode::Think, Some("low".to_string())),
        Some("medium") => (ThinkMode::Think, Some("medium".to_string())),
        Some("high") => (ThinkMode::Think, Some("high".to_string())),
        Some(other) => return Err(format!(
            "bad reasoning_effort {other:?} (none|minimal|low|medium|high)")),
    };
    Ok((think, level))
}

/// Validate tool schemas and pre-serialize them for the template's <tools> block; also
/// extract declared parameter types (function -> parameter -> type) for argument coercion.
#[allow(clippy::type_complexity)]
fn prepare_tools(tools: &[serde_json::Value])
    -> Result<(Vec<String>, HashMap<String, HashMap<String, String>>), String> {
    let mut tools_json = Vec::with_capacity(tools.len());
    let mut schemas: HashMap<String, HashMap<String, String>> = HashMap::new();
    for t in tools {
        let f = t.get("function").ok_or("each tool needs a function object")?;
        let name = f.get("name").and_then(|n| n.as_str())
            .ok_or("each tool needs function.name")?;
        let mut params: HashMap<String, String> = HashMap::new();
        if let Some(props) = f.get("parameters").and_then(|p| p.get("properties"))
            .and_then(|p| p.as_object()) {
            for (p, def) in props {
                if let Some(ty) = def.get("type").and_then(|t| t.as_str()) {
                    params.insert(p.clone(), ty.to_string());
                }
            }
        }
        schemas.insert(name.to_string(), params);
        tools_json.push(pyjson_str(t));
    }
    Ok((tools_json, schemas))
}

/// Re-render an assistant-history tool call for the template. Value law mirrors the
/// template's `args_value | tojson if mapping/sequence else | string`: strings raw,
/// objects/arrays python-style JSON; scalars use their JSON text (`true`/`3`/`null` —
/// JSON spelling, not python's, so a parse round-trip stays self-consistent).
fn render_req_tool_call(tc: &ReqToolCall) -> Result<TmplToolCall, String> {
    let parsed: serde_json::Value = match &tc.function.arguments {
        serde_json::Value::Null => json!({}),
        serde_json::Value::String(s) if s.trim().is_empty() => json!({}),
        serde_json::Value::String(s) => serde_json::from_str(s)
            .map_err(|e| format!("tool_calls arguments is not valid JSON: {e}"))?,
        v @ serde_json::Value::Object(_) => v.clone(),
        _ => return Err("tool_calls arguments must be a JSON object".into()),
    };
    let obj = parsed.as_object()
        .ok_or("tool_calls arguments must decode to a JSON object")?;
    let params = obj.iter().map(|(k, v)| {
        let rendered = match v {
            serde_json::Value::String(s) => s.clone(),
            v @ (serde_json::Value::Object(_) | serde_json::Value::Array(_)) => pyjson_str(v),
            scalar => scalar.to_string(),
        };
        (k.clone(), rendered)
    }).collect();
    Ok(TmplToolCall { name: tc.function.name.clone(), params })
}

/// OpenAI response entry for one parsed call.
fn tool_call_json(c: &ParsedToolCall) -> serde_json::Value {
    json!({ "id": c.id, "type": "function",
            "function": { "name": c.name, "arguments": c.arguments } })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Key lifecycle CLI (lane/api-keys): `--gen-key <tenant>` / `--revoke-key <prefix>`
    // manage the keyring and exit — no engine, no GPU, no model load.
    let args: Vec<String> = std::env::args().skip(1).collect();
    if let Some(code) = auth::run_cli(&args) {
        std::process::exit(code);
    }
    // Keyring (MEMRA_API_KEYS): parsed once here so a bad config is a startup FATAL,
    // not a per-request surprise. Absent = single-key/open behavior, unchanged.
    auth::init_from_env();

    let models = parse_models_config();
    let openrouter_metadata = match load_openrouter_metadata(&models) {
        Ok(metadata) => metadata,
        Err(err) => {
            eprintln!("[server] FATAL: {err}");
            std::process::exit(1);
        }
    };
    eprintln!("[server] starting; models config = {models:?}");

    // Inference-liveness state (G5). Created BEFORE the worker so the whole weight load is
    // observable as PHASE_LOADING rather than as a gap: /livez and /readyz answer honestly
    // from the first accepted connection, which is what a supervisor's Type=notify +
    // WatchdogSec contract and a load balancer's readiness probe both need.
    let health_state = health::WorkerHealth::new();
    // GPU-fault watchers (G24) start before the load too: an Xid that fires DURING a 120 s
    // weight load is exactly the case a post-load watcher misses. spawn_gpu_watch owns the
    // Xid tail as well (one call, two threads).
    health::spawn_gpu_watch(health_state.clone());
    health::spawn_sd_watchdog(health_state.clone());

    // Spawn the GPU worker thread and block until every model is loaded (or it fails).
    let (cmd_tx, model_names, caps, metrics) = match worker::spawn(models, health_state.clone()) {
        Ok(v) => v,
        Err(err) => {
            eprintln!("[server] FATAL: worker init failed: {err}");
            health_state.mark_dead(format!("worker init failed: {err}"));
            health::sd_notify(&format!("STATUS=worker init failed: {err}"));
            std::process::exit(1);
        }
    };
    eprintln!("[server] worker ready; serving models: {model_names:?}");

    // Dead-darklane background job runner (MEMRA_BG_JOB; lane/darklane-training): armed
    // only after the worker is ready — a weight load is PHASE_LOADING, never a valley.
    let bg_handle = darklane::spawn_from_env(health_state.clone());
    let bg_state = bg_handle.as_ref().map(|h| {
        let mode = darklane::BgConfig::from_env()
            .map(|c| c.yield_mode.as_str()).unwrap_or("stop");
        (h.state.clone(), mode)
    });

    let state = AppState {
        cmd_tx, models: model_names, caps,
        openrouter_metadata: Arc::new(openrouter_metadata),
        metrics,
        started: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs()).unwrap_or(0),
        inflight: Arc::new(Default::default()),
        tenant_inflight: Arc::new(Default::default()),
        health: health_state.clone(),
        bg: bg_state,
    };
    let inflight_handle = state.inflight.clone();
    let app = Router::new()
        // /health is the historical name (every memra script polls it) and stays the
        // LIVENESS probe; /livez + /readyz are the k8s-doctrine split (healthz deprecated
        // upstream at v1.16). Readiness ≠ liveness: draining or a not-yet-loaded model
        // takes the box out of ROTATION without asking a supervisor to kill it.
        .route("/health", get(health_live))
        .route("/livez", get(health_live))
        .route("/readyz", get(health_ready))
        .route("/models", get(list_models))
        .route("/v1/models", get(list_models_v1))
        .route("/v1/completions", post(completions))
        .route("/v1/chat/completions", post(chat_completions))
        .route("/metrics", get(get_metrics))
        .route("/yield/metrics", get(yield_metrics))
        .with_state(state);

    let addr = std::env::var("MEMRA_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into());
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    eprintln!("[server] listening on http://{addr}");
    // READY=1 only AFTER the models are resident and the socket is bound — the whole point of
    // Type=notify is that "started" means "can serve". A no-op when NOTIFY_SOCKET is unset
    // (i.e. every non-systemd run), so it costs nothing outside a unit.
    health::sd_notify("READY=1\nSTATUS=serving");
    // GRACEFUL DRAIN (gap-scan F11): SIGTERM flips the drain flag (new completion
    // requests 503 immediately; /health reports "draining"), then the shutdown future
    // resolves once every in-flight request finished (the HTTP-layer gauge — streams
    // hold their slot until fully written) or the MEMRA_DRAIN_S deadline (default 30s)
    // passed. axum's graceful shutdown stops accepting, lets tracked connections finish
    // their current response, and returns — exit 0 (in-flight loss only past deadline).
    let inflight = inflight_handle;
    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            let mut sigterm = match tokio::signal::unix::signal(
                tokio::signal::unix::SignalKind::terminate()) {
                Ok(s) => s,
                Err(err) => {
                    eprintln!("[server] WARN: no SIGTERM handler ({err}); drain disabled");
                    std::future::pending::<()>().await;
                    unreachable!()
                }
            };
            sigterm.recv().await;
            DRAINING.store(true, std::sync::atomic::Ordering::SeqCst);
            // STOPPING=1 + EXTEND_TIMEOUT_USEC: tell systemd the stop is deliberate and how
            // long the drain may legitimately take, so TimeoutStopSec does not SIGKILL a
            // healthy drain mid-stream (audit's systemd section).
            health::sd_notify(&format!(
                "STOPPING=1\nSTATUS=draining\nEXTEND_TIMEOUT_USEC={}",
                (drain_deadline_s() + 5) * 1_000_000));
            let n: usize = inflight.iter()
                .map(|c| c.load(std::sync::atomic::Ordering::SeqCst)).sum();
            eprintln!("[server] SIGTERM: draining ({n} in flight, deadline {}s)",
                      drain_deadline_s());
            let deadline = std::time::Duration::from_secs(drain_deadline_s());
            let t0 = std::time::Instant::now();
            loop {
                let n: usize = inflight.iter()
                    .map(|c| c.load(std::sync::atomic::Ordering::SeqCst)).sum();
                if n == 0 {
                    eprintln!("[server] drain complete in {:.1}s; exiting",
                              t0.elapsed().as_secs_f64());
                    break;
                }
                if t0.elapsed() >= deadline {
                    eprintln!("[server] drain deadline ({}s) hit with {n} in flight; exiting",
                              drain_deadline_s());
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
        })
        .await?;
    // Background job cleanup on the graceful path: SIGCONT+SIGTERM(+KILL past grace) the
    // job's process group — a SIGSTOPped orphan would stay frozen forever. The ungraceful
    // path (server SIGKILL) is covered by PDEATHSIG on the child.
    if let Some(h) = bg_handle {
        h.shutdown();
    }
    Ok(())
}

/// Validate a resolved model-plan path BEFORE the worker thread spins up: a FILE loads as
/// GGUF; a DIRECTORY must be an HF safetensors checkpoint (`config.json` +
/// `model.safetensors` or `model.safetensors.index.json` — the run-safetensors load path)
/// or a memra repack dir (`manifest.json`). A clear error at parse time beats a worker
/// load failure after the Engine is already up.
fn validate_model_path(path: &str) -> Result<(), String> {
    let p = std::path::Path::new(path);
    if !p.exists() {
        return Err(format!("model path {path:?} does not exist"));
    }
    if p.is_file() {
        return Ok(()); // GGUF file (the worker's file branch)
    }
    if p.join("manifest.json").exists() {
        return Ok(()); // memra repack/overlay dir
    }
    let has_st = p.join("model.safetensors").exists()
        || p.join("model.safetensors.index.json").exists();
    if !has_st {
        return Err(format!(
            "model dir {path:?} is not a servable checkpoint: want model.safetensors or \
             model.safetensors.index.json + config.json (HF safetensors dir), or \
             manifest.json (memra repack dir)"));
    }
    if !p.join("config.json").exists() {
        return Err(format!("model dir {path:?} has safetensors weights but no config.json"));
    }
    Ok(())
}

/// MEMRA_MODELS="name=/path.gguf[+/draft.gguf],name2=hf:owner/repo,name3=/hf_ckpt_dir".
/// Falls back to the BASE-4 test pair. `+<draft.gguf>` after a model path attaches that
/// model's regime draft (docs/DRAFT-REGIME.md) — per model, not the global MEMRA_MTP_DRAFT
/// env, so a multi-model server gives each model its own draft. Both parts accept hf: specs.
/// A model path may also be an HF safetensors checkpoint DIRECTORY (serve-st lane,
/// 2026-08-04) — validated by `validate_model_path`, loaded through the same
/// SafetensorsSource seam as run-safetensors/run-gen.
fn parse_models_config() -> Vec<(String, String, Option<String>)> {
    if let Ok(spec) = std::env::var("MEMRA_MODELS") {
        let mut out = Vec::new();
        for entry in spec.split(',').filter(|s| !s.trim().is_empty()) {
            if let Some((name, path)) = entry.split_once('=') {
                // Paths accept hf:owner/repo[:file] specs — resolved (downloaded on first
                // use) before the worker sees them.
                let (mpath, dpath) = match path.trim().split_once('+') {
                    Some((m, d)) => (m.trim(), Some(d.trim())),
                    None => (path.trim(), None),
                };
                let resolve = |p: &str| memra_gguf::hf::resolve_arg(p).unwrap_or_else(|err| {
                    eprintln!("[server] FATAL: model {name:?}: {err}");
                    std::process::exit(1);
                });
                let mpath = resolve(mpath);
                if let Err(err) = validate_model_path(&mpath) {
                    eprintln!("[server] FATAL: model {name:?}: {err}");
                    std::process::exit(1);
                }
                // The DRAFT path gets the same parse-time existence check as the model path
                // (lane/step-draft, 2026-08-07). It did not, and the asymmetry cost a class of
                // late failure: a typo'd or unmounted drafter path survived parse, survived the
                // hf resolve, and only failed after the worker had already spent the whole
                // trunk load on the GPU — so on a busy card the operator got
                // `CUDA_ERROR_OUT_OF_MEMORY` on the TRUNK and never learned the drafter path
                // was wrong at all. Found by this lane's own gate arm D. A drafter must be a
                // FILE: `load_draft` opens it as a GGUF, so the dir forms `validate_model_path`
                // admits are not valid here.
                let dpath = dpath.map(|d| {
                    let d = resolve(d);
                    let p = std::path::Path::new(&d);
                    if !p.exists() {
                        eprintln!("[server] FATAL: model {name:?}: drafter path {d:?} does not \
                                   exist (MEMRA_MODELS '+draft' attach). Refusing to start \
                                   rather than serving plain decode under a config that asked \
                                   for speculative decoding.");
                        std::process::exit(1);
                    }
                    if !p.is_file() {
                        eprintln!("[server] FATAL: model {name:?}: drafter path {d:?} is not a \
                                   file — a '+draft' attach must be a NextN/MTP GGUF file.");
                        std::process::exit(1);
                    }
                    d
                });
                out.push((name.trim().to_string(), mpath, dpath));
            } else {
                eprintln!("[server] WARN: bad MEMRA_MODELS entry {entry:?} (want name=/path[+/draft]); skipping");
            }
        }
        if !out.is_empty() { return out; }
    }
    // Default: the BASE-4 test pair (main=27B, judge=9B).
    vec![
        ("main".into(),  "/data/ai-ml/hf-models/qwen36-27b-nvfp4-mtp/Qwen3.6-27B-NVFP4-Q4_K_M-mtp.gguf".into(), None),
        ("judge".into(), "/data/ai-ml/hf-models/qwen35-9b-nvfp4-gguf/Qwen3.5-9B-NVFP4-MTP-GGUF.gguf".into(), None),
    ]
}

/// Shared body for both probes: the honest state, plus the numbers that explain it.
fn health_payload(st: &AppState, status: &str, detail: Option<&str>) -> serde_json::Value {
    let s = st.health.snapshot();
    let mut v = json!({
        "status": status,
        "models": *st.models,
        "worker": {
            "phase": health::phase_name(s.phase),
            "beat_age_ms": s.beat_age_ms,
            "tick_max_ms": s.tick_max_ms,
            "stall_threshold_ms": s.stall_threshold_ms,
            "generation": s.generation,
            "xid_warnings": s.xid_warns,
        },
    });
    if let Some(d) = detail {
        v["detail"] = json!(d);
    }
    v
}

/// LIVENESS (`/health`, `/livez`) — INFERENCE liveness, not process liveness (G5).
///
/// WHAT CHANGED AND WHY. The old handler returned 200 whenever the HTTP task was scheduled:
/// a panicked GPU worker, a wedged GPU, a poisoned CUDA context — all reported "ok" forever,
/// on a box that answered nothing. Now the answer is derived ONLY from worker state: a
/// heartbeat the scheduler loop stamps every iteration, the panic/GPU fault latches, and the
/// load phase.
///
/// 503 (dead / GPU-faulted / stalled / still loading) is deliberately a
/// SUPERVISOR-ACTIONABLE signal — the only recovery for a sticky CUDA fault is restarting the
/// process, so this endpoint is what makes `Restart=on-failure` + a liveness probe work.
///
/// DRAINING stays **200**: a drain is a healthy, deliberate shutdown, and answering 503 here
/// would invite a supervisor to kill the process in the middle of finishing in-flight
/// streams. Rotation is `/readyz`'s job — that is the whole reason the two are separate.
async fn health_live(State(st): State<AppState>) -> impl IntoResponse {
    if draining() {
        // "draining" = the LB/orchestrator not-ready signal (gap-scan F11): the process is
        // finishing in-flight work and will exit; route new traffic elsewhere.
        return (StatusCode::OK, Json(health_payload(&st, "draining", None))).into_response();
    }
    match st.health.live() {
        Ok(()) => (StatusCode::OK, Json(health_payload(&st, "ok", None))).into_response(),
        Err(why) => retry_contract_response(
            (StatusCode::SERVICE_UNAVAILABLE,
             Json(health_payload(&st, "unhealthy", Some(&why)))).into_response(),
            Some(worker::WORKER_RESPAWN_BACKOFF_BASE_S),
        ),
    }
}

/// READINESS (`/readyz`) — "should this instance receive traffic right now?"
///
/// Ready = model loaded AND worker alive AND not draining. Unready is NOT a request for a
/// restart: draining and still-loading are both perfectly healthy states that simply must not
/// be routed to. k8s doctrine (`/livez` + `/readyz`; `healthz` deprecated at v1.16), and ahead
/// of both vLLM (no readiness endpoint) and TGI (single `/health`).
///
/// Queue pressure deliberately does NOT flip readiness: memra's interactive lane queues FIFO
/// and never sheds, so a deep queue is work in progress, not unreadiness. Capacity backpressure
/// belongs on the request path as 429/503 (G6), where a client can act on it.
async fn health_ready(State(st): State<AppState>) -> impl IntoResponse {
    let is_draining = draining();
    match st.health.ready(is_draining) {
        Ok(()) => (StatusCode::OK, Json(health_payload(&st, "ready", None))).into_response(),
        Err(why) => retry_contract_response(
            (StatusCode::SERVICE_UNAVAILABLE,
             Json(health_payload(&st, "not_ready", Some(&why)))).into_response(),
            Some(if is_draining {
                drain_deadline_s()
            } else {
                worker::WORKER_RESPAWN_BACKOFF_BASE_S
            }),
        ),
    }
}

/// Flat serving counters + engine-truth step latency percentiles.
async fn get_metrics(State(st): State<AppState>) -> impl IntoResponse {
    let m = st.metrics.lock().map(|m| m.clone()).unwrap_or_default();
    // Valley signal (lane/darklane-training): seconds the worker has been COMPLETELY idle
    // (no active sessions, no queued admissions, no pending HTTP handoffs) — worker truth
    // via health phase + beat age + the PENDING_ADMITS gauge, no new hot-path cost.
    // 0.0 the instant there is any work. Always published: the field is the idle sensor
    // whether or not a background job is configured.
    let idle_s = darklane::ValleySignal::new(st.health.clone()).idle_seconds();
    let mut body = json!({
        "admitted": m.admitted,
        "completed": m.completed,
        "tokens_out": m.tokens_out,
        "step_p50_ms": m.step_p50_ms,
        "step_p99_ms": m.step_p99_ms,
        // worker-truth prompt caching split (cached = resumed from any KV cache tier).
        "prompt_tokens_in": m.prompt_tokens_in,
        "cached_tokens_in": m.cached_tokens_in,
        // computed = actually primed; the denominator of the revenue multiplier
        // (billed prompt tokens / computed prompt tokens — tools/cache_economics.py).
        "computed_tokens_in": m.prompt_tokens_in.saturating_sub(m.cached_tokens_in),
        // token-weighted hit ratio: what fraction of admitted prompt tokens were served
        // from a cache instead of being computed. THE hit-rate receipt number.
        "cache_hit_token_ratio": if m.prompt_tokens_in > 0 {
            m.cached_tokens_in as f64 / m.prompt_tokens_in as f64 } else { 0.0 },
        "prefix_cache_hits": m.prefix_hits,
        "prefix_cache_entries": m.prefix_entries,
        "prefix_cache_bytes": m.prefix_bytes,
        // full prefix-cache counter set (lane/cache-metering): probe outcomes + churn.
        "prefix_cache_misses": m.prefix_misses,
        "prefix_cache_inserts": m.prefix_inserts,
        "prefix_cache_evictions": m.prefix_evictions,
        "prefix_cache_hit_tokens": m.prefix_hit_tokens,
        // LCP length histogram: one sample per prefix-cache probe (hit -> served entry
        // length; miss -> best LCP against the pool). `edges` are lower bucket edges,
        // last bucket unbounded. The [64,512) window (buckets 4..=6) is the tick-seg
        // segmentation class — how often real traffic lands there is this histogram's
        // reason to exist.
        "lcp_histogram": {
            "edges": worker::LCP_HIST_EDGES.to_vec(),
            "counts": m.lcp_hist.to_vec(),
        },
        "serve_idle_seconds": (idle_s * 1000.0).round() / 1000.0,
    });
    // Per-tenant prompt/cached breakdown (composes with PC-ISO tenancy): keyring
    // deployments key rows by tenant (`t:<tenant>`), no-keyring by raw cache_salt
    // ("" = the default namespace). ABSENT until the first admit, so a fresh server's
    // /metrics is otherwise unchanged. Bounded rows; overflow aggregates in "(other)".
    if !m.ns_tokens.is_empty() {
        let tenants: serde_json::Map<String, serde_json::Value> = m.ns_tokens.iter()
            .map(|(ns, [p, c])| (ns.clone(), json!({
                "prompt_tokens_in": p,
                "cached_tokens_in": c,
                "cache_hit_token_ratio": if *p > 0 { *c as f64 / *p as f64 } else { 0.0 },
            })))
            .collect();
        body["tenants"] = serde_json::Value::Object(tenants);
    }
    // Background-job block: ABSENT unless MEMRA_BG_JOB armed the runner (pre-lane payload
    // stays byte-identical for every deployment that doesn't use it).
    if let Some((bg, mode)) = &st.bg {
        body["bg"] = bg.to_json(mode);
    }
    // Spec-decode acceptance telemetry (lane/accept-telemetry — the llama.cpp #26389 /
    // vLLM per-draft-position counter schema). Per model, cumulative since model load
    // (models load once per process — counters reset on restart, never mid-run). The
    // block is ABSENT until a spec burst runs: spec-off deployments see the exact
    // pre-lane payload. accept_rate_per_pos[j] = P(position j accepted | round offered
    // position j) — sane spec decode decays monotonically from pos 0.
    let spec: serde_json::Map<String, serde_json::Value> = m.spec.iter().map(|(model, t)| {
        let n_pos = t.pos_drafted.iter().rposition(|&d| d > 0).map_or(0, |p| p + 1);
        (model.clone(), json!({
            "rounds": t.rounds,
            "drafted": t.drafted,
            "accepted": t.accepted,
            "acceptance_rate": if t.drafted > 0 {
                t.accepted as f64 / t.drafted as f64 } else { 0.0 },
            "tokens_per_round": if t.rounds > 0 {
                (t.accepted + t.rounds) as f64 / t.rounds as f64 } else { 0.0 },
            "pos_drafted": t.pos_drafted[..n_pos].to_vec(),
            "pos_accepted": t.pos_accepted[..n_pos].to_vec(),
            "accept_rate_per_pos": (0..n_pos).map(|j| if t.pos_drafted[j] > 0 {
                t.pos_accepted[j] as f64 / t.pos_drafted[j] as f64 } else { 0.0 })
                .collect::<Vec<f64>>(),
        }))
    }).collect();
    if !spec.is_empty() {
        body["spec"] = serde_json::Value::Object(spec);
    }
    Json(body)
}

#[derive(Debug, Default, Deserialize)]
struct ModelsQuery {
    #[serde(default)]
    schema: Option<String>,
}

fn models_openai_body(models: &[String]) -> serde_json::Value {
    let data: Vec<_> = models
        .iter()
        .map(|m| json!({ "id": m, "object": "model" }))
        .collect();
    json!({ "object": "list", "data": data })
}

fn openrouter_supported_parameters(
    caps: Option<&ModelCaps>,
    max_output_length: Option<u64>,
) -> serde_json::Value {
    let mut parameters = serde_json::Map::new();
    for name in [
        "temperature",
        "top_p",
        "min_p",
        "frequency_penalty",
        "presence_penalty",
        "repetition_penalty",
        "stop",
    ] {
        parameters.insert(name.into(), json!({ "type": "unknown" }));
    }
    parameters.insert("top_k".into(), json!({ "type": "integer", "min": 0 }));
    parameters.insert(
        "seed".into(),
        json!({ "type": "integer", "min": 0, "max": JSON_SAFE_INTEGER_MAX }),
    );
    let mut max_tokens = json!({ "type": "integer", "min": 1, "unit": "token" });
    if let Some(max) = max_output_length {
        max_tokens["max"] = json!(max);
    }
    parameters.insert("max_tokens".into(), max_tokens);
    parameters.insert("json_mode".into(), json!({ "type": "boolean" }));
    parameters.insert(
        "structured_outputs".into(),
        json!({ "type": "boolean" }),
    );
    if caps.is_some_and(|c| c.tools_branch) {
        parameters.insert("tools".into(), json!({ "type": "boolean" }));
        parameters.insert(
            "tool_choice".into(),
            json!({ "type": "enum", "values": ["auto", "none"] }),
        );
    }
    if caps.is_some_and(|c| c.qwen_think || c.effort_levels || c.gemma_think) {
        parameters.insert("reasoning".into(), json!({ "type": "boolean" }));
    }
    serde_json::Value::Object(parameters)
}

fn model_entry_openrouter(
    name: &str,
    caps: Option<&ModelCaps>,
    metadata: Option<&OpenRouterModelMetadata>,
) -> serde_json::Value {
    let empty = OpenRouterModelMetadata::default();
    let metadata = metadata.unwrap_or(&empty);
    let context_length = caps
        .map(|c| c.context_length as u64)
        .filter(|&v| v > 0 && v <= JSON_SAFE_INTEGER_MAX);
    let tokenizer = caps
        .map(|c| c.tokenizer.as_str())
        .filter(|tokenizer| !tokenizer.is_empty());

    let mut input = serde_json::Map::new();
    input.insert("type".into(), json!("text"));
    let mut supported_inputs = serde_json::Map::new();
    if let Some(value) = context_length {
        supported_inputs.insert(
            "max_context_length".into(),
            json!({ "value": value, "unit": "token" }),
        );
    }
    if let Some(value) = metadata.max_prompt_length {
        supported_inputs.insert(
            "max_prompt_length".into(),
            json!({ "value": value, "unit": "token" }),
        );
    }
    if !supported_inputs.is_empty() {
        input.insert(
            "supported_inputs".into(),
            serde_json::Value::Object(supported_inputs),
        );
    }
    let mut input_pricing = Vec::new();
    for (kind, cost) in [
        ("prompt", metadata.pricing.prompt.as_deref()),
        (
            "cached_prompt",
            metadata.pricing.cached_prompt.as_deref(),
        ),
        ("cache_write", metadata.pricing.cache_write.as_deref()),
    ] {
        if let Some(cost) = cost {
            input_pricing.push(json!({
                "type": kind,
                "unit": "token",
                "cost_usd": cost,
            }));
        }
    }
    if !input_pricing.is_empty() {
        input.insert("pricing".into(), serde_json::Value::Array(input_pricing));
    }
    let mut input_capacity = Vec::new();
    for (kind, value) in [
        ("prompt", metadata.capacity.prompt_tpm),
        ("cached_prompt", metadata.capacity.cached_prompt_tpm),
    ] {
        if let Some(value) = value {
            input_capacity.push(json!({
                "type": kind,
                "unit": "token",
                "per": "minute",
                "value": value,
            }));
        }
    }
    if !input_capacity.is_empty() {
        input.insert(
            "capacity".into(),
            serde_json::Value::Array(input_capacity),
        );
    }

    let mut output = serde_json::Map::new();
    output.insert("type".into(), json!("text"));
    output.insert(
        "supported_parameters".into(),
        openrouter_supported_parameters(caps, metadata.max_output_length),
    );
    output.insert("streaming".into(), json!(true));
    if let Some(value) = metadata.max_output_length {
        output.insert(
            "max_length".into(),
            json!({ "value": value, "unit": "token" }),
        );
    }
    let mut output_pricing = Vec::new();
    for (kind, cost) in [
        ("completion", metadata.pricing.completion.as_deref()),
        (
            "internal_reasoning",
            metadata.pricing.internal_reasoning.as_deref(),
        ),
    ] {
        if let Some(cost) = cost {
            output_pricing.push(json!({
                "type": kind,
                "unit": "token",
                "cost_usd": cost,
            }));
        }
    }
    if !output_pricing.is_empty() {
        output.insert(
            "pricing".into(),
            serde_json::Value::Array(output_pricing),
        );
    }
    let mut output_capacity = Vec::new();
    if let Some(value) = metadata.capacity.completion_tpm {
        output_capacity.push(json!({
            "type": "completion",
            "unit": "token",
            "per": "minute",
            "value": value,
        }));
    }
    if let Some(value) = metadata.capacity.concurrency {
        output_capacity.push(json!({
            "type": "concurrency",
            "unit": "request",
            "value": value,
        }));
    }
    if !output_capacity.is_empty() {
        output.insert(
            "capacity".into(),
            serde_json::Value::Array(output_capacity),
        );
    }

    let mut entry = serde_json::Map::new();
    entry.insert("schema_version".into(), json!(OPENROUTER_SCHEMA_VERSION));
    entry.insert("id".into(), json!(name));
    entry.insert("name".into(), json!(name));
    if let Some(value) = metadata.hugging_face_id.as_deref() {
        entry.insert("hugging_face_id".into(), json!(value));
    }
    if let Some(value) = metadata.created {
        entry.insert("created".into(), json!(value));
    }
    if let Some(value) = metadata.quantization.as_deref() {
        entry.insert("quantization".into(), json!(value));
    }
    if let Some(value) = tokenizer {
        entry.insert("tokenizer".into(), json!(value));
    }
    if let Some(value) = metadata.description.as_deref() {
        entry.insert("description".into(), json!(value));
    }
    entry.insert(
        "input_modalities".into(),
        serde_json::Value::Array(vec![serde_json::Value::Object(input)]),
    );
    entry.insert(
        "output_modalities".into(),
        serde_json::Value::Array(vec![serde_json::Value::Object(output)]),
    );
    if let Some(cost) = metadata.pricing.request.as_deref() {
        entry.insert(
            "pricing".into(),
            json!([{ "type": "request", "unit": "request", "cost_usd": cost }]),
        );
    }
    if let Some(value) = metadata.capacity.request_rpm {
        entry.insert(
            "capacity".into(),
            json!([{
                "type": "request",
                "unit": "request",
                "per": "minute",
                "value": value,
            }]),
        );
    }
    if let Some(value) = metadata.is_ready {
        entry.insert("is_ready".into(), json!(value));
    }
    if let Some(value) = metadata.is_free {
        entry.insert("is_free".into(), json!(value));
    }
    if let Some(value) = metadata.discount_to_user {
        entry.insert("discount_to_user".into(), json!(value));
    }
    if let Some(value) = metadata.openrouter_slug.as_deref() {
        entry.insert("openrouter".into(), json!({ "slug": value }));
    }
    if !metadata.datacenters.is_empty() {
        entry.insert("datacenters".into(), json!(metadata.datacenters));
    }
    let mut compliance = serde_json::Map::new();
    if let Some(value) = metadata.zdr {
        compliance.insert("zdr".into(), json!(value));
    }
    if let Some(value) = metadata.hipaa {
        compliance.insert("hipaa".into(), json!(value));
    }
    if !compliance.is_empty() {
        entry.insert(
            "compliance".into(),
            serde_json::Value::Object(compliance),
        );
    }
    serde_json::Value::Object(entry)
}

fn models_openrouter_body(st: &AppState) -> serde_json::Value {
    let data: Vec<_> = st
        .models
        .iter()
        .map(|model| {
            model_entry_openrouter(
                model,
                st.caps.get(model),
                st.openrouter_metadata.get(model),
            )
        })
        .collect();
    json!({ "data": data })
}

async fn list_models(
    State(st): State<AppState>,
    Query(query): Query<ModelsQuery>,
) -> Response {
    match query.schema.as_deref() {
        None | Some("openai") => Json(models_openai_body(st.models.as_ref())).into_response(),
        Some("openrouter") => Json(models_openrouter_body(&st)).into_response(),
        Some(schema) => bad_request(
            &format!("unsupported models schema {schema:?}; expected openai or openrouter"),
            Some("schema"),
        ),
    }
}

/// One /v1/models entry in the existing OpenRouter catalog-style schema (serve-tail lane).
/// Values are worker truth from the loaded model plan (ModelCaps probed at spawn);
/// anything the plan doesn't know is an honest null, never an invented value.
/// Pricing is the self-hosted stub ("0" USD strings, the OR convention for an
/// unpriced endpoint) — a marketplace listing overrides it on the OR side.
fn model_entry_v1(name: &str, caps: Option<&ModelCaps>, created: u64) -> serde_json::Value {
    let ctx = caps.map(|c| c.context_length).filter(|&c| c > 0);
    let tokenizer = caps.map(|c| c.tokenizer.as_str()).filter(|t| !t.is_empty());
    let instruct = caps.and_then(|c| c.instruct_type.as_deref());
    json!({
        "id": name,
        "name": name,
        "object": "model",
        "created": created,
        "context_length": ctx,
        "architecture": {
            // text-only serving surface (no image/audio inputs on this server).
            "modality": "text->text",
            "tokenizer": tokenizer,
            "instruct_type": instruct,
        },
        "pricing": {
            "prompt": "0",
            "completion": "0",
            "request": "0",
            "image": "0",
        },
        "top_provider": {
            "context_length": ctx,
            // no static per-request completion cap: max_tokens is context-bounded
            // (gap-scan F2), so the honest schema value is null.
            "max_completion_tokens": serde_json::Value::Null,
        },
    })
}

/// GET /v1/models — the existing OpenAI/OpenRouter catalog listing, enriched with per-model
/// metadata from the loaded plan (context length, tokenizer, instruct family).
async fn list_models_v1(State(st): State<AppState>) -> impl IntoResponse {
    let data: Vec<_> = st.models.iter()
        .map(|m| model_entry_v1(m, st.caps.get(m), st.started))
        .collect();
    Json(json!({ "object": "list", "data": data }))
}

/// Per-lane counters + engine-truth interactive step latency (sidecar-compatible shape —
/// the x-lane QoS gate's receipts endpoint).
async fn yield_metrics(State(st): State<AppState>) -> impl IntoResponse {
    let m = st.metrics.lock().map(|m| m.clone()).unwrap_or_default();
    let lane = |i: usize| json!({
        "admitted": m.lane_admitted[i], "shed": m.lane_shed[i],
        "completed": m.lane_completed[i], "tokens_out": m.lane_tokens[i],
    });
    Json(json!({
        "lanes": {
            "interactive": lane(0), "judge": lane(1), "harvest": lane(2),
        },
        "interactive_step_ms": { "p50": m.step_p50_ms, "p99": m.step_p99_ms },
        "batch_size_last": m.batch_size_last,
    }))
}

/// Dark lanes (judge/harvest) can be SHED at admission — surface that as HTTP 429 +
/// Retry-After before committing to a streaming response. Interactive never sheds, so it
/// skips the peek (its first token may be legitimately far away; don't hold headers).
///
/// WHY THE PEEK MATTERS MORE THAN IT LOOKS (audit §OpenRouter uptime): once the first byte of
/// a 200 is written, the response is COMMITTED — a router cannot fail over, and a mid-stream
/// death counts against uptime. Catching an admission refusal here converts a would-be
/// mid-stream failure into a clean pre-header 429/503 that the client's own retry handles.
///
/// The 429 body now goes through `engine_error_body` (G6). It used to be
/// `{"error": "<string>"}` — a BARE STRING where every OpenAI SDK expects an object, which
/// made shed errors render as a blank message in every client that parses the standard shape.
async fn peek_shed(
    lane: lanes::Lane,
    mut rx: tokio::sync::mpsc::UnboundedReceiver<Event>,
) -> Result<tokio::sync::mpsc::UnboundedReceiver<Event>, Response> {
    if lane == lanes::Lane::Interactive {
        return Ok(rx);
    }
    match rx.recv().await {
        // Any pre-first-token failure — a shed, a rejected admission, a load fault — is
        // answered as a normal HTTP error with its own class instead of being smuggled into a
        // stream. Classification is the producer's (worker::EngineError), so this no longer
        // string-matches a "shed:" prefix that only ever existed as an in-band sentinel.
        Some(Event::Error(e)) => Err(engine_error_response(&e)),
        first => {
            let (tx2, rx2) = tokio::sync::mpsc::unbounded_channel();
            if let Some(ev) = first {
                let _ = tx2.send(ev);
            }
            tokio::spawn(async move {
                while let Some(ev) = rx.recv().await {
                    if tx2.send(ev).is_err() { break; }
                }
            });
            Ok(rx2)
        }
    }
}

/// Build the (GenParams, SamplerConfig, stop, prompt) from a request body.
fn build_request(req: &CompletionReq, tx: tokio::sync::mpsc::UnboundedSender<Event>,
                 lane: lanes::Lane, affinity: Option<String>) -> Request {
    let params = GenParams {
        max_new: req.max_tokens.unwrap_or(worker::MAX_NEW_CTX_BOUNDED),
        max_ctx: req.max_ctx,
        eos: Vec::new(), // worker adds the model's own eos id
    };
    let sampler_cfg = sampler_config(
        req.temperature, req.top_k, req.top_p, req.min_p,
        req.frequency_penalty, req.presence_penalty, req.repetition_penalty, req.seed);
    Request {
        model: req.model.clone(),
        prompt_ids: req.prompt_ids.clone(),
        prompt_text: req.prompt.clone(),
        chat: req.chat,
        chat_turns: Vec::new(),
        tools_json: Vec::new(),
        think: ThinkMode::Default,
        reasoning_effort: None, // /v1/completions is a raw-prompt surface (no template render)
        params,
        sampler_cfg,
        stop_strings: req.stop.clone().into_vec(),
        trace_id: req.trace_id.clone(),
        cache_ns: cache_namespace(&req.cache_salt),
        affinity,
        lane,
        grammar: None, // /v1/completions carries no response_format (chat surface only)
        oom_retries: 0, // step-OOM park budget: fresh from the HTTP layer (lane/admit-oom)
        tx,
    }
}

/// Everything the chat handler derives from the request body before submitting to the
/// worker: the worker Request plus the parser arming state for the response side.
struct ChatPlan {
    request: Request,
    /// Some(parser) when a <tools> block was rendered — the ONLY case the emission parser
    /// runs (non-tools traffic keeps byte-identical streams, chunk boundaries included).
    parser: Option<ToolStreamParser>,
}

fn build_chat_request(req: ChatCompletionReq, caps: Option<&ModelCaps>,
                      tx: tokio::sync::mpsc::UnboundedSender<Event>,
                      lane: lanes::Lane, affinity: Option<String>)
                      -> Result<ChatPlan, String> {
    let tool_choice = parse_tool_choice(&req.tool_choice)?;
    // Template honesty gate (serve-st lane, 2026-08-04): a directory checkpoint
    // (safetensors/repack) with NO chat template cannot honestly serve chat — 400 with a
    // clear message instead of silently rendering fallback ChatML the model never saw.
    // GGUF models keep the historical fallback (chat_ok=true there regardless).
    if let Some(c) = caps {
        if !c.chat_ok {
            return Err(format!(
                "model {:?} has no chat template (checkpoint carries neither \
                 tokenizer_config.json chat_template nor chat_template.jinja) — \
                 /v1/chat/completions unavailable; use /v1/completions with a raw prompt",
                req.model));
        }
    }
    let (mut think, effort_level) = parse_think(&req.reasoning_effort, &req.reasoning)?;
    // Effort-level templates (step35 dialect): the client's reasoning_effort is a RENDER
    // input ("Reasoning: {level}\n\n" in the system turn), not a think switch. Gate on the
    // capability so every other model's prompt stays byte-identical; the ThinkMode half is
    // already a documented no-op on switchless templates, so both controls stay consistent.
    let reasoning_effort = if caps.map(|c| c.effort_levels).unwrap_or(false) {
        effort_level
    } else {
        None
    };
    // response_format -> grammar spec (constrained decoding). None/text = unconstrained,
    // the exact legacy path; unknown/malformed forms are loud 400s.
    let grammar = constrained::parse_response_format(req.response_format.as_ref())?;
    // GRAMMAR x THINK (measured live 2026-08-03): the grammar masks from the FIRST
    // generated token, so an open <think> tail can never be closed — the forced JSON
    // lands in the think segment and `content` comes back empty. Constrained requests
    // force the template's no-think switch; a think-tail template WITHOUT the switch is
    // a loud 400 (honesty gate), not a silently broken stream.
    if grammar.is_some() {
        if let Some(c) = caps {
            if c.qwen_think && think != ThinkMode::NoThink {
                if c.think_switch {
                    think = ThinkMode::NoThink;
                } else {
                    return Err("response_format requires disabling the model's think tail, \
                                but this chat template has no enable_thinking switch".into());
                }
            }
        }
    }

    // tool_choice "none" = OpenAI "the model will not call tools": the prompt renders
    // WITHOUT the tools block (byte-identical to a no-tools request) and no parser runs.
    let (tools_json, schemas) = if !req.tools.is_empty() && tool_choice == ToolChoice::Auto {
        prepare_tools(&req.tools)?
    } else {
        (Vec::new(), HashMap::new())
    };

    let mut turns: Vec<TmplTurn> = Vec::with_capacity(req.messages.len());
    for msg in &req.messages {
        let content = content_to_text(&msg.content)
            .map_err(|e| format!("{} message: {e}", msg.role))?;
        let tool_calls = msg.tool_calls.iter().map(render_req_tool_call)
            .collect::<Result<Vec<_>, _>>()?;
        if !tool_calls.is_empty() && msg.role != "assistant" {
            return Err("tool_calls are only valid on assistant messages".into());
        }
        turns.push(TmplTurn { role: msg.role.clone(), content, tool_calls });
    }

    // Capability gate: reject tools on models whose template has no tools branch BEFORE
    // the request reaches the GPU worker (clean 400 instead of a mid-stream error).
    let has_tool_features = !tools_json.is_empty()
        || turns.iter().any(|t| t.role == "tool" || !t.tool_calls.is_empty());
    if has_tool_features && !caps.map(|c| c.tools_branch).unwrap_or(false) {
        return Err(format!("model {:?} chat template has no tools branch", req.model));
    }

    // Parser think gate: the rendered prompt ends with an OPEN think tail (template
    // default, not switched off by reasoning_effort on a switch-carrying template).
    let think_open = caps.map(|c| c.qwen_think
        && !(think == ThinkMode::NoThink && c.think_switch)).unwrap_or(false);
    // REASONING SEPARATION (gap-scan F13): think-segment text routes to the OpenRouter
    // `reasoning` response field on EVERY chat request against a think-open prompt —
    // content is post-think only. `include_reasoning:false` / `reasoning.exclude:true`
    // drops the separated text. Tools requests keep the full tool-call scanner; non-tools
    // think-open requests get the reasoning-only splitter (post-think text unscanned).
    // Models without a think tail keep a byte-identical no-parser stream.
    let include_reasoning = req.include_reasoning.unwrap_or(true)
        && req.reasoning.as_ref()
            .and_then(|r| r.get("exclude")).and_then(|v| v.as_bool()) != Some(true);
    let parser = if !tools_json.is_empty() {
        Some(ToolStreamParser::new(schemas, think_open)
            .with_include_reasoning(include_reasoning))
    } else if think_open {
        Some(ToolStreamParser::reasoning_only(include_reasoning))
    } else if caps.map(|c| c.gemma_think).unwrap_or(false) {
        // gemma4 thought-channel dialect (lane/gemma4-serve-gaps): thought text used to
        // land VERBATIM in content — `<|channel>thought\n…` with thinking on, and the tags
        // leaked with it (think-smoke receipt, step-sku lane). Armed on EVERY gemma4 chat
        // request, not just thinking-on: the closed-channel prompt still leaves the model
        // free to open a channel mid-stream (observed live), and the template's own
        // strip_thinking law applies wherever the tags appear. gemma4 templates carry no
        // tools branch, so this arm never competes with the tool scanner.
        Some(ToolStreamParser::gemma_thought(include_reasoning))
    } else {
        None
    };

    Ok(ChatPlan {
        request: Request {
            model: req.model,
            prompt_ids: Vec::new(),
            prompt_text: String::new(),
            chat: false,
            chat_turns: turns,
            tools_json,
            think,
            reasoning_effort,
            params: GenParams {
                max_new: req.max_tokens.unwrap_or(worker::MAX_NEW_CTX_BOUNDED),
                max_ctx: req.max_ctx,
                eos: Vec::new(),
            },
            sampler_cfg: sampler_config(
                req.temperature, req.top_k, req.top_p, req.min_p,
                req.frequency_penalty, req.presence_penalty, req.repetition_penalty,
                req.seed),
            stop_strings: req.stop.into_vec(),
            trace_id: None,
            cache_ns: cache_namespace(&req.cache_salt),
            affinity,
            lane,
            grammar,
            oom_retries: 0, // step-OOM park budget: fresh from the HTTP layer (lane/admit-oom)
            tx,
        },
        parser,
    })
}

/// Resolve the request's tenant identity (lane/api-keys, 2026-08-05). The law lives in
/// `auth::authenticate_with`; this wraps it with the process env:
///   MEMRA_API_KEYS keyring match -> that key's tenant/lane-class/rate-limit;
///   MEMRA_API_KEY single-key match -> tenant "default" (back-compat: the daily driver
///     and every serve script keep working unchanged, keyring configured or not);
///   neither configured -> open, tenant "default";
///   otherwise Err: Unknown -> 401 (OpenAI authentication_error), Disabled -> 403.
fn authenticate(headers: &axum::http::HeaderMap) -> Result<auth::TenantCtx, Response> {
    static SINGLE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    let single = SINGLE.get_or_init(|| std::env::var("MEMRA_API_KEY").ok());
    let bearer = headers.get("authorization")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "));
    auth::authenticate_with(auth::global(), single.as_deref(), bearer).map_err(|why| {
        match why {
            auth::AuthDenied::Unknown => error_response(
                StatusCode::UNAUTHORIZED, "invalid api key", "authentication_error", None),
            auth::AuthDenied::Disabled => error_response(
                StatusCode::FORBIDDEN, "api key is disabled", "authentication_error", None),
        }
    })
}

/// Lane resolution with the tenant's lane class applied: interactive-class keys keep the
/// legacy behavior exactly (default interactive, any x-lane honored); batch-class keys
/// DEFAULT to harvest and are refused the protected interactive lane (403, loud — the
/// QoS gate exists to protect interactive from bulk traffic, so a bulk key cannot claim
/// the protected class by omission or by header).
fn lane_for_tenant(headers: &axum::http::HeaderMap, tenant: &auth::TenantCtx)
    -> Result<lanes::Lane, Response> {
    let requested = match headers.get("x-lane").map(|v| v.to_str().unwrap_or("?")) {
        None => None,
        // A bad x-lane really is a client bug, so 400 is the right status — but the body has to
        // be an OpenAI-compat error OBJECT like every other refusal on this surface. It used to
        // be a bare `{"error":"unknown x-lane ..."}` string, which makes `e.body["error"]["type"]`
        // an index error in every SDK that parses the standard shape.
        Some(v) => Some(lanes::Lane::parse(v).ok_or_else(|| {
            error_response_coded(StatusCode::BAD_REQUEST,
                &format!("unknown x-lane {v:?}; expected one of interactive, judge, harvest"),
                "invalid_request_error", Some("x-lane"), Some("invalid_lane"))
        })?),
    };
    match tenant.lane_class {
        auth::LaneClass::Interactive => Ok(requested.unwrap_or(lanes::Lane::Interactive)),
        auth::LaneClass::Batch => match requested {
            None => Ok(lanes::Lane::Harvest),
            Some(lanes::Lane::Interactive) => Err(error_response(
                StatusCode::FORBIDDEN,
                "this api key is batch-class: x-lane interactive is not permitted \
                 (use judge or harvest)",
                "authentication_error", Some("x-lane"))),
            Some(l) => Ok(l),
        },
    }
}

/// The tenant-scoped PC-ISO namespace: keyring configured -> `t:<tenant>\x1f<salt>`
/// (a tenant's keys share cache, different tenants never — auth::scope_namespace);
/// no keyring -> the raw salt, byte-identical to pre-lane PC-ISO behavior.
fn tenant_namespace(tenant: &auth::TenantCtx, cache_salt: &Option<String>) -> String {
    let raw = cache_namespace(cache_salt);
    if auth::global().is_some() {
        auth::scope_namespace(&tenant.tenant, &raw)
    } else {
        raw
    }
}

/// METER SEAM (public-repo half): one flat log line per admitted request with the tenant
/// identity — the private fork's metering layer parses these for per-tenant usage/billing;
/// the public repo only emits. Completion accounting stays on the existing worker-truth
/// usage/abort lines; this line binds request-id -> tenant -> model/lane at admission.
fn meter_admit(env: &Envelope, tenant: &auth::TenantCtx, model: &str, lane: lanes::Lane) {
    eprintln!("[meter] admit id={} tenant={} lane={} model={:?}",
              env.id, tenant.tenant, lane.as_str(), model);
}

async fn completions(State(st): State<AppState>, headers: axum::http::HeaderMap,
                     Json(req): Json<CompletionReq>) -> Response {
    // API key: OpenAI-style `Authorization: Bearer <key>` -> tenant identity
    // (MEMRA_API_KEYS keyring and/or the MEMRA_API_KEY single key; nothing set = open).
    let env = Envelope::new(false);
    let tenant = match authenticate(&headers) {
        Ok(t) => t,
        Err(resp) => return with_request_id(&env.id, resp),
    };
    // HONESTY GATE (gap-scan F4): semantic params we can't honor 400 loudly.
    if let Err((msg, param)) = reject_unsupported(&[
        ("logit_bias", req.logit_bias.is_some(),
         " (device-side sampling has no bias hook yet)"),
        ("logprobs", req.logprobs.is_some(), ""),
        ("n", req.n.is_some_and(|n| n != 1), " for n != 1 (single choice only)"),
        ("best_of", req.best_of.is_some_and(|n| n != 1), " (single choice only)"),
    ]) {
        return with_request_id(&env.id, bad_request(&msg, Some(&param)));
    }
    let lane = match lane_for_tenant(&headers, &tenant) {
        Ok(l) => l,
        Err(resp) => return resp,
    };
    // DRAIN GATE (gap-scan F11): a draining server admits nothing new — immediate
    // 503 + Retry-After, before any slot/queue state is touched.
    if draining() {
        return with_request_id(&env.id, drain_response());
    }
    // RATE-LIMIT SNAPSHOT (gap-scan F12): take the in-flight slot at submission time;
    // the guard rides the response (stream included) and frees the slot at completion.
    let (guard, rl) = match acquire_request_slot(&st, lane, &tenant, &env) {
        Ok(slot) => slot,
        Err(resp) => return resp,
    };
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
    let model = req.model.clone();
    let stream = req.stream;
    let affinity = affinity_key(&req.session_id, &req.user, &headers);
    let mut request = build_request(&req, tx, lane, affinity);
    request.cache_ns = tenant_namespace(&tenant, &req.cache_salt);
    meter_admit(&env, &tenant, &model, lane);
    let stop_strings = request.stop_strings.clone();

    // Admission yield (lane/admission-latency): raise the pending-admit gauge BEFORE the
    // send — an in-flight spec burst polls it at every round boundary and ends early so
    // this request's admission wait stops scaling with MEMRA_SPEC_BURST. The worker
    // decrements at pop (handle_cmd).
    worker::PENDING_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Release);
    if st.cmd_tx.send(Cmd::Generate(Box::new(request))).is_err() {
        worker::PENDING_ADMITS.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
        return rl.attach(with_request_id(&env.id, worker_unavailable_response()));
    }
    let rx = match peek_shed(lane, rx).await {
        Ok(rx) => rx,
        Err(resp) => return rl.attach(with_request_id(&env.id, resp)),
    };

    let resp = if stream {
        sse_response(rx, model, false, None, env.clone(), stop_strings, Some(guard))
            .into_response()
    } else {
        let resp = blocking_response(rx, model, false, stop_strings, None, env.clone()).await
            .into_response();
        drop(guard); // response complete — free the slot before stamping headers
        resp
    };
    rl.attach(with_request_id(&env.id, resp))
}

async fn chat_completions(State(st): State<AppState>, headers: axum::http::HeaderMap,
                          Json(req): Json<ChatCompletionReq>) -> Response {
    let env = Envelope::new(true);
    let tenant = match authenticate(&headers) {
        Ok(t) => t,
        Err(resp) => return with_request_id(&env.id, resp),
    };
    if req.messages.is_empty() || req.messages.iter().any(|message| {
        !matches!(message.role.as_str(), "system" | "user" | "assistant" | "tool")
    }) {
        return with_request_id(&env.id, bad_request(
            "messages must use system/user/assistant/tool roles", Some("messages")));
    }
    // HONESTY GATE (gap-scan F4): semantic params we can't honor 400 loudly, never
    // silent downgrades. response_format json_object/json_schema are now REAL
    // (constrained decoding, lane/constrained) — parsed below; bad forms 400 with the
    // parser's own message.
    if let Err((msg, param)) = reject_unsupported(&[
        ("logit_bias", req.logit_bias.is_some(),
         " (device-side sampling has no bias hook yet)"),
        ("logprobs", req.logprobs.as_ref().is_some_and(|v| v.as_bool() != Some(false)), ""),
        ("top_logprobs", req.top_logprobs.is_some(), ""),
        ("n", req.n.is_some_and(|n| n != 1), " for n != 1 (single choice only)"),
    ]) {
        return with_request_id(&env.id, bad_request(&msg, Some(&param)));
    }
    let lane = match lane_for_tenant(&headers, &tenant) {
        Ok(l) => l,
        Err(resp) => return resp,
    };
    let model = req.model.clone();
    let stream = req.stream;
    let cache_salt = req.cache_salt.clone();
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
    let affinity = affinity_key(&req.session_id, &req.user, &headers);
    let mut plan = match build_chat_request(req, st.caps.get(&model), tx, lane, affinity) {
        Ok(plan) => plan,
        Err(err) => {
            return with_request_id(&env.id, bad_request(&err, None));
        }
    };
    plan.request.cache_ns = tenant_namespace(&tenant, &cache_salt);
    // DRAIN GATE (gap-scan F11): a draining server admits nothing new — immediate
    // 503 + Retry-After, before any slot/queue state is touched.
    if draining() {
        return with_request_id(&env.id, drain_response());
    }
    // RATE-LIMIT SNAPSHOT (gap-scan F12): slot taken at submission (post-validation —
    // a 400 never held a slot); freed when the response completes (guard).
    let (guard, rl) = match acquire_request_slot(&st, lane, &tenant, &env) {
        Ok(slot) => slot,
        Err(resp) => return resp,
    };
    meter_admit(&env, &tenant, &model, lane);
    let stop_strings = plan.request.stop_strings.clone();
    // Admission yield (lane/admission-latency): gauge up before send — see completions.
    worker::PENDING_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Release);
    if st.cmd_tx.send(Cmd::Generate(Box::new(plan.request))).is_err() {
        worker::PENDING_ADMITS.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
        return rl.attach(with_request_id(&env.id, worker_unavailable_response()));
    }
    let rx = match peek_shed(lane, rx).await {
        Ok(rx) => rx,
        Err(resp) => return rl.attach(with_request_id(&env.id, resp)),
    };
    let resp = if stream {
        sse_response(rx, model, true, plan.parser, env.clone(), stop_strings, Some(guard))
            .into_response()
    } else {
        let resp = blocking_response(rx, model, true, stop_strings, plan.parser, env.clone())
            .await.into_response();
        drop(guard); // response complete — free the slot before stamping headers
        resp
    };
    rl.attach(with_request_id(&env.id, resp))
}

/// Streaming (SSE): forward each Token as an SSE `data:` line; emit a final `done` event.
/// `parser`: Some only for tools-armed chat requests — content routes through the tool-call
/// parser and parsed calls stream as OpenAI `tool_calls` deltas (one header chunk carrying
/// id/type/name, one arguments chunk), with `finish_reason:"tool_calls"` on the final chunk.
/// ENVELOPE (gap-scan F1): every OpenAI-shape chunk is stamped with the request's
/// id/created/system_fingerprint; the FIRST chat delta carries `role:"assistant"` (SDK
/// stream-accumulator contract); mid-stream worker errors go out as a `data:` error chunk
/// (OpenAI clients never parse named SSE events) followed by [DONE].
fn sse_response(mut rx: tokio::sync::mpsc::UnboundedReceiver<Event>, model: String, chat: bool,
                mut parser: Option<ToolStreamParser>, env: Envelope,
                stop_strings: Vec<String>, guard: Option<InflightGuard>)
    -> Sse<impl futures_core::Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
    // STOP-LEAK holdback (gap-scan F9), OpenAI shapes only: content deltas buffer until
    // they can't start a stop string; matched stop text is excluded exactly like the
    // non-stream shape. The memra-native stream stays byte-identical (no scrubber).
    let mut scrub = (!stop_strings.is_empty() && (chat || openai_compat()))
        .then(|| StopScrubber::new(stop_strings));
    let stream = async_stream::stream! {
        // in-flight slot rides the stream: freed when the stream completes or the
        // client disconnects (drop) — the rate-limit gauge + drain barrier source.
        let _guard = guard;
        let mut call_index: usize = 0;
        // first chat delta carries the role (applied to whatever delta comes first —
        // content, reasoning, or the tool-call header).
        let mut role_sent = false;
        macro_rules! chat_chunk {
            ($delta:expr, $finish:expr) => {{
                let mut delta = $delta;
                if chat && !role_sent {
                    role_sent = true;
                    delta["role"] = json!("assistant");
                }
                env.stamp(json!({ "object": "chat.completion.chunk", "model": model,
                                  "choices": [{ "index": 0, "delta": delta,
                                                "finish_reason": $finish }] }))
                    .to_string()
            }};
        }
        // renders Piece -> chat.completion.chunk payloads (tools-armed path only).
        macro_rules! piece_chunks {
            ($piece:expr) => {{
                let mut payloads: Vec<String> = Vec::new();
                match $piece {
                    Piece::Content(text) => {
                        let text = match scrub.as_mut() {
                            Some(sc) => sc.push(&text),
                            None => text,
                        };
                        if !text.is_empty() {
                            payloads.push(chat_chunk!(json!({ "content": text }),
                                                      serde_json::Value::Null));
                        }
                    }
                    // OR reasoning dialect (gap-scan F13): think text streams as
                    // delta.reasoning, never as content (stop strings scrub content only,
                    // same as the non-stream truncate law).
                    Piece::Reasoning(text) => payloads.push(
                        chat_chunk!(json!({ "reasoning": text }), serde_json::Value::Null)),
                    Piece::Call(call) => {
                        payloads.push(chat_chunk!(json!({ "tool_calls": [{
                            "index": call_index, "id": call.id, "type": "function",
                            "function": { "name": call.name, "arguments": "" } }] }),
                            serde_json::Value::Null));
                        payloads.push(chat_chunk!(json!({ "tool_calls": [{
                            "index": call_index,
                            "function": { "arguments": call.arguments } }] }),
                            serde_json::Value::Null));
                        call_index += 1;
                    }
                }
                payloads
            }};
        }
        while let Some(ev) = rx.recv().await {
            match ev {
                Event::Token { id, text } => {
                    if let Some(p) = parser.as_mut() {
                        for piece in p.push(&text) {
                            for payload in piece_chunks!(piece) {
                                yield Ok(SseEvent::default().data(payload));
                            }
                        }
                        continue;
                    }
                    let text = match scrub.as_mut() {
                        Some(sc) => sc.push(&text),
                        None => text,
                    };
                    if text.is_empty() && scrub.is_some() {
                        continue; // held back (possible stop prefix) or post-stop
                    }
                    let payload = if chat {
                        chat_chunk!(json!({ "content": text }), serde_json::Value::Null)
                    } else if openai_compat() {
                        env.stamp(json!({ "object": "text_completion", "model": model,
                                "choices": [{ "index": 0, "text": text, "finish_reason": null }] }))
                            .to_string()
                    } else {
                        json!({ "model": model, "id": id, "text": text }).to_string()
                    };
                    yield Ok(SseEvent::default().data(payload));
                }
                Event::Done { stop_reason, n_tokens, n_prompt, n_cached, elapsed_s, spec } => {
                    let mut finish = stop_reason_to_finish(&stop_reason);
                    if let Some(p) = parser.as_mut() {
                        for piece in p.finish() {
                            for payload in piece_chunks!(piece) {
                                yield Ok(SseEvent::default().data(payload));
                            }
                        }
                        if p.n_calls() > 0 { finish = "tool_calls"; }
                    }
                    // stop-scrubber flush: held-back text that never became a stop.
                    if let Some(sc) = scrub.as_mut() {
                        let tail = sc.finish();
                        if !tail.is_empty() {
                            let payload = if chat {
                                chat_chunk!(json!({ "content": tail }),
                                            serde_json::Value::Null)
                            } else {
                                env.stamp(json!({ "object": "text_completion",
                                    "model": model,
                                    "choices": [{ "index": 0, "text": tail,
                                                  "finish_reason": null }] })).to_string()
                            };
                            yield Ok(SseEvent::default().data(payload));
                        }
                    }
                    if chat || openai_compat() {
                        let usage = usage_json(n_prompt, n_tokens, n_cached, elapsed_s, spec);
                        let fin = if chat {
                            let mut v = env.stamp(json!({
                                "object": "chat.completion.chunk", "model": model,
                                "choices": [{ "index": 0, "delta": {},
                                              "finish_reason": finish }],
                                "usage": usage }));
                            // zero-token stream: the role must still arrive (SDK contract).
                            if !role_sent {
                                v["choices"][0]["delta"]["role"] = json!("assistant");
                            }
                            v
                        } else {
                            env.stamp(json!({ "object": "text_completion", "model": model,
                                "choices": [{ "index": 0, "text": "",
                                              "finish_reason": finish }],
                                "usage": usage }))
                        }.to_string();
                        yield Ok(SseEvent::default().data(fin));
                        yield Ok(SseEvent::default().data("[DONE]".to_string()));
                    } else {
                        let payload = json!({
                            "stop_reason": stop_reason, "n_tokens": n_tokens,
                            "prompt_tokens": n_prompt, "cached_tokens": n_cached,
                            "elapsed_s": elapsed_s
                        }).to_string();
                        yield Ok(SseEvent::default().event("done").data(payload));
                    }
                    break;
                }
                Event::Error(err) => {
                    // MID-STREAM FAILURE (G6). The response status is already 200 and the
                    // headers are gone, so there is no status code left to change: the ONLY
                    // honest signal is an error object in the stream followed by closing the
                    // connection. Both happen here — the `break` ends the generator, which
                    // drops the SSE body and closes.
                    //
                    // The class-derived type/code now travels with it (previously hardcoded
                    // "server_error" for every cause, so a client could not tell an
                    // out-of-VRAM from a context-length mistake once streaming had begun).
                    if chat || openai_compat() {
                        // OpenAI clients only parse `data:` lines — a named `event: error`
                        // reads as a silent hang. Error object as the final data chunk.
                        let payload = engine_error_body(&err).to_string();
                        yield Ok(SseEvent::default().data(payload));
                        yield Ok(SseEvent::default().data("[DONE]".to_string()));
                    } else {
                        // Native (non-OpenAI) surface keeps its named `error` event: its
                        // clients are memra's own tools, which do parse named events.
                        let payload = engine_error_body(&err).to_string();
                        yield Ok(SseEvent::default().event("error").data(payload));
                    }
                    break;
                }
            }
        }
    };
    Sse::new(stream).keep_alive(
        // OR cancels + fails over on silent phases (fetch timeout) — long-prompt prefill
        // streams nothing for many seconds before first token. SSE comment every 5s.
        axum::response::sse::KeepAlive::new()
            .interval(std::time::Duration::from_secs(5)),
    )
}

/// Blocking JSON: collect all tokens, return one {text, tokens, stop_reason} when done.
fn truncate_at_stop(text: &mut String, stop_strings: &[String]) {
    if let Some(offset) = stop_strings.iter().filter_map(|stop| text.find(stop)).min() {
        text.truncate(offset);
    }
}

/// Longest PROPER prefix of `tag` (on tag char boundaries) that `s` ends with — the
/// char-boundary-safe twin of toolcall's ASCII-tag helper (stop strings are client text).
fn partial_stop_suffix(s: &str, tag: &str) -> usize {
    let mut best = 0;
    for (k, _) in tag.char_indices().skip(1) {
        if k <= s.len() && s.ends_with(&tag[..k]) {
            best = k;
        }
    }
    best
}

/// STREAMING STOP SCRUBBER (gap-scan F9): the worker emits the token delta BEFORE its
/// stop check, so streams used to leak the stop text (and same-token overshoot) that
/// non-stream clients never see. Content deltas route through this holdback buffer:
/// text is released only once it can no longer be the start of a stop string, and a
/// completed stop truncates exactly like the non-stream `truncate_at_stop`.
struct StopScrubber {
    stops: Vec<String>,
    buf: String,
    done: bool,
}

impl StopScrubber {
    fn new(stops: Vec<String>) -> Self {
        Self { stops, buf: String::new(), done: false }
    }

    /// Feed a content delta; returns the text now safe to emit.
    fn push(&mut self, text: &str) -> String {
        if self.done {
            return String::new();
        }
        self.buf.push_str(text);
        if let Some(i) = self.stops.iter().filter_map(|s| self.buf.find(s.as_str())).min() {
            self.done = true;
            let out = self.buf[..i].to_string();
            self.buf.clear();
            return out;
        }
        let keep = self.stops.iter()
            .map(|s| partial_stop_suffix(&self.buf, s)).max().unwrap_or(0);
        let emit_to = self.buf.len() - keep;
        let out = self.buf[..emit_to].to_string();
        self.buf.drain(..emit_to);
        out
    }

    /// End of stream: release held-back text (it never became a stop).
    fn finish(&mut self) -> String {
        if self.done {
            self.buf.clear();
            return String::new();
        }
        std::mem::take(&mut self.buf)
    }
}

async fn blocking_response(mut rx: tokio::sync::mpsc::UnboundedReceiver<Event>, model: String,
                           chat: bool, stop_strings: Vec<String>,
                           mut parser: Option<ToolStreamParser>, env: Envelope) -> Response {
    let mut text = String::new();
    let mut reasoning = String::new();
    let mut tokens: Vec<u32> = Vec::new();
    let mut calls: Vec<ParsedToolCall> = Vec::new();
    let consume = |pieces: Vec<Piece>, text: &mut String, reasoning: &mut String,
                   calls: &mut Vec<ParsedToolCall>| {
        for piece in pieces {
            match piece {
                Piece::Content(t) => text.push_str(&t),
                Piece::Reasoning(t) => reasoning.push_str(&t),
                Piece::Call(c) => calls.push(c),
            }
        }
    };
    while let Some(ev) = rx.recv().await {
        match ev {
            Event::Token { id, text: delta } => {
                tokens.push(id);
                match parser.as_mut() {
                    Some(p) => consume(p.push(&delta), &mut text, &mut reasoning, &mut calls),
                    None => text.push_str(&delta),
                }
            }
            Event::Done { stop_reason, n_tokens, n_prompt, n_cached, elapsed_s, spec } => {
                if let Some(p) = parser.as_mut() {
                    consume(p.finish(), &mut text, &mut reasoning, &mut calls);
                }
                truncate_at_stop(&mut text, &stop_strings);
                let finish = if calls.is_empty() { stop_reason_to_finish(&stop_reason) }
                             else { "tool_calls" };
                if chat {
                    // OpenAI shape: content is null on a pure tool-call turn.
                    let content = if !calls.is_empty() && text.is_empty() {
                        serde_json::Value::Null
                    } else {
                        serde_json::Value::String(text)
                    };
                    let mut message = json!({ "role": "assistant", "content": content });
                    // OR reasoning dialect (gap-scan F13): think text is a dedicated
                    // message field (+ reasoning_details), content is post-think only.
                    if !reasoning.is_empty() {
                        message["reasoning"] = json!(reasoning);
                        message["reasoning_details"] = json!([{
                            "type": "reasoning.text", "text": reasoning }]);
                    }
                    if !calls.is_empty() {
                        message["tool_calls"] = serde_json::Value::Array(
                            calls.iter().map(tool_call_json).collect());
                    }
                    return Json(env.stamp(json!({
                        "object": "chat.completion", "model": model,
                        "choices": [{ "index": 0,
                                      "message": message,
                                      "finish_reason": finish }],
                        "usage": usage_json(n_prompt, n_tokens, n_cached, elapsed_s, spec)
                    }))).into_response();
                }
                if openai_compat() {
                    return Json(env.stamp(json!({
                        "object": "text_completion", "model": model,
                        "choices": [{ "index": 0, "text": text,
                                      "finish_reason": finish }],
                        "usage": usage_json(n_prompt, n_tokens, n_cached, elapsed_s, spec)
                    }))).into_response();
                }
                return Json(CompletionResp {
                    model, text, tokens, stop_reason, n_tokens,
                    prompt_tokens: n_prompt, cached_tokens: n_cached, elapsed_s,
                }).into_response();
            }
            Event::Error(err) => {
                // G6: the class decides the status. This single line used to be
                // `bad_request(&msg, None)` — every CUDA fault, VRAM exhaustion and admission
                // shed reported as 400 invalid_request_error, which no SDK retries.
                return engine_error_response(&err);
            }
        }
    }
    // The worker's Event channel closed without a Done or an Error: the worker thread is gone
    // (panicked and unrecoverable, or shutting down). 503 + Retry-After, not 500: this is a
    // process-level condition the supervisor is already acting on, and a client's retry may
    // well land on a restarted process.
    let e = worker::EngineError::overloaded(
        "worker closed the stream without completing (worker restart in progress)");
    engine_error_response(&e)
}

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

    fn tool_caps() -> ModelCaps {
        ModelCaps {
            tools_branch: true, qwen_think: true, think_switch: true, chat_ok: true,
            ..Default::default()
        }
    }

    #[test]
    fn chat_request_preserves_turns_and_openai_stop_forms() {
        let payload = serde_json::json!({
            "model": "plain_quant",
            "messages": [
                {"role": "system", "content": "rules"},
                {"role": "user", "content": "task"},
                {"role": "assistant", "content": "work"}
            ],
            "max_tokens": 64,
            "temperature": 0.0,
            "stop": "<stop>"
        });
        let req: ChatCompletionReq = serde_json::from_value(payload).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let plan = build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap();
        let request = plan.request;
        assert!(plan.parser.is_none(), "no tools -> no parser (isolation contract)");
        assert!(request.tools_json.is_empty());
        assert_eq!(request.think, ThinkMode::Default);
        assert_eq!(request.model, "plain_quant");
        assert_eq!(request.params.max_new, 64);
        // OMITTED max_tokens (gap-scan F2): the context-bounded sentinel, not 128.
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "plain_quant", "messages": [{"role": "user", "content": "task"}]
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let plan = build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap();
        assert_eq!(plan.request.params.max_new, worker::MAX_NEW_CTX_BOUNDED);
        // max_completion_tokens alias still honored exactly.
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "plain_quant", "messages": [{"role": "user", "content": "task"}],
            "max_completion_tokens": 7
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap().request.params.max_new, 7);
        // completions body: same omission law.
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "plain_quant", "prompt": "task"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_request(&req, tx, lanes::Lane::Interactive, None).params.max_new, worker::MAX_NEW_CTX_BOUNDED);
        let turns: Vec<(String, String)> = request.chat_turns.iter()
            .map(|t| (t.role.clone(), t.content.clone())).collect();
        assert_eq!(turns, vec![
            ("system".into(), "rules".into()),
            ("user".into(), "task".into()),
            ("assistant".into(), "work".into()),
        ]);
        assert!(request.chat_turns.iter().all(|t| t.tool_calls.is_empty()));
        assert_eq!(request.stop_strings, vec!["<stop>"]);

        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "plain_quant", "messages": [{"role": "user", "content": "task"}],
            "stop": ["a", "b"]
        })).unwrap();
        assert_eq!(req.stop.into_vec(), vec!["a", "b"]);

        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "plain_quant", "messages": [{"role": "user", "content": "task"}],
            "stop": null
        })).unwrap();
        assert!(req.stop.into_vec().is_empty());
    }

    #[tokio::test]
    async fn chat_response_has_openai_message_shape() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "hello".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Eos".into(), n_tokens: 1, n_prompt: 42, n_cached: 30, elapsed_s: 0.5,
            spec: None,
        }).unwrap();
        drop(tx);
        let response = blocking_response(rx, "plain_quant".into(), true, Vec::new(), None,
                                         Envelope::new(true)).await;
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["object"], "chat.completion");
        // OpenAI envelope (gap-scan F1): the official SDK pydantic-REQUIRES id + created.
        assert!(payload["id"].as_str().unwrap().starts_with("chatcmpl-"));
        assert!(payload["created"].as_u64().unwrap() > 1_700_000_000);
        assert!(payload["system_fingerprint"].as_str().unwrap().starts_with("memra-"));
        assert_eq!(payload["choices"][0]["message"]["role"], "assistant");
        assert_eq!(payload["choices"][0]["message"]["content"], "hello");
        assert_eq!(payload["choices"][0]["finish_reason"], "stop");
        // OpenAI prompt-caching usage schema (worker-truth cached vs computed split).
        assert_eq!(payload["usage"]["prompt_tokens"], 42);
        assert_eq!(payload["usage"]["completion_tokens"], 1);
        assert_eq!(payload["usage"]["total_tokens"], 43);
        assert_eq!(payload["usage"]["prompt_tokens_details"]["cached_tokens"], 30);
        // ADDITIVE contract (lane/accept-telemetry): a non-spec request carries NO usage.spec
        // — the pre-lane usage object byte-for-byte.
        assert!(payload["usage"].get("spec").is_none());
    }

    /// usage.spec (lane/accept-telemetry): spec-decode requests carry this request's own
    /// acceptance summary as an additive usage extension; every existing field is untouched.
    #[tokio::test]
    async fn chat_usage_carries_spec_acceptance_summary() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "hello".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Eos".into(), n_tokens: 1, n_prompt: 42, n_cached: 0, elapsed_s: 0.5,
            spec: Some(worker::SpecUsage { rounds: 10, drafted: 30, accepted: 21 }),
        }).unwrap();
        drop(tx);
        let response = blocking_response(rx, "plain_quant".into(), true, Vec::new(), None,
                                         Envelope::new(true)).await;
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        let sp = &payload["usage"]["spec"];
        assert_eq!(sp["rounds"], 10);
        assert_eq!(sp["drafted"], 30);
        assert_eq!(sp["accepted"], 21);
        assert!((sp["acceptance_rate"].as_f64().unwrap() - 0.7).abs() < 1e-9);
        // existing fields untouched next to the extension.
        assert_eq!(payload["usage"]["total_tokens"], 43);
    }

    fn weather_request(extra: serde_json::Value) -> ChatCompletionReq {
        let mut payload = serde_json::json!({
            "model": "m",
            "messages": [{"role": "user", "content": "Weather in Paris?"}],
            "tools": [{"type": "function", "function": {
                "name": "get_weather",
                "description": "Get current weather",
                "parameters": {"type": "object",
                               "properties": {"city": {"type": "string"},
                                              "days": {"type": "integer"}},
                               "required": ["city"]}}}],
        });
        if let Some(obj) = extra.as_object() {
            for (k, v) in obj { payload[k] = v.clone(); }
        }
        serde_json::from_value(payload).unwrap()
    }

    #[test]
    fn tools_request_renders_client_key_order_and_arms_parser() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let plan = build_chat_request(weather_request(json!({})), Some(&tool_caps()), tx, lanes::Lane::Interactive, None).unwrap();
        assert!(plan.parser.is_some());
        assert_eq!(plan.request.tools_json.len(), 1);
        // client key order preserved + python-dumps separators (the template's tojson law).
        assert_eq!(plan.request.tools_json[0],
            "{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \
             \"description\": \"Get current weather\", \"parameters\": {\"type\": \"object\", \
             \"properties\": {\"city\": {\"type\": \"string\"}, \"days\": {\"type\": \
             \"integer\"}}, \"required\": [\"city\"]}}}");
    }

    #[test]
    fn tool_choice_none_strips_tools_and_parser() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let plan = build_chat_request(weather_request(json!({"tool_choice": "none"})),
                                      Some(&tool_caps()), tx, lanes::Lane::Interactive, None).unwrap();
        // tools stripped: no tool-call scanning; the think-open prompt still arms the
        // reasoning-only splitter (F13) — a <tool_call> in post-think prose stays prose.
        let mut p = plan.parser.expect("think-open chat arms the reasoning splitter");
        let pieces = p.push("x</think>\n\n<tool_call> stays prose");
        assert_eq!(pieces, vec![
            Piece::Reasoning("x".into()),
            Piece::Content("<tool_call> stays prose".into()),
        ]);
        assert!(plan.request.tools_json.is_empty());
        // unsupported tool_choice forms are clean 400s, not silent downgrades.
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(build_chat_request(weather_request(json!({"tool_choice": "required"})),
                                   Some(&tool_caps()), tx, lanes::Lane::Interactive, None).is_err());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(build_chat_request(weather_request(json!({"tool_choice":
            {"type": "function", "function": {"name": "get_weather"}}})),
                                   Some(&tool_caps()), tx, lanes::Lane::Interactive, None).is_err());
    }

    #[test]
    fn model_plan_accepts_st_dir_and_rejects_bogus_dir() {
        let root = std::env::temp_dir().join(format!("memra_plan_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);

        // (a) single-file ST checkpoint dir: config.json + model.safetensors.
        let st = root.join("st_single");
        std::fs::create_dir_all(&st).unwrap();
        std::fs::write(st.join("config.json"), "{}").unwrap();
        std::fs::write(st.join("model.safetensors"), b"x").unwrap();
        assert!(validate_model_path(st.to_str().unwrap()).is_ok());

        // (b) sharded ST checkpoint dir: config.json + model.safetensors.index.json.
        let sh = root.join("st_sharded");
        std::fs::create_dir_all(&sh).unwrap();
        std::fs::write(sh.join("config.json"), "{}").unwrap();
        std::fs::write(sh.join("model.safetensors.index.json"), "{}").unwrap();
        assert!(validate_model_path(sh.to_str().unwrap()).is_ok());

        // (c) repack dir: manifest.json alone qualifies.
        let rp = root.join("repack");
        std::fs::create_dir_all(&rp).unwrap();
        std::fs::write(rp.join("manifest.json"), "{}").unwrap();
        assert!(validate_model_path(rp.to_str().unwrap()).is_ok());

        // (d) bogus dir (no weights): clear error naming what was expected.
        let bogus = root.join("bogus");
        std::fs::create_dir_all(&bogus).unwrap();
        let err = validate_model_path(bogus.to_str().unwrap()).unwrap_err();
        assert!(err.contains("model.safetensors"), "error should say what is missing: {err}");
        assert!(err.contains("manifest.json"), "error should mention the repack form: {err}");

        // (e) ST weights but no config.json: distinct clear error.
        let nc = root.join("no_config");
        std::fs::create_dir_all(&nc).unwrap();
        std::fs::write(nc.join("model.safetensors"), b"x").unwrap();
        let err = validate_model_path(nc.to_str().unwrap()).unwrap_err();
        assert!(err.contains("config.json"), "error should name config.json: {err}");

        // (f) nonexistent path.
        let err = validate_model_path(root.join("nowhere").to_str().unwrap()).unwrap_err();
        assert!(err.contains("does not exist"), "{err}");

        // (g) plain file = GGUF branch, accepted as-is.
        let f = root.join("model.gguf");
        std::fs::write(&f, b"g").unwrap();
        assert!(validate_model_path(f.to_str().unwrap()).is_ok());

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn chat_on_templateless_dir_checkpoint_is_rejected_with_clear_message() {
        // serve-st v1 honesty gate: a dir checkpoint whose tokenizer carries no chat
        // template probes chat_ok=false -> every chat request 400s BEFORE the worker.
        let caps = ModelCaps {
            tools_branch: false, qwen_think: false, think_switch: false, chat_ok: false,
            ..Default::default() };
        let payload = serde_json::json!({
            "model": "st_model",
            "messages": [{"role": "user", "content": "hello"}],
        });
        let req: ChatCompletionReq = serde_json::from_value(payload).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let err = match build_chat_request(req, Some(&caps), tx, lanes::Lane::Interactive, None) {
            Err(e) => e,
            Ok(_) => panic!("templateless dir checkpoint must reject chat"),
        };
        assert!(err.contains("no chat template"), "message should name the cause: {err}");
        assert!(err.contains("/v1/completions"), "message should point at the raw-prompt escape hatch: {err}");
    }

    #[test]
    fn tools_on_model_without_tools_branch_is_rejected() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let caps = ModelCaps { chat_ok: true, ..Default::default() };
        assert!(build_chat_request(weather_request(json!({})), Some(&caps), tx, lanes::Lane::Interactive, None).is_err());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(build_chat_request(weather_request(json!({})), None, tx, lanes::Lane::Interactive, None).is_err());
    }

    #[test]
    fn reasoning_effort_maps_to_think_switch() {
        // The reasoning-capable-model convention (owner directive 2026-08-07):
        // low|medium|high = thinking ON at that budget; none|minimal = thinking OFF;
        // absent = the model's own default. `low` used to map to NoThink — that read the
        // OpenAI field as a "how much" dial with off at the bottom, which contradicts how
        // reasoning models ship (low IS a reasoning mode).
        for (extra, want) in [
            (json!({}), ThinkMode::Default),
            (json!({"reasoning_effort": "low"}), ThinkMode::Think),
            (json!({"reasoning_effort": "none"}), ThinkMode::NoThink),
            (json!({"reasoning_effort": "minimal"}), ThinkMode::NoThink),
            (json!({"reasoning_effort": "high"}), ThinkMode::Think),
            (json!({"reasoning_effort": "medium"}), ThinkMode::Think),
            (json!({"reasoning": {"enabled": false}}), ThinkMode::NoThink),
            (json!({"reasoning": {"effort": "low"}}), ThinkMode::Think),
            (json!({"reasoning": {"enabled": true}}), ThinkMode::Think),
        ] {
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            let plan = build_chat_request(weather_request(extra.clone()),
                                          Some(&tool_caps()), tx, lanes::Lane::Interactive, None).unwrap();
            assert_eq!(plan.request.think, want, "extra={extra}");
        }
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(build_chat_request(weather_request(json!({"reasoning_effort": "extreme"})),
                                   Some(&tool_caps()), tx, lanes::Lane::Interactive, None).is_err());
    }

    #[test]
    fn reasoning_effort_maps_to_effort_level_on_step35_class_templates() {
        // ModelCaps::effort_levels=true (the step35 dialect): the SAME client field becomes
        // a render input (Request::reasoning_effort) — low/medium/high pass through,
        // none/minimal clamp to "low" (the template has no thinking-off level), absent stays
        // None (the template's own default: no `Reasoning:` line).
        let effort_caps = ModelCaps { effort_levels: true, ..tool_caps() };
        for (extra, want) in [
            (json!({}), None),
            (json!({"reasoning_effort": "low"}), Some("low")),
            (json!({"reasoning_effort": "medium"}), Some("medium")),
            (json!({"reasoning_effort": "high"}), Some("high")),
            (json!({"reasoning_effort": "none"}), Some("low")),
            (json!({"reasoning_effort": "minimal"}), Some("low")),
            (json!({"reasoning": {"effort": "high"}}), Some("high")),
            (json!({"reasoning": {"enabled": false}}), Some("low")),
        ] {
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            let plan = build_chat_request(weather_request(extra.clone()),
                                          Some(&effort_caps), tx, lanes::Lane::Interactive, None).unwrap();
            assert_eq!(plan.request.reasoning_effort.as_deref(), want, "extra={extra}");
        }
        // effort_levels=false (every other template): the field NEVER reaches the render —
        // byte-identity for non-step35 prompts is a caps gate, not a template accident.
        for extra in [json!({}), json!({"reasoning_effort": "high"}),
                      json!({"reasoning": {"effort": "low"}})] {
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            let plan = build_chat_request(weather_request(extra.clone()),
                                          Some(&tool_caps()), tx, lanes::Lane::Interactive, None).unwrap();
            assert_eq!(plan.request.reasoning_effort, None, "extra={extra}");
        }
    }

    #[test]
    fn assistant_history_tool_calls_and_tool_role_render_into_turns() {
        let payload = serde_json::json!({
            "model": "m",
            "messages": [
                {"role": "user", "content": "Weather in Paris?"},
                {"role": "assistant", "content": null, "tool_calls": [
                    {"id": "call_x", "type": "function", "function": {
                        "name": "get_weather",
                        "arguments": "{\"city\": \"Paris\", \"days\": 3}"}}]},
                {"role": "tool", "tool_call_id": "call_x", "content": "{\"temp_c\": 21}"}
            ],
        });
        let req: ChatCompletionReq = serde_json::from_value(payload).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let plan = build_chat_request(req, Some(&tool_caps()), tx, lanes::Lane::Interactive, None).unwrap();
        let turns = &plan.request.chat_turns;
        assert_eq!(turns[1].tool_calls, vec![TmplToolCall {
            name: "get_weather".into(),
            params: vec![("city".into(), "Paris".into()), ("days".into(), "3".into())],
        }]);
        assert_eq!(turns[2].role, "tool");
        assert_eq!(turns[2].content, "{\"temp_c\": 21}");
        // no tools field on this follow-up turn: no tool-call scanning — but the think-open
        // prompt still arms the reasoning-only splitter (gap-scan F13).
        let mut p = plan.parser.expect("think-open chat arms the reasoning splitter");
        let pieces = p.push("thought</think>\n\nanswer <tool_call> is prose here");
        assert_eq!(pieces, vec![
            Piece::Reasoning("thought".into()),
            Piece::Content("answer <tool_call> is prose here".into()),
        ]);
    }

    #[tokio::test]
    async fn blocking_tools_response_carries_tool_calls_and_finish_reason() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "plan</think>\n\n".into() }).unwrap();
        tx.send(Event::Token { id: 2, text: "<tool_call>\n<function=get_weather>\n\
<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Eos".into(), n_tokens: 2, n_prompt: 40, n_cached: 0, elapsed_s: 0.5,
            spec: None,
        }).unwrap();
        drop(tx);
        let parser = ToolStreamParser::new(HashMap::new(), true);
        let response = blocking_response(rx, "m".into(), true, Vec::new(), Some(parser),
                                         Envelope::new(true)).await;
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["choices"][0]["finish_reason"], "tool_calls");
        // reasoning separation (gap-scan F13): think text -> message.reasoning (+details),
        // content is post-think only (null here — a pure tool-call turn).
        assert_eq!(payload["choices"][0]["message"]["content"], serde_json::Value::Null);
        assert_eq!(payload["choices"][0]["message"]["reasoning"], "plan");
        assert_eq!(payload["choices"][0]["message"]["reasoning_details"][0]["text"], "plan");
        let call = &payload["choices"][0]["message"]["tool_calls"][0];
        assert_eq!(call["type"], "function");
        assert_eq!(call["function"]["name"], "get_weather");
        assert_eq!(call["function"]["arguments"], "{\"city\":\"Paris\"}");
        // THE INTERSECTION (integrate-cache): a tools response's usage carries the same
        // worker-truth prompt/cached split as any other shape — one source of truth.
        assert_eq!(payload["usage"]["prompt_tokens"], 40);
        assert_eq!(payload["usage"]["completion_tokens"], 2);
        assert_eq!(payload["usage"]["total_tokens"], 42);
        assert_eq!(payload["usage"]["prompt_tokens_details"]["cached_tokens"], 0);
    }

    #[test]
    fn cache_salt_plumbs_to_the_worker_namespace() {
        // PC-ISO: explicit cache_salt -> the request's cache namespace, on BOTH bodies.
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task", "cache_salt": "tenant-a"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_request(&req, tx, lanes::Lane::Interactive, None).cache_ns, "tenant-a");

        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "task"}],
            "cache_salt": "tenant-b"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap().request.cache_ns, "tenant-b");

        // no salt -> "" (the default single-tenant namespace; pre-PC-ISO behavior).
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_request(&req, tx, lanes::Lane::Interactive, None).cache_ns, "");
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "task"}]
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert_eq!(build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap().request.cache_ns, "");
    }

    #[test]
    fn affinity_key_honors_both_client_conventions_in_priority_order() {
        use axum::http::HeaderMap;
        let hdr = |v: &str| {
            let mut h = HeaderMap::new();
            h.insert("x-session-id", v.parse().unwrap());
            h
        };
        let empty = HeaderMap::new();
        let s = |v: &str| Some(v.to_string());
        // each convention alone.
        assert_eq!(affinity_key(&s("explicit"), &None, &empty), s("explicit"));
        assert_eq!(affinity_key(&None, &s("openai-user"), &empty), s("openai-user"));
        assert_eq!(affinity_key(&None, &None, &hdr("hdr-id")), s("hdr-id"));
        // priority: session_id > user > header. Body beats header because a header can be
        // rewritten by an intermediary.
        assert_eq!(affinity_key(&s("a"), &s("b"), &hdr("c")), s("a"));
        assert_eq!(affinity_key(&None, &s("b"), &hdr("c")), s("b"));
        // blank/whitespace is ABSENT, not a key — a client sending "user": "" must not
        // collapse every conversation onto one shared session.
        assert_eq!(affinity_key(&s("  "), &s(""), &hdr("  ")), None);
        assert_eq!(affinity_key(&s(""), &s("real"), &empty), s("real"));
        // trimmed.
        assert_eq!(affinity_key(&s(" padded "), &None, &empty), s("padded"));
        // nothing supplied -> implicit tier (fingerprint) in the worker.
        assert_eq!(affinity_key(&None, &None, &empty), None);
    }

    #[test]
    fn affinity_key_plumbs_to_the_worker_request_on_both_bodies() {
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task", "session_id": "conv-1"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let key = affinity_key(&req.session_id, &req.user, &axum::http::HeaderMap::new());
        assert_eq!(build_request(&req, tx, lanes::Lane::Interactive, key).affinity.as_deref(),
                   Some("conv-1"));
        // OpenAI `user` on the chat body.
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "task"}],
            "user": "conv-2"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let key = affinity_key(&req.session_id, &req.user, &axum::http::HeaderMap::new());
        assert_eq!(build_chat_request(req, None, tx, lanes::Lane::Interactive, key)
                   .unwrap().request.affinity.as_deref(), Some("conv-2"));
        // absent on both -> None (implicit tier).
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(build_request(&req, tx, lanes::Lane::Interactive, None).affinity.is_none());
    }

    /// Drain an Sse response into its `data:` payload lines (keep-alive comments skipped).
    async fn sse_data_lines(resp: Response) -> Vec<String> {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
            .lines()
            .filter_map(|l| l.strip_prefix("data: ").map(str::to_string))
            .collect()
    }

    #[tokio::test]
    async fn stream_chunks_carry_envelope_and_first_delta_role() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "he".into() }).unwrap();
        tx.send(Event::Token { id: 2, text: "llo".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Eos".into(), n_tokens: 2, n_prompt: 10, n_cached: 0, elapsed_s: 0.1,
            spec: None,
        }).unwrap();
        drop(tx);
        let resp = sse_response(rx, "m".into(), true, None, Envelope::new(true), Vec::new(), None)
            .into_response();
        let lines = sse_data_lines(resp).await;
        assert_eq!(lines.last().map(String::as_str), Some("[DONE]"));
        let chunks: Vec<serde_json::Value> = lines[..lines.len() - 1].iter()
            .map(|l| serde_json::from_str(l).unwrap()).collect();
        // every chunk: id (chatcmpl-, SAME id) + created + system_fingerprint + object.
        let id = chunks[0]["id"].as_str().unwrap().to_string();
        assert!(id.starts_with("chatcmpl-"));
        for c in &chunks {
            assert_eq!(c["id"], id.as_str());
            assert!(c["created"].as_u64().unwrap() > 1_700_000_000);
            assert!(c["system_fingerprint"].as_str().unwrap().starts_with("memra-"));
            assert_eq!(c["object"], "chat.completion.chunk");
        }
        // FIRST delta carries role:"assistant" (SDK accumulator contract); later ones don't.
        assert_eq!(chunks[0]["choices"][0]["delta"]["role"], "assistant");
        assert_eq!(chunks[0]["choices"][0]["delta"]["content"], "he");
        assert!(chunks[1]["choices"][0]["delta"].get("role").is_none());
        // final chunk: finish_reason + usage.
        let fin = chunks.last().unwrap();
        assert_eq!(fin["choices"][0]["finish_reason"], "stop");
        assert_eq!(fin["usage"]["prompt_tokens"], 10);
    }

    #[tokio::test]
    async fn stream_excludes_stop_text_like_non_stream_does() {
        // gap-scan F9: the worker emits the delta BEFORE its stop check — the stream
        // shape must still exclude the stop text (and same-token overshoot) exactly
        // like the non-stream truncate. Stop spans two token events here.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "answer\nPro".into() }).unwrap();
        tx.send(Event::Token { id: 2, text: "blem: leaked prompt".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Callback".into(), n_tokens: 2, n_prompt: 8, n_cached: 0,
            elapsed_s: 0.1, spec: None,
        }).unwrap();
        drop(tx);
        let resp = sse_response(rx, "m".into(), true, None, Envelope::new(true),
                                vec!["Problem:".into()], None).into_response();
        let lines = sse_data_lines(resp).await;
        let content: String = lines.iter()
            .filter(|l| *l != "[DONE]")
            .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
            .filter_map(|c| c["choices"][0]["delta"]["content"].as_str()
                .map(str::to_string))
            .collect();
        assert_eq!(content, "answer\n");

        // held-back text that never becomes a stop is flushed at Done.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "ends in Pro".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Eos".into(), n_tokens: 1, n_prompt: 8, n_cached: 0, elapsed_s: 0.1,
            spec: None,
        }).unwrap();
        drop(tx);
        let resp = sse_response(rx, "m".into(), true, None, Envelope::new(true),
                                vec!["Problem:".into()], None).into_response();
        let lines = sse_data_lines(resp).await;
        let content: String = lines.iter()
            .filter(|l| *l != "[DONE]")
            .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
            .filter_map(|c| c["choices"][0]["delta"]["content"].as_str()
                .map(str::to_string))
            .collect();
        assert_eq!(content, "ends in Pro");
    }

    #[tokio::test]
    async fn stream_worker_error_is_a_data_chunk_not_a_named_event() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Error(worker::EngineError::engine("boom"))).unwrap();
        drop(tx);
        let resp = sse_response(rx, "m".into(), true, None, Envelope::new(true), Vec::new(), None)
            .into_response();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let body = String::from_utf8(bytes.to_vec()).unwrap();
        // OpenAI clients only parse `data:` lines — no named `event: error` on the chat shape.
        assert!(!body.contains("event: error"), "named SSE event leaked: {body}");
        let lines: Vec<&str> = body.lines()
            .filter_map(|l| l.strip_prefix("data: ")).collect();
        let err: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(err["error"]["message"], "boom");
        assert_eq!(err["error"]["type"], "server_error");
        assert_eq!(err["error"]["code"], "engine_error");
        assert_eq!(lines.last(), Some(&"[DONE]"));
    }

    #[tokio::test]
    async fn error_bodies_use_the_openai_object_shape() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Error(worker::EngineError::model_not_found("unknown model \"x\""))).unwrap();
        drop(tx);
        let response = blocking_response(rx, "m".into(), true, Vec::new(), None,
                                         Envelope::new(true)).await;
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        // {"error": {message, type, param, code}} — the object every OpenAI SDK parses.
        assert_eq!(payload["error"]["message"], "unknown model \"x\"");
        assert_eq!(payload["error"]["type"], "invalid_request_error");
        assert_eq!(payload["error"]["param"], "model");
        assert_eq!(payload["error"]["code"], "model_not_found");
    }

    // ---- G6 taxonomy (lane/serve-hardening) --------------------------------------------
    //
    // The mapping is the deliverable, so it is asserted class by class rather than through
    // one happy-path example. Before this lane EVERY row below answered 400
    // invalid_request_error, which no OpenAI-compatible SDK retries.

    fn retry_after(resp: &Response) -> Option<String> {
        resp.headers().get(axum::http::header::RETRY_AFTER)
            .and_then(|v| v.to_str().ok()).map(str::to_string)
    }

    #[test]
    fn taxonomy_maps_every_class_to_its_status_and_code() {
        use worker::{EngineError as E, ErrClass as C};
        let cases: Vec<(worker::EngineError, StatusCode, &str, &str)> = vec![
            (E::invalid_param("bad json", "response_format"),
             StatusCode::BAD_REQUEST, "invalid_request_error", ""),
            (E::context_length("prompt (9000 tok) >= context cap (8192)"),
             StatusCode::BAD_REQUEST, "invalid_request_error", "context_length_exceeded"),
            (E::model_not_found("unknown model \"nope\""),
             StatusCode::BAD_REQUEST, "invalid_request_error", "model_not_found"),
            (E::rate_limit("lane judge is at capacity, retry"),
             StatusCode::TOO_MANY_REQUESTS, "rate_limit_error", "rate_limit_exceeded"),
            (E::overloaded("no VRAM for a new session"),
             StatusCode::SERVICE_UNAVAILABLE, "server_error", "overloaded"),
            (E::engine("graph step failed: launch error"),
             StatusCode::INTERNAL_SERVER_ERROR, "server_error", "engine_error"),
        ];
        for (err, want_status, want_type, want_code) in cases {
            let (status, etype, code) = class_http(err.class);
            assert_eq!(status, want_status, "{:?}", err);
            assert_eq!(etype, want_type, "{:?}", err);
            if !want_code.is_empty() {
                assert_eq!(code, Some(want_code), "{:?}", err);
            }
            // the rendered body agrees with the mapping
            let body = engine_error_body(&err);
            assert_eq!(body["error"]["message"], err.message);
            assert_eq!(body["error"]["type"], want_type);
        }
        // and no class is silently missing from the match
        for c in [C::InvalidRequest, C::ContextLength, C::ModelNotFound,
                  C::RateLimit, C::Overloaded, C::Engine] {
            let (s, t, _) = class_http(c);
            assert!(s.is_client_error() || s.is_server_error(), "{c:?} -> {s}");
            assert!(!t.is_empty());
        }
    }

    #[test]
    fn a_cuda_oom_message_is_capacity_503_not_a_500() {
        // The one deliberate text rule: the driver's own OOM text promotes an engine fault to
        // Overloaded, because the box ran out of VRAM (a retryable capacity condition) rather
        // than hitting a bug. Same predicate the step-OOM park path uses, so the two paths
        // cannot disagree about what an OOM is.
        let e = worker::EngineError::engine(
            "step error: DriverError(CUDA_ERROR_OUT_OF_MEMORY, \"out of memory\")");
        let resp = engine_error_response(&e);
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(retry_after(&resp).as_deref(), Some("5"));
    }

    #[test]
    fn retry_headers_follow_the_sdk_contract() {
        // openai-python reads retry-after-ms FIRST, then retry-after, and ABANDONS the retry
        // if the delay exceeds 120 s; litellm honors retry-after only for 0 < v <= 60. So:
        // integer seconds, <= 60, with a matching millisecond twin.
        for e in [worker::EngineError::rate_limit("shed"),
                  worker::EngineError::overloaded("no VRAM")] {
            let resp = engine_error_response(&e);
            let ra = retry_after(&resp).expect("retryable class must carry Retry-After");
            let secs: u64 = ra.parse().expect("Retry-After must be integer delay-seconds");
            assert!(secs > 0 && secs <= 60, "Retry-After {secs}s outside the honored window");
            let ms = resp.headers().get("retry-after-ms").unwrap().to_str().unwrap();
            assert_eq!(ms.parse::<u64>().unwrap(), secs * 1000, "the two headers disagree");
            assert!(resp.headers().get("x-should-retry").is_none(),
                    "a retryable class must not say x-should-retry: false");
        }
    }

    #[tokio::test]
    async fn command_send_failure_obeys_the_retry_contract() {
        let _l = DRAIN_LOCK.lock().unwrap();
        DRAINING.store(false, std::sync::atomic::Ordering::SeqCst);
        let mut st = fake_worker_state();
        let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<Cmd>();
        drop(cmd_rx);
        st.cmd_tx = cmd_tx;

        let completion = completions(
            State(st.clone()),
            axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "prompt": "test"
            })).unwrap()),
        ).await;
        let chat = chat_completions(
            State(st),
            axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "messages": [{"role": "user", "content": "test"}]
            })).unwrap()),
        ).await;

        for resp in [completion, chat] {
            assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
            assert_eq!(retry_after(&resp).as_deref(), Some("2"));
            assert_eq!(resp.headers().get("retry-after-ms").unwrap(), "2000");
            assert_ne!(resp.headers().get("x-should-retry")
                .and_then(|v| v.to_str().ok()), Some("false"));
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
            let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
            assert_eq!(payload["error"]["type"], "server_error");
            assert_eq!(payload["error"]["code"], "overloaded");
        }
    }

    #[test]
    fn unfixable_client_errors_say_x_should_retry_false() {
        // Retrying the identical bytes cannot succeed, and a client that retries on status
        // alone would hammer for nothing. openai-python honors this override explicitly.
        for e in [worker::EngineError::model_not_found("unknown model \"x\""),
                  worker::EngineError::context_length("prompt too long"),
                  worker::EngineError::invalid_param("bad", "messages")] {
            let resp = engine_error_response(&e);
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
            assert_eq!(resp.headers().get("x-should-retry").unwrap(), "false");
            assert!(retry_after(&resp).is_none(), "a 400 must not promise a retry window");
        }
    }

    #[tokio::test]
    async fn a_closed_worker_channel_is_503_not_500() {
        // The worker thread died (panicked, unrecoverable) mid-request: the Event channel
        // closes with neither Done nor Error. The client's retry may land on a restarted
        // process, so this is capacity-class with a window — not a bare 500.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
        drop(tx);
        let resp = blocking_response(rx, "m".into(), true, Vec::new(), None,
                                     Envelope::new(true)).await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(retry_after(&resp).as_deref(), Some("5"));
    }

    #[tokio::test]
    async fn a_dark_lane_shed_is_429_with_an_openai_object_body() {
        // peek_shed used to answer `{"error": "<string>"}` — a bare string where every SDK
        // expects an object, which renders as a blank message client-side.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Error(worker::EngineError::rate_limit(
            "lane judge shed: interactive p99 over budget, retry"))).unwrap();
        let resp = peek_shed(lanes::Lane::Judge, rx).await
            .err().expect("a shed must not be forwarded into the stream");
        assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(retry_after(&resp).as_deref(), Some("2"));
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(payload["error"].is_object(), "bare-string error body: {payload}");
        assert_eq!(payload["error"]["type"], "rate_limit_error");
        assert!(payload["error"]["message"].as_str().unwrap().contains("shed"));
    }

    #[tokio::test]
    async fn interactive_never_peeks_so_its_first_token_is_not_held() {
        // Interactive does not shed, and its first token may legitimately be seconds away —
        // the peek would hold headers for nothing.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Error(worker::EngineError::rate_limit("would-be shed"))).unwrap();
        assert!(peek_shed(lanes::Lane::Interactive, rx).await.is_ok());
    }

    #[test]
    fn penalties_plumb_from_http_to_sampler_config() {
        // gap-scan F3: the fields existed in SamplerConfig all along — assert the HTTP
        // layer actually delivers them, with the whole-history window armed.
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "task"}],
            "frequency_penalty": 0.5, "presence_penalty": 0.25, "repetition_penalty": 1.1
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let cfg = build_chat_request(req, None, tx, lanes::Lane::Interactive, None).unwrap().request.sampler_cfg;
        assert_eq!(cfg.penalty_freq, 0.5);
        assert_eq!(cfg.penalty_present, 0.25);
        assert_eq!(cfg.penalty_repeat, 1.1);
        assert_eq!(cfg.penalty_last_n, usize::MAX);

        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task", "frequency_penalty": 1.5
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let cfg = build_request(&req, tx, lanes::Lane::Interactive, None).sampler_cfg;
        assert_eq!(cfg.penalty_freq, 1.5);
        assert_eq!(cfg.penalty_last_n, usize::MAX);

        // no penalties set -> window off, byte-identical legacy config.
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "task"
        })).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let cfg = build_request(&req, tx, lanes::Lane::Interactive, None).sampler_cfg;
        assert_eq!(cfg.penalty_last_n, 0);
        assert_eq!(cfg.penalty_repeat, 1.0);
    }

    #[test]
    fn omitted_temperature_is_openai_default_not_greedy() {
        // dogfood F4: `#[serde(default)] temperature: f32` yielded 0.0 = greedy, so any
        // client that omits temperature (the owner's own agentic pill, the OpenAI SDK's
        // documented "leave it out" path) got locked into deterministic argmax — same
        // context in, same token out, identical tool-call cycles forever. OpenAI's
        // default-when-omitted is 1.0 on BOTH surfaces.
        let chat_temp = |body: serde_json::Value| {
            let req: ChatCompletionReq = serde_json::from_value(body).unwrap();
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            build_chat_request(req, None, tx, lanes::Lane::Interactive, None)
                .unwrap().request.sampler_cfg.temperature
        };
        let comp_temp = |body: serde_json::Value| {
            let req: CompletionReq = serde_json::from_value(body).unwrap();
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            build_request(&req, tx, lanes::Lane::Interactive, None).sampler_cfg.temperature
        };

        // OMITTED => 1.0 (sampled), all the way through to the SamplerConfig.
        assert_eq!(chat_temp(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}]})), 1.0,
            "omitted chat temperature must be the OpenAI 1.0 default, not 0.0/greedy");
        assert_eq!(comp_temp(serde_json::json!({
            "model": "m", "prompt": "t"})), 1.0,
            "omitted completions temperature must be the OpenAI 1.0 default");

        // EXPLICIT 0 still means greedy — a caller asking for determinism gets it.
        assert_eq!(chat_temp(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}],
            "temperature": 0.0})), 0.0, "explicit temperature 0 must stay greedy");
        assert_eq!(comp_temp(serde_json::json!({
            "model": "m", "prompt": "t", "temperature": 0})), 0.0,
            "explicit temperature 0 must stay greedy");
        // and the greedy predicate agrees (this is what gates the spec/graph arms).
        assert!(memra_engine::sampler::Sampler::new(
            sampler_config(0.0, 0, 1.0, 0.0, 0.0, 0.0, 1.0, Some(0))).is_greedy());
        assert!(!memra_engine::sampler::Sampler::new(
            sampler_config(1.0, 0, 1.0, 0.0, 0.0, 0.0, 1.0, Some(0))).is_greedy());

        // explicit non-default values still pass through untouched.
        assert_eq!(chat_temp(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}],
            "temperature": 0.7})), 0.7);

        // OMITTED filter defaults: top_p disabled at 1.0 (OpenAI default), top_k/min_p
        // disabled at 0 (not OpenAI params — OpenRouter/HF convention, 0 = keep all).
        // An omitted-temperature request must therefore be PURE temperature-1.0 sampling.
        let req: CompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "prompt": "t"})).unwrap();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let cfg = build_request(&req, tx, lanes::Lane::Interactive, None).sampler_cfg;
        assert_eq!(cfg.top_p, 1.0, "omitted top_p = OpenAI 1.0 = disabled");
        assert_eq!(cfg.top_k, 0, "omitted top_k = disabled");
        assert_eq!(cfg.min_p, 0.0, "omitted min_p = disabled");
        assert_eq!(cfg.penalty_last_n, 0, "omitted penalties = window off");
        // and it lands in the PURE-TEMP sampled-spec regime — the one that keeps the
        // in-graph sampled draft chain (spec.rs `pure_temp`). Filters/penalties would still
        // be spec-eligible but would drop the draft to the eager chain, so the default
        // request shape must stay in the fast regime.
        assert!(memra_engine::sampler::Sampler::new(cfg).is_spec_sampling(),
                "the omitted-temperature default must ride sampled spec's pure-temp regime");
    }

    #[test]
    fn omitted_seed_is_fresh_entropy_not_a_pinned_zero() {
        // dogfood F4, SECOND HALF — found only by driving the live server. Fixing the
        // temperature default is NOT sufficient: `#[serde(default)] seed: u64` gave 0, a
        // perfectly valid FIXED seed, so a temp-1.0 request with seed omitted still replayed
        // one single sampled stream. Measured on the pre-fix binary: 4/4 byte-identical
        // completions at temperature 1.0 with seed omitted (receipts in
        // research/sampledspec-20260804/). The loop survives the temperature fix alone.
        let comp_seed = |body: serde_json::Value| {
            let req: CompletionReq = serde_json::from_value(body).unwrap();
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            build_request(&req, tx, lanes::Lane::Interactive, None).sampler_cfg.seed
        };
        let chat_seed = |body: serde_json::Value| {
            let req: ChatCompletionReq = serde_json::from_value(body).unwrap();
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            build_chat_request(req, None, tx, lanes::Lane::Interactive, None)
                .unwrap().request.sampler_cfg.seed
        };

        // OMITTED seed: successive requests must NOT share a seed (that was the loop), and
        // must not be the old pinned 0.
        let a = comp_seed(serde_json::json!({"model": "m", "prompt": "t"}));
        let b = comp_seed(serde_json::json!({"model": "m", "prompt": "t"}));
        let c = chat_seed(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}]}));
        assert_ne!(a, 0, "omitted seed must not be the pinned 0 that caused the loop");
        assert_ne!(b, 0);
        assert_ne!(c, 0);
        assert_ne!(a, b, "two seed-omitting requests must get DIFFERENT streams");
        assert_ne!(a, c);

        // EXPLICIT seed is honored exactly — including an explicit 0, which every
        // determinism gate in tools/ and research/ relies on.
        assert_eq!(comp_seed(serde_json::json!({
            "model": "m", "prompt": "t", "seed": 0})), 0,
            "explicit seed 0 must stay 0 — the determinism gates depend on it");
        assert_eq!(comp_seed(serde_json::json!({
            "model": "m", "prompt": "t", "seed": 12345})), 12345);
        assert_eq!(chat_seed(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}],
            "seed": 777})), 777);
        // explicit seed is reproducible across calls (the gate contract).
        assert_eq!(comp_seed(serde_json::json!({"model": "m", "prompt": "t", "seed": 42})),
                   comp_seed(serde_json::json!({"model": "m", "prompt": "t", "seed": 42})));

        // fresh_seed itself: never 0, and distinct across rapid successive calls (the
        // same-nanosecond batched-arrival case the counter mix exists for).
        let seeds: std::collections::HashSet<u64> = (0..256).map(|_| fresh_seed()).collect();
        assert_eq!(seeds.len(), 256, "fresh_seed must not collide across rapid calls");
        assert!(!seeds.contains(&0));
    }

    #[test]
    fn response_format_builds_grammar_only_when_present() {
        // NO-OP CONTRACT (lane/constrained): absent / {"type":"text"} => grammar None —
        // the worker Request is field-identical to a pre-lane request, no llguidance
        // object is ever built. json_object / json_schema arm the grammar.
        let mk = |rf: Option<serde_json::Value>| {
            let mut body = serde_json::json!({
                "model": "m", "messages": [{"role": "user", "content": "t"}]});
            if let Some(rf) = rf { body["response_format"] = rf; }
            let req: ChatCompletionReq = serde_json::from_value(body).unwrap();
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            build_chat_request(req, None, tx, lanes::Lane::Interactive, None)
        };
        assert!(mk(None).unwrap().request.grammar.is_none());
        assert!(mk(Some(serde_json::json!({"type": "text"})))
            .unwrap().request.grammar.is_none());
        assert!(matches!(mk(Some(serde_json::json!({"type": "json_object"})))
            .unwrap().request.grammar,
            Some(constrained::GrammarSpec::JsonObject)));
        assert!(matches!(mk(Some(serde_json::json!({"type": "json_schema",
            "json_schema": {"schema": {"type": "object"}}})))
            .unwrap().request.grammar,
            Some(constrained::GrammarSpec::JsonSchema(_))));
        // unknown type: loud error, never silent.
        assert!(mk(Some(serde_json::json!({"type": "yaml"}))).is_err());
    }

    #[test]
    fn unsupported_semantic_params_are_named_rejections() {
        // gap-scan F4: fields serde used to swallow now deserialize into rejection slots.
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}],
            "response_format": {"type": "json_object"}
        })).unwrap();
        assert!(req.response_format.is_some());
        let req: ChatCompletionReq = serde_json::from_value(serde_json::json!({
            "model": "m", "messages": [{"role": "user", "content": "t"}],
            "response_format": {"type": "text"}, "logprobs": false, "n": 1,
            "user": "u-1", "stream_options": {"include_usage": true}
        })).unwrap();
        // the no-op forms + cosmetic fields: all fine (accept-and-ignore class).
        assert_eq!(req.response_format.as_ref().unwrap()["type"], "text");
        assert_eq!(req.logprobs.as_ref().unwrap().as_bool(), Some(false));
        assert_eq!(req.n, Some(1));
        // the gate law itself: present -> named error, absent -> Ok.
        assert!(reject_unsupported(&[("logit_bias", false, "")]).is_ok());
        let (msg, param) = reject_unsupported(&[("logit_bias", true, " (why)")]).unwrap_err();
        assert_eq!(param, "logit_bias");
        assert_eq!(msg, "logit_bias is not supported (why)");
    }

    #[test]
    fn completions_accept_openai_stop_forms() {
        for (value, expected) in [
            (serde_json::json!("Problem:"), vec!["Problem:"]),
            (serde_json::json!(["Question:", "Problem:"]), vec!["Question:", "Problem:"]),
            (serde_json::Value::Null, Vec::<&str>::new()),
        ] {
            let req: CompletionReq = serde_json::from_value(serde_json::json!({
                "model": "plain_quant", "prompt": "task", "stop": value
            })).unwrap();
            assert_eq!(req.stop.into_vec(), expected);
        }
    }

    /// Fake GPU worker: consumes Generate commands and answers each with one Token +
    /// Done — handler-level tests (headers, drain) without a GPU or a loaded model.
    ///
    /// It also drives the SAME health handle the real worker does (mark_ready at "load"
    /// completion, beat_busy per iteration), which is what lets the /health and /readyz tests
    /// exercise the real handlers instead of a mock.
    fn fake_worker_state() -> AppState {
        let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<Cmd>();
        let health = health::WorkerHealth::new();
        let h = health.clone();
        std::thread::spawn(move || {
            h.mark_ready();
            while let Ok(Cmd::Generate(req)) = cmd_rx.recv() {
                // mirror handle_cmd's saturating PENDING_ADMITS decrement: handlers
                // increment before send, and a fake worker that never decrements leaks
                // the process-global gauge into every other test (the valley signal
                // reads it).
                let _ = worker::PENDING_ADMITS.fetch_update(
                    std::sync::atomic::Ordering::AcqRel,
                    std::sync::atomic::Ordering::Acquire,
                    |v| v.checked_sub(1),
                );
                h.beat_busy();
                let _ = req.tx.send(Event::Token { id: 1, text: "ok".into() });
                let _ = req.tx.send(Event::Done {
                    stop_reason: "Eos".into(), n_tokens: 1, n_prompt: 1, n_cached: 0,
                    elapsed_s: 0.01, spec: None,
                });
                h.set_phase(health::PHASE_IDLE);
            }
        });
        // The spawn above is the "load"; wait for its ready stamp so a health assertion is not
        // racing the thread start (the real path blocks on ready_tx for the same reason).
        for _ in 0..2000 {
            if health.live().is_ok() { break; }
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        AppState {
            cmd_tx,
            models: Arc::new(vec!["m".into()]),
            caps: Arc::new(HashMap::new()),
            openrouter_metadata: Arc::new(HashMap::new()),
            metrics: SharedMetrics::default(),
            started: 1,
            inflight: Arc::new(Default::default()),
            tenant_inflight: Arc::new(Default::default()),
            health,
            bg: None,
        }
    }

    #[test]
    fn rate_limit_math_remaining_hits_zero_at_cap_and_reset_arms() {
        let metrics = SharedMetrics::default();
        // free slots: remaining counts down, reset stays 0.
        let rl = RateLimit::compute(4, 1, &metrics);
        assert_eq!((rl.limit, rl.remaining, rl.reset_s), (4, 3, 0));
        let rl = RateLimit::compute(4, 3, &metrics);
        assert_eq!(rl.remaining, 1);
        // at cap: remaining 0, reset arms (static default — no meter signal here).
        let rl = RateLimit::compute(4, 4, &metrics);
        assert_eq!(rl.remaining, 0);
        assert!(rl.reset_s > 0, "reset must arm when no slots are free");
        // over cap (queued interactive): saturates at 0, never underflows.
        assert_eq!(RateLimit::compute(4, 9, &metrics).remaining, 0);
        // meter signal: reset = mean tokens/request x p50 step, ceil seconds.
        let m = worker::Metrics {
            completed: 2, tokens_out: 200, step_p50_ms: 20.0, ..Default::default()
        };
        assert_eq!(reset_estimate_s(&m), 2); // 100 tok x 20ms = 2.0s
    }

    #[test]
    fn inflight_guard_counts_up_and_frees_on_drop() {
        let counts: InflightCounts = Arc::new(Default::default());
        let tenants: TenantGauge = Arc::new(Default::default());
        let (g1, n1, t1) = InflightGuard::try_acquire(
            counts.clone(), lanes::Lane::Interactive, tenants.clone(), "acme", None)
            .unwrap();
        let (g2, n2, t2) = InflightGuard::try_acquire(
            counts.clone(), lanes::Lane::Interactive, tenants.clone(), "acme", None)
            .unwrap();
        assert_eq!((n1, n2), (1, 2));
        // tenant gauge counts per tenant, across lanes.
        assert_eq!((t1, t2), (1, 2));
        // lanes are independent gauges; a different tenant starts at 1.
        let (gj, nj, tj) = InflightGuard::try_acquire(
            counts.clone(), lanes::Lane::Judge, tenants.clone(), "blue", None)
            .unwrap();
        assert_eq!((nj, tj), (1, 1));
        drop(g1);
        drop(gj);
        assert_eq!(counts[0].load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 0);
        assert_eq!(tenants.lock().unwrap().get("acme"), Some(&1));
        // tenant entries are removed at zero (bounded by CONCURRENT tenants).
        assert!(tenants.lock().unwrap().get("blue").is_none());
        drop(g2);
        assert_eq!(counts[0].load(std::sync::atomic::Ordering::SeqCst), 0);
        assert!(tenants.lock().unwrap().is_empty());
    }

    #[test]
    fn tenant_concurrency_cap_is_atomic_across_arrivals() {
        let counts: InflightCounts = Arc::new(Default::default());
        let tenants: TenantGauge = Arc::new(Default::default());
        let start = Arc::new(std::sync::Barrier::new(3));
        let attempted = Arc::new(std::sync::Barrier::new(3));
        let mut joins = Vec::new();
        for _ in 0..2 {
            let counts = counts.clone();
            let tenants = tenants.clone();
            let start = start.clone();
            let attempted = attempted.clone();
            joins.push(std::thread::spawn(move || {
                start.wait();
                let result = InflightGuard::try_acquire(
                    counts, lanes::Lane::Interactive, tenants, "preview_001", Some(1));
                let won = result.is_ok();
                attempted.wait(); // winner holds its guard until both arrivals attempted.
                drop(result);
                won
            }));
        }
        start.wait();
        attempted.wait();
        let wins = joins.into_iter()
            .map(|join| join.join().unwrap())
            .filter(|won| *won)
            .count();
        assert_eq!(wins, 1, "exactly one simultaneous request may pass cap=1");
        assert_eq!(counts[0].load(std::sync::atomic::Ordering::SeqCst), 0);
        assert!(tenants.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn tenant_concurrency_cap_rejects_before_worker_admission() {
        let st = fake_worker_state();
        let tenant = auth::TenantCtx {
            tenant: "preview_001".into(),
            lane_class: auth::LaneClass::Interactive,
            rate_limit: Some(1),
        };
        let first_env = Envelope::new(true);
        let (guard, first_rl) = match acquire_request_slot(
            &st, lanes::Lane::Interactive, &tenant, &first_env)
        {
            Ok(slot) => slot,
            Err(_) => panic!("the first request must acquire the tenant slot"),
        };
        assert_eq!((first_rl.limit, first_rl.remaining), (1, 0));

        let second_env = Envelope::new(true);
        let response = match acquire_request_slot(
            &st, lanes::Lane::Interactive, &tenant, &second_env)
        {
            Err(response) => response,
            Ok(_) => panic!("the second request must be rejected at the tenant cap"),
        };
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(response.headers()["retry-after"], "2");
        assert_eq!(response.headers()["retry-after-ms"], "2000");
        assert_eq!(response.headers()["x-ratelimit-limit"], "1");
        assert_eq!(response.headers()["x-ratelimit-remaining"], "0");
        assert_eq!(response.headers()["x-request-id"], second_env.id);
        assert_eq!(st.inflight[0].load(std::sync::atomic::Ordering::SeqCst), 1,
                   "rejected request must not consume a lane slot");
        assert_eq!(
            st.tenant_inflight.lock().unwrap().get("preview_001").copied(), Some(1),
            "rejected request must not increment the tenant gauge");
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["error"]["type"], "rate_limit_error");
        assert_eq!(payload["error"]["code"], "rate_limit_exceeded");
        assert!(payload["error"]["message"].as_str().unwrap()
            .contains("concurrent request limit"));

        drop(guard);
        let _ = InflightGuard::try_acquire(
            st.inflight.clone(), lanes::Lane::Interactive,
            st.tenant_inflight.clone(), "preview_001", Some(1))
            .expect("slot must reopen after the in-flight request completes");
    }

    #[test]
    fn tenant_rate_limit_override_is_min_with_global_cap() {
        let metrics = SharedMetrics::default();
        let unlimited = auth::TenantCtx::default_tenant();
        let capped = auth::TenantCtx {
            tenant: "acme".into(),
            lane_class: auth::LaneClass::Interactive,
            rate_limit: Some(2),
        };
        let global = lane_cap(lanes::Lane::Interactive);
        // no override: the global lane cap reports as before.
        let rl = RateLimit::at_admit(lanes::Lane::Interactive, 1, &metrics, &unlimited, 1);
        assert_eq!((rl.limit, rl.remaining), (global, global - 1));
        // override binds: limit = the tenant cap, remaining counts the TENANT gauge.
        let rl = RateLimit::at_admit(lanes::Lane::Interactive, 5, &metrics, &capped, 1);
        assert_eq!((rl.limit, rl.remaining), (2, 1));
        let rl = RateLimit::at_admit(lanes::Lane::Interactive, 5, &metrics, &capped, 2);
        assert_eq!(rl.remaining, 0);
        assert!(rl.reset_s > 0, "reset must arm at the tenant cap too");
        // the GLOBAL cap stays authoritative: a saturated lane zeroes the tenant's
        // remaining even below its own cap, and an override above the global cap is
        // ignored (min(t, global) — a key cannot widen the lane).
        let rl = RateLimit::at_admit(lanes::Lane::Interactive, global, &metrics, &capped, 0);
        assert_eq!(rl.remaining, 0);
        let wide = auth::TenantCtx { rate_limit: Some(global + 100), ..capped.clone() };
        let rl = RateLimit::at_admit(lanes::Lane::Interactive, 1, &metrics, &wide, 1);
        assert_eq!((rl.limit, rl.remaining), (global, global - 1));
    }

    #[test]
    fn batch_class_keys_default_to_harvest_and_cannot_claim_interactive() {
        let batch = auth::TenantCtx {
            tenant: "bulk".into(),
            lane_class: auth::LaneClass::Batch,
            rate_limit: None,
        };
        let interactive = auth::TenantCtx::default_tenant();
        let hdr = |v: Option<&str>| {
            let mut h = axum::http::HeaderMap::new();
            if let Some(v) = v {
                h.insert("x-lane", axum::http::HeaderValue::from_str(v).unwrap());
            }
            h
        };
        // interactive-class: legacy behavior exactly (default interactive, header honored).
        assert_eq!(lane_for_tenant(&hdr(None), &interactive).unwrap(),
                   lanes::Lane::Interactive);
        assert_eq!(lane_for_tenant(&hdr(Some("judge")), &interactive).unwrap(),
                   lanes::Lane::Judge);
        // batch-class: defaults to harvest; judge ok; interactive is a loud 403.
        assert_eq!(lane_for_tenant(&hdr(None), &batch).unwrap(), lanes::Lane::Harvest);
        assert_eq!(lane_for_tenant(&hdr(Some("judge")), &batch).unwrap(),
                   lanes::Lane::Judge);
        let resp = lane_for_tenant(&hdr(Some("interactive")), &batch).unwrap_err();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        // unknown lane still 400s for everyone.
        let resp = lane_for_tenant(&hdr(Some("turbo")), &interactive).unwrap_err();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn handler_layer_refusals_are_openai_objects_with_x_should_retry() {
        // The lane refusals were the last bare-string error bodies on the surface:
        // `{"error": "unknown x-lane ..."}` indexes as a string in every SDK that reads
        // error.type / error.code. Both lane refusals now go through error_response_coded,
        // and both are unfixable-by-retry 4xx, so both must also say so in a header.
        let hdr = |v: &str| {
            let mut h = axum::http::HeaderMap::new();
            h.insert("x-lane", axum::http::HeaderValue::from_str(v).unwrap());
            h
        };
        let body = |resp: Response| async move {
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
            serde_json::from_slice::<serde_json::Value>(&bytes).unwrap()
        };

        let resp = lane_for_tenant(&hdr("turbo"), &auth::TenantCtx::default_tenant()).unwrap_err();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        assert_eq!(resp.headers().get("x-should-retry").unwrap(), "false");
        let payload = body(resp).await;
        assert!(payload["error"].is_object(), "bare-string error body: {payload}");
        assert_eq!(payload["error"]["type"], "invalid_request_error");
        assert_eq!(payload["error"]["param"], "x-lane");
        assert_eq!(payload["error"]["code"], "invalid_lane");

        let batch = auth::TenantCtx {
            tenant: "bulk".into(), lane_class: auth::LaneClass::Batch, rate_limit: None,
        };
        let resp = lane_for_tenant(&hdr("interactive"), &batch).unwrap_err();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        assert_eq!(resp.headers().get("x-should-retry").unwrap(), "false");
        let payload = body(resp).await;
        assert_eq!(payload["error"]["type"], "authentication_error");
        assert_eq!(payload["error"]["param"], "x-lane");
    }

    /// Serializes tests that read or flip the process-global DRAINING flag (the drain
    /// test must not 503 a concurrently-running handler test).
    static DRAIN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[tokio::test]
    async fn responses_carry_rate_limit_headers_and_slot_frees() {
        let _l = DRAIN_LOCK.lock().unwrap();
        let st = fake_worker_state();
        // non-stream chat: headers present, remaining = cap - 1 (this request held
        // the only slot), slot freed after completion.
        let resp = chat_completions(State(st.clone()), axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "messages": [{"role": "user", "content": "t"}]
            })).unwrap())).await;
        assert_eq!(resp.status(), StatusCode::OK);
        let h = resp.headers();
        let limit: usize = h["x-ratelimit-limit"].to_str().unwrap().parse().unwrap();
        let remaining: usize = h["x-ratelimit-remaining"].to_str().unwrap().parse().unwrap();
        assert_eq!(remaining, limit - 1);
        assert_eq!(h["x-ratelimit-reset"], "0");
        assert_eq!(st.inflight[0].load(std::sync::atomic::Ordering::SeqCst), 0,
                   "slot must free at completion");
        // streaming completions: headers on the SSE response too; slot freed once the
        // body is drained (the guard rides the stream).
        let resp = completions(State(st.clone()), axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "prompt": "t", "stream": true
            })).unwrap())).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert!(resp.headers().contains_key("x-ratelimit-limit"));
        assert!(resp.headers().contains_key("x-ratelimit-remaining"));
        assert!(resp.headers().contains_key("x-ratelimit-reset"));
        assert_eq!(st.inflight[0].load(std::sync::atomic::Ordering::SeqCst), 1,
                   "stream in flight holds the slot");
        let _ = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        assert_eq!(st.inflight[0].load(std::sync::atomic::Ordering::SeqCst), 0,
                   "slot must free when the stream completes");
    }

    #[tokio::test]
    async fn draining_rejects_new_requests_with_503_and_retry_after() {
        let _l = DRAIN_LOCK.lock().unwrap();
        let st = fake_worker_state();
        DRAINING.store(true, std::sync::atomic::Ordering::SeqCst);
        // both completion routes: immediate 503 + Retry-After, no slot held.
        let resp = chat_completions(State(st.clone()), axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "messages": [{"role": "user", "content": "t"}]
            })).unwrap())).await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        // The drain 503 obeys the same retry contract as every taxonomy class: an integer
        // Retry-After <= 60, the retry-after-ms twin openai-python reads FIRST (its absence
        // was a real gap — a client trusting only the ms header saw NO window on memra's most
        // predictable outage), both agreeing, and a `code` clients can branch on.
        let ra = resp.headers()["retry-after"].to_str().unwrap().to_string();
        let ra_s: u64 = ra.parse().expect("Retry-After must be integer delay-seconds");
        assert!(ra_s > 0 && ra_s <= 60, "Retry-After {ra_s}s is outside the honored window");
        let ra_ms: u64 = resp.headers()["retry-after-ms"].to_str().unwrap().parse().unwrap();
        assert_eq!(ra_ms, ra_s * 1000, "the two retry headers must agree");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(payload["error"]["message"].as_str().unwrap().contains("draining"));
        assert_eq!(payload["error"]["type"], "server_error");
        assert_eq!(payload["error"]["code"], "draining");
        let resp = completions(State(st.clone()), axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "prompt": "t"
            })).unwrap())).await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert!(resp.headers().contains_key("retry-after"));
        assert_eq!(st.inflight[0].load(std::sync::atomic::Ordering::SeqCst), 0,
                   "rejected requests must not hold slots");
        // /health flips to "draining" but stays 200 — a drain is a HEALTHY shutdown, and 503
        // here would invite a supervisor to SIGKILL a process that is finishing streams.
        let resp = health_live(State(st.clone())).await.into_response();
        assert_eq!(resp.status(), StatusCode::OK, "a drain must not look like a liveness fault");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["status"], "draining");
        // Rotation is /readyz's job: unready while draining, so the LB stops sending.
        let resp = health_ready(State(st.clone())).await.into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let retry_s = drain_deadline_s().clamp(1, 60);
        let retry_s_text = retry_s.to_string();
        let retry_ms_text = (retry_s * 1000).to_string();
        assert_eq!(retry_after(&resp).as_deref(), Some(retry_s_text.as_str()));
        assert_eq!(resp.headers().get("retry-after-ms").unwrap(),
                   retry_ms_text.as_str());
        assert_ne!(resp.headers().get("x-should-retry")
            .and_then(|v| v.to_str().ok()), Some("false"));
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["status"], "not_ready");
        assert!(payload["detail"].as_str().unwrap().contains("draining"));
        DRAINING.store(false, std::sync::atomic::Ordering::SeqCst);
        // flag cleared: requests admit again (the gate is the flag, nothing latent).
        let resp = chat_completions(State(st.clone()), axum::http::HeaderMap::new(),
            Json(serde_json::from_value(serde_json::json!({
                "model": "m", "messages": [{"role": "user", "content": "t"}]
            })).unwrap())).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ---- G5: /health reports INFERENCE liveness, not process liveness -------------------

    #[tokio::test]
    async fn health_is_green_only_while_the_worker_is_alive() {
        // /readyz reads the process-global DRAINING flag, which the drain test toggles —
        // serialize against it or this races (measured: an interleaved run saw 503 here).
        let _l = DRAIN_LOCK.lock().unwrap();
        let st = fake_worker_state();
        // loaded + alive: 200 ok, and the payload explains WHY (phase + heartbeat age vs the
        // threshold), so an operator reading a green never has to guess.
        let resp = health_live(State(st.clone())).await.into_response();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["status"], "ok");
        assert_eq!(payload["worker"]["phase"], "idle");
        assert!(payload["worker"]["stall_threshold_ms"].as_u64().unwrap() > 0);
        let ready = health_ready(State(st.clone())).await.into_response();
        assert_eq!(ready.status(), StatusCode::OK);

        // THE REGRESSION THIS PINS. Kill inference the way a panic does — the health handle
        // is marked dead, the HTTP task keeps running, the process is entirely fine. The old
        // handler returned `{"status":"ok"}` here, forever, on a box answering nothing.
        st.health.mark_dead("worker thread panicked: test-injected");
        let resp = health_live(State(st.clone())).await.into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE,
                   "a dead worker MUST NOT report a healthy liveness");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["status"], "unhealthy");
        // the cause is QUOTED, not inferred — the panic text travels to the operator
        assert!(payload["detail"].as_str().unwrap().contains("test-injected"),
                "cause not surfaced: {payload}");
        let ready = health_ready(State(st.clone())).await.into_response();
        assert_eq!(ready.status(), StatusCode::SERVICE_UNAVAILABLE, "dead is also not ready");

        // Latency of the flip: a fault latch, not a timeout — no staleness threshold to wait
        // out, which is what makes this usable as a k8s livenessProbe.
        st.health.mark_ready();
        assert_eq!(health_live(State(st.clone())).await.into_response().status(),
                   StatusCode::OK, "mark_ready must clear the latch (a successful respawn)");
    }

    #[tokio::test]
    async fn liveness_failure_obeys_the_retry_contract() {
        let st = fake_worker_state();
        st.health.mark_dead("worker thread panicked: retry-contract-test");

        let resp = health_live(State(st)).await.into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(retry_after(&resp).as_deref(), Some("2"));
        assert_eq!(resp.headers().get("retry-after-ms").unwrap(), "2000");
        assert_ne!(resp.headers().get("x-should-retry")
            .and_then(|v| v.to_str().ok()), Some("false"));
    }

    #[tokio::test]
    async fn readiness_failure_obeys_the_retry_contract() {
        let _l = DRAIN_LOCK.lock().unwrap();
        DRAINING.store(false, std::sync::atomic::Ordering::SeqCst);
        let st = fake_worker_state();
        st.health.mark_dead("worker thread panicked: retry-contract-test");

        let resp = health_ready(State(st)).await.into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(retry_after(&resp).as_deref(), Some("2"));
        assert_eq!(resp.headers().get("retry-after-ms").unwrap(), "2000");
        assert_ne!(resp.headers().get("x-should-retry")
            .and_then(|v| v.to_str().ok()), Some("false"));
    }

    #[tokio::test]
    async fn a_wedged_gpu_flips_health_even_though_the_worker_thread_is_fine() {
        // G24: Xid 119/120 hangs nvidia-smi and emits no Xid line; the watcher's probe
        // timeout is the alarm. The worker thread may still be looping (blocked in a driver
        // call), so the heartbeat alone would never catch this — the GPU latch does.
        let st = fake_worker_state();
        assert_eq!(health_live(State(st.clone())).await.into_response().status(), StatusCode::OK);
        st.health.mark_gpu_fault("nvidia-smi probe exceeded 10s deadline (GSP hang class)");
        let resp = health_live(State(st.clone())).await.into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(payload["detail"].as_str().unwrap().contains("probe exceeded"));
        // A GPU fault survives mark_ready deliberately: a respawned worker on a wedged card
        // is not recovery, and only a fresh process (new CUDA context) can be.
        st.health.mark_ready();
        assert_eq!(health_live(State(st.clone())).await.into_response().status(),
                   StatusCode::SERVICE_UNAVAILABLE,
                   "a GPU fault must not be cleared by an in-process respawn");
    }

    #[test]
    fn v1_models_entry_keeps_catalog_shape_with_honest_nulls() {
        // KNOWN plan metadata populates every OR-schema field from worker truth.
        let caps = ModelCaps {
            tools_branch: true, qwen_think: true, think_switch: true, chat_ok: true,
            context_length: 262144,
            tokenizer: "qwen2".into(),
            instruct_type: Some("chatml".into()),
            effort_levels: false,
            gemma_think: false,
        };
        let e = model_entry_v1("main", Some(&caps), 1_754_000_000);
        assert_eq!(e["id"], "main");
        assert_eq!(e["name"], "main");
        assert_eq!(e["object"], "model");
        assert_eq!(e["created"], 1_754_000_000u64);
        assert_eq!(e["context_length"], 262144);
        assert_eq!(e["architecture"]["modality"], "text->text");
        assert_eq!(e["architecture"]["tokenizer"], "qwen2");
        assert_eq!(e["architecture"]["instruct_type"], "chatml");
        // pricing stub: OR-convention USD strings, self-hosted zeros.
        assert_eq!(e["pricing"]["prompt"], "0");
        assert_eq!(e["pricing"]["completion"], "0");
        assert_eq!(e["top_provider"]["context_length"], 262144);
        // no static completion cap (context-bounded, gap-scan F2) -> honest null.
        assert!(e["top_provider"]["max_completion_tokens"].is_null());

        // UNKNOWN metadata (no caps / empty fields) -> honest nulls, never invented.
        let e = model_entry_v1("m", None, 7);
        assert!(e["context_length"].is_null());
        assert!(e["architecture"]["tokenizer"].is_null());
        assert!(e["architecture"]["instruct_type"].is_null());
        assert!(e["top_provider"]["context_length"].is_null());
        let bare = ModelCaps::default(); // caps present, fields unknown (0/""/None)
        let e = model_entry_v1("m", Some(&bare), 7);
        assert!(e["context_length"].is_null());
        assert!(e["architecture"]["tokenizer"].is_null());
        assert!(e["architecture"]["instruct_type"].is_null());
    }

    #[test]
    fn models_openai_default_body_stays_byte_identical() {
        let body = models_openai_body(&["main".into(), "judge".into()]);
        let bytes = serde_json::to_vec(&body).unwrap();
        assert_eq!(
            bytes,
            br#"{"object":"list","data":[{"id":"main","object":"model"},{"id":"judge","object":"model"}]}"#
        );
    }

    #[test]
    fn openrouter_models_entry_serializes_complete_metadata() {
        let metadata = OpenRouterMetadataFile::from_toml(
            r#"
[models.main]
hugging_face_id = "Qwen/Qwen3.6-27B"
created = 1786032000
quantization = "nvfp4"
description = "Qwen3.6 27B served by memra."
max_prompt_length = 245760
max_output_length = 16384
is_ready = true
is_free = false
discount_to_user = 0.1
openrouter_slug = "qwen/qwen3.6-27b"
datacenters = [{ country_code = "US", region = "us-east-1" }]
zdr = true
hipaa = false

[models.main.pricing]
prompt = "0.000000234"
cached_prompt = "0.0000000585"
cache_write = "0.000000234"
completion = "0.000001872"
internal_reasoning = "0.000001872"
request = "0.01"

[models.main.capacity]
prompt_tpm = 1000000
cached_prompt_tpm = 2000000
completion_tpm = 500000
request_rpm = 1000
concurrency = 64
"#,
        )
        .unwrap();
        let caps = ModelCaps {
            tools_branch: true,
            qwen_think: true,
            think_switch: true,
            chat_ok: true,
            context_length: 262144,
            tokenizer: "qwen2".into(),
            instruct_type: Some("chatml".into()),
            ..Default::default()
        };
        let entry = model_entry_openrouter("main", Some(&caps), metadata.get("main"));

        assert_eq!(entry["schema_version"], "2.4");
        assert_eq!(entry["id"], "main");
        assert_eq!(entry["name"], "main");
        assert_eq!(entry["hugging_face_id"], "Qwen/Qwen3.6-27B");
        assert_eq!(entry["created"], 1786032000u64);
        assert_eq!(entry["quantization"], "nvfp4");
        assert_eq!(entry["tokenizer"], "qwen2");
        assert_eq!(entry["description"], "Qwen3.6 27B served by memra.");
        assert!(
            entry.get("object").is_none(),
            "OpenRouter schema 2.4 rejects unknown OpenAI fields"
        );

        let input = &entry["input_modalities"][0];
        assert_eq!(input["type"], "text");
        assert_eq!(
            input["supported_inputs"]["max_context_length"]["value"],
            262144
        );
        assert_eq!(
            input["supported_inputs"]["max_prompt_length"]["value"],
            245760
        );
        let input_prices = input["pricing"].as_array().unwrap();
        let input_price = |kind: &str| {
            input_prices
                .iter()
                .find(|price| price["type"] == kind)
                .unwrap()
        };
        assert_eq!(input_price("prompt")["cost_usd"], "0.000000234");
        assert_eq!(
            input_price("cached_prompt")["cost_usd"],
            "0.0000000585"
        );
        assert_eq!(input_price("cache_write")["cost_usd"], "0.000000234");
        assert_eq!(input["capacity"][0]["value"], 1000000);
        assert_eq!(input["capacity"][1]["value"], 2000000);

        let output = &entry["output_modalities"][0];
        assert_eq!(output["type"], "text");
        assert_eq!(output["max_length"]["value"], 16384);
        assert_eq!(output["streaming"], true);
        assert_eq!(output["supported_parameters"]["tools"]["type"], "boolean");
        assert_eq!(
            output["supported_parameters"]["structured_outputs"]["type"],
            "boolean"
        );
        assert_eq!(
            output["supported_parameters"]["reasoning"]["type"],
            "boolean"
        );
        assert_eq!(output["pricing"][0]["type"], "completion");
        assert_eq!(output["pricing"][0]["cost_usd"], "0.000001872");
        assert_eq!(output["pricing"][1]["type"], "internal_reasoning");
        assert_eq!(output["capacity"][0]["value"], 500000);
        assert_eq!(output["capacity"][1]["type"], "concurrency");
        assert_eq!(output["capacity"][1]["value"], 64);

        assert_eq!(entry["pricing"][0]["type"], "request");
        assert_eq!(entry["pricing"][0]["cost_usd"], "0.01");
        assert_eq!(entry["capacity"][0]["value"], 1000);
        assert_eq!(entry["is_ready"], true);
        assert_eq!(entry["is_free"], false);
        assert_eq!(entry["discount_to_user"], 0.1);
        assert_eq!(entry["openrouter"]["slug"], "qwen/qwen3.6-27b");
        assert_eq!(entry["datacenters"][0]["country_code"], "US");
        assert_eq!(entry["compliance"]["zdr"], true);
        assert_eq!(entry["compliance"]["hipaa"], false);
    }

    #[test]
    fn openrouter_models_entry_omits_undeclared_optional_fields() {
        let entry = model_entry_openrouter("minimal", None, None);
        let object = entry.as_object().unwrap();
        for field in [
            "hugging_face_id",
            "created",
            "quantization",
            "tokenizer",
            "description",
            "pricing",
            "capacity",
            "is_ready",
            "is_free",
            "discount_to_user",
            "openrouter",
            "datacenters",
            "compliance",
        ] {
            assert!(
                !object.contains_key(field),
                "optional field {field} must be absent, not null"
            );
        }
        assert_eq!(entry["schema_version"], "2.4");
        assert_eq!(entry["input_modalities"][0]["type"], "text");
        assert!(
            entry["input_modalities"][0]
                .get("supported_inputs")
                .is_none()
        );
        assert!(entry["input_modalities"][0].get("pricing").is_none());
        assert!(entry["input_modalities"][0].get("capacity").is_none());
        assert_eq!(entry["output_modalities"][0]["type"], "text");
        assert_eq!(entry["output_modalities"][0]["streaming"], true);
        assert!(
            entry["output_modalities"][0]["supported_parameters"]
                .is_object()
        );
        assert!(entry["output_modalities"][0].get("max_length").is_none());
        assert!(entry["output_modalities"][0].get("pricing").is_none());
        assert!(entry["output_modalities"][0].get("capacity").is_none());
    }

    #[tokio::test]
    async fn blocking_response_excludes_stop_text_across_token_events() {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        tx.send(Event::Token { id: 1, text: "answer\nPro".into() }).unwrap();
        tx.send(Event::Token { id: 2, text: "blem: leaked prompt".into() }).unwrap();
        tx.send(Event::Done {
            stop_reason: "Callback".into(), n_tokens: 2, n_prompt: 8, n_cached: 0, elapsed_s: 0.5,
            spec: None,
        }).unwrap();
        drop(tx);
        let response = blocking_response(
            rx, "plain_quant".into(), false, vec!["Problem:".into()], None, Envelope::new(false)
        ).await;
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(payload["text"], "answer\n");
        assert_eq!(payload["stop_reason"], "Callback");
    }
}