dynamo-llm 1.5.0

Dynamo LLM Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! The Preprocessor consists of the following modules
//!
//! - `translation`: This module converts the allowed Ingress message types to the corresponding
//!   internal representation.
//! - `apply`: This module applies ModelConfig defaults to any empty optional fields specified
//! - `prompt`: This module applies any prompt template logic to the internal Request object.
//! - `tokenize`: This module tokenizes the formatted prompt string and returns the token ids.
//!
//! The Preprocessor will accept any IngressRequest and transform it to a BackendRequest.

#[cfg(feature = "mm-routing")]
pub mod lightseek_mm;
pub mod media;
#[cfg(all(feature = "mm-routing", any(feature = "media-ffmpeg", test)))]
mod mm_routing;
pub mod prompt;
pub mod speculative_prefill;
pub(crate) mod structural_tag;
pub(crate) mod tool_choice;
pub mod tools;
use anyhow::Context;
use anyhow::{Result, bail};

use dynamo_protocols::types::{
    ChatCompletionMessageContent, ChatCompletionRequestMessage,
    ChatCompletionRequestToolMessageContent, ChatCompletionRequestToolMessageContentPart,
    ChatCompletionRequestUserMessageContent, ChatCompletionRequestUserMessageContentPart,
    ChatCompletionToolChoiceOption, EncodingFormat,
};
use dynamo_renderer::{OAIPromptFormatter, PromptRenderError, RenderedPrompt};
use dynamo_runtime::config::{
    env_is_falsey, environment_names::llm as env_llm, is_truthy, parse_bool_opt,
};
use dynamo_runtime::error::{DynamoError, ErrorType};
use either::Either;
use futures::Stream;
use futures::stream::{self, StreamExt};
use std::borrow::Cow;
use std::time::Instant;

use dynamo_runtime::dynamo_nvtx_range;
use dynamo_runtime::metrics::frontend_perf::{
    DETOKENIZE_TOKEN_COUNT, DETOKENIZE_TOTAL_US, STAGE_DURATION_SECONDS, STAGE_PREPROCESS,
    StageGuard, TEMPLATE_SECONDS, TOKENIZE_SECONDS,
};
use std::{
    any::Any,
    collections::{HashMap, HashSet},
    pin::Pin,
    sync::{Arc, Mutex, OnceLock},
};
use tracing;

#[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
use crate::local_model::runtime_config::VLLM_QWEN_VIDEO_PROCESSOR_CONTRACT_RUNTIME_KEY;
use crate::local_model::runtime_config::{TOKEN_BUDGET_RUNTIME_KEY, TokenBudget};
#[cfg(feature = "mm-routing")]
use crate::model_card::ModelInfoType;
use crate::model_card::{ModelDeploymentCard, ModelInfo, PromptFormatterArtifact};
#[cfg(feature = "mm-routing")]
use crate::preprocessor::media::MediaFetcher;
use crate::preprocessor::media::{MediaDecoder, MediaLoader};
use crate::protocols::common::preprocessor::{
    MultimodalData, MultimodalDataMap, MultimodalUuidMap, PreprocessedRequestBuilder, RoutingHints,
};
use crate::protocols::common::timing::RequestTracker;
use crate::tokenizers::Encoding;

use dynamo_parsers::{
    ReasoningParser, ReasoningParserType, reasoning::ParserResult,
    tool_calling::parsers::get_tool_parser_map,
};
use dynamo_runtime::engine::{AsyncEngine, AsyncEngineContextProvider, ResponseStream};
use dynamo_runtime::pipeline::{
    AsyncEngineContext, Context as PipelineContext, Error, ManyOut, Operator, SingleIn, async_trait,
};
use dynamo_runtime::protocols::annotated::{Annotated, AnnotationsProvider};

use crate::protocols::{
    TokenIdType,
    common::{
        OutputOptionsProvider, SamplingOptionsProvider, StopConditionsProvider,
        extensions::{
            AgentHints, NvExtProvider, merge_response_nvext, request_cache_salt,
            routing_constraints_to_kv,
        },
    },
    openai::{
        DeltaGeneratorExt,
        chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
            scrub_synthetic_chunk_metadata,
        },
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
        embeddings::{NvCreateEmbeddingRequest, NvCreateEmbeddingResponse},
    },
};
use crate::tokenizers::traits::Tokenizer;

use crate::preprocessor::prompt::{
    MediaRequestExt, apply_continue_final_message, prompt_formatter_from_mdc,
};
use crate::protocols::openai::common_ext::CommonExtProvider;
use dynamo_renderer::{OAIChatLikeRequest, PromptFormatter, PromptInput, TextInput, TokenInput};

pub use crate::protocols::common::llm_backend::{BackendOutput, PreprocessedRequest};
pub use crate::protocols::common::metrics::{
    ANNOTATION_LLM_METRICS, ANNOTATION_PAYLOAD_USAGE, LLMMetricAnnotation,
};
pub use crate::protocols::common::preprocessor::PreprocessedEmbeddingRequest;

use crate::protocols::common::llm_backend::EmbeddingsEngineOutput;

fn routing_priorities(hints: Option<&AgentHints>) -> (Option<f64>, Option<u32>, Option<i32>) {
    let priority_jump = hints.and_then(|h| {
        h.priority
            .map(|priority| priority.max(0) as f64)
            .or(h.latency_sensitivity)
    });
    let strict_priority = hints.and_then(|h| h.strict_priority);
    let priority = hints.and_then(|h| h.priority);
    (priority_jump, strict_priority, priority)
}

fn invalid_argument_error(message: impl Into<String>) -> anyhow::Error {
    DynamoError::builder()
        .error_type(ErrorType::InvalidArgument)
        .message(message.into())
        .build()
        .into()
}

// Preserves terminal versus recoverable failures when moka shares a
// dimension fetch among concurrent callers.
#[cfg(feature = "mm-routing")]
enum ImageDimFetchFailure {
    InvalidArgument(String),
    Recoverable(String),
}

#[cfg(feature = "mm-routing")]
impl ImageDimFetchFailure {
    fn from_error(error: anyhow::Error) -> Self {
        if MediaFetcher::is_policy_rejection(&error) {
            Self::InvalidArgument(error.to_string())
        } else {
            Self::Recoverable(error.to_string())
        }
    }

    fn to_error(&self) -> anyhow::Error {
        match self {
            Self::InvalidArgument(message) => invalid_argument_error(message.clone()),
            Self::Recoverable(message) => anyhow::anyhow!("fetch_image_dims failed: {message}"),
        }
    }
}

fn validate_legacy_jail_nvext_choice_count(
    n: u8,
    extra_fields: Option<&[String]>,
    is_legacy_jail: bool,
) -> Result<()> {
    if n <= 1 || !is_legacy_jail {
        return Ok(());
    }

    const CHOICE_SPECIFIC_FIELDS: [&str; 3] = ["engine_data", "routed_experts", "stop_reason"];
    if let Some(field) = extra_fields.and_then(|fields| {
        fields
            .iter()
            .find(|field| CHOICE_SPECIFIC_FIELDS.contains(&field.as_str()))
    }) {
        return Err(invalid_argument_error(format!(
            "legacy tool-call parsing requires n = 1 when nvext.extra_fields requests choice-specific field `{field}`"
        )));
    }

    Ok(())
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum ToolProcessingRoute {
    MuseUnified(String),
    QwenUnified(&'static str),
    ParserV2(String),
    LegacyJail(Option<String>),
    PassThrough,
}

impl ToolProcessingRoute {
    fn uses_legacy_jail(&self) -> bool {
        matches!(self, Self::LegacyJail(_))
    }
}

fn tool_content_part_as_user(
    part: &ChatCompletionRequestToolMessageContentPart,
) -> Cow<'_, ChatCompletionRequestUserMessageContentPart> {
    Cow::Owned(match part {
        ChatCompletionRequestToolMessageContentPart::Text(part) => {
            ChatCompletionRequestUserMessageContentPart::Text(part.clone())
        }
        ChatCompletionRequestToolMessageContentPart::ImageUrl(part) => {
            ChatCompletionRequestUserMessageContentPart::ImageUrl(part.clone())
        }
        ChatCompletionRequestToolMessageContentPart::VideoUrl(part) => {
            ChatCompletionRequestUserMessageContentPart::VideoUrl(part.clone())
        }
        ChatCompletionRequestToolMessageContentPart::AudioUrl(part) => {
            ChatCompletionRequestUserMessageContentPart::AudioUrl(part.clone())
        }
    })
}

enum MultimodalContentPart<'a> {
    User(&'a ChatCompletionRequestUserMessageContentPart),
    Tool(&'a ChatCompletionRequestToolMessageContentPart),
}

impl<'a> MultimodalContentPart<'a> {
    fn as_user(&self) -> Cow<'a, ChatCompletionRequestUserMessageContentPart> {
        match self {
            Self::User(part) => Cow::Borrowed(part),
            Self::Tool(part) => tool_content_part_as_user(part),
        }
    }

    fn media_info(&self) -> Option<(&'static str, Option<url::Url>, Option<String>)> {
        match self {
            Self::User(part) => match *part {
                ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => Some((
                    "image_url",
                    part.image_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                ChatCompletionRequestUserMessageContentPart::VideoUrl(part) => Some((
                    "video_url",
                    part.video_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                ChatCompletionRequestUserMessageContentPart::AudioUrl(part) => Some((
                    "audio_url",
                    part.audio_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                _ => None,
            },
            Self::Tool(part) => match *part {
                ChatCompletionRequestToolMessageContentPart::ImageUrl(part) => Some((
                    "image_url",
                    part.image_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                ChatCompletionRequestToolMessageContentPart::VideoUrl(part) => Some((
                    "video_url",
                    part.video_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                ChatCompletionRequestToolMessageContentPart::AudioUrl(part) => Some((
                    "audio_url",
                    part.audio_url.as_ref().map(|media| media.url.clone()),
                    part.uuid.clone(),
                )),
                _ => None,
            },
        }
    }
}

fn multimodal_content_parts(
    message: &ChatCompletionRequestMessage,
) -> Option<impl Iterator<Item = MultimodalContentPart<'_>>> {
    match message {
        ChatCompletionRequestMessage::User(user) => match &user.content {
            ChatCompletionRequestUserMessageContent::Array(parts) => {
                Some(Either::Left(parts.iter().map(MultimodalContentPart::User)))
            }
            ChatCompletionRequestUserMessageContent::Text(_) => None,
        },
        ChatCompletionRequestMessage::Tool(tool) => match &tool.content {
            ChatCompletionRequestToolMessageContent::Array(parts) => {
                Some(Either::Right(parts.iter().map(MultimodalContentPart::Tool)))
            }
            ChatCompletionRequestToolMessageContent::Text(_) => None,
        },
        _ => None,
    }
}

#[cfg(feature = "mm-routing")]
fn image_content_part_url(
    content_part: &ChatCompletionRequestUserMessageContentPart,
) -> Option<&str> {
    let ChatCompletionRequestUserMessageContentPart::ImageUrl(part) = content_part else {
        return None;
    };
    part.image_url.as_ref().map(|image| image.url.as_str())
}

/// Decode a base64-encoded little-endian f32 byte string back into a float
/// vector. The byte length must be a multiple of 4; trailing bytes are
/// rejected. Shared by the tokens-path postprocessor and the HTTP embedding
/// handler, which converts leftover Base64 payloads to Float when requested.
pub(crate) fn decode_base64_to_floats(encoded: &str) -> Result<Vec<f32>, String> {
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    let bytes = STANDARD
        .decode(encoded)
        .map_err(|error| error.to_string())?;
    if bytes.len() % std::mem::size_of::<f32>() != 0 {
        return Err(format!(
            "base64-decoded embedding byte length {} is not a multiple of 4",
            bytes.len()
        ));
    }
    Ok(bytes
        .chunks_exact(std::mem::size_of::<f32>())
        .map(|chunk| f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
        .collect())
}

#[cfg(test)]
mod embedding_base64_transport_tests {
    use super::{OpenAIPreprocessor, decode_base64_to_floats};
    use crate::protocols::common::llm_backend::EmbeddingsEngineOutput;
    use crate::protocols::openai::embeddings::NvCreateEmbeddingRequest;
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use dynamo_runtime::protocols::annotated::Annotated;
    use futures::StreamExt;
    use futures::stream;

    #[test]
    fn portable_embedding_bytes_decode() {
        let expected = vec![0.0, 1.0, -1.0, 2.5, -42.5, 3.25, f32::MIN, f32::MAX];
        let bytes = expected
            .iter()
            .flat_map(|value: &f32| value.to_le_bytes())
            .collect::<Vec<_>>();
        let encoded = STANDARD.encode(bytes);
        assert_eq!(decode_base64_to_floats(&encoded).unwrap(), expected);
    }

    #[test]
    fn portable_embedding_bytes_reject_invalid_base64() {
        assert!(decode_base64_to_floats("not!valid!base64").is_err());
    }

    #[test]
    fn portable_embedding_bytes_reject_partial_float() {
        let encoded = STANDARD.encode([0_u8; 5]);
        let error = decode_base64_to_floats(&encoded).unwrap_err();
        assert!(error.contains("not a multiple of 4"));
    }

    #[test]
    fn empty_embeddings_engine_output_surfaces_as_error() {
        let request: NvCreateEmbeddingRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "input": "hello"
        }))
        .unwrap();
        let output = Annotated::from_data(EmbeddingsEngineOutput {
            embeddings: vec![],
            prompt_tokens: 0,
            total_tokens: 0,
        });
        let items = futures::executor::block_on(
            OpenAIPreprocessor::transform_embedding_postprocessor_stream(
                stream::iter(vec![output]),
                request,
            )
            .collect::<Vec<_>>(),
        );
        assert_eq!(items.len(), 1);
        let item = items.into_iter().next().unwrap();
        assert!(item.is_error(), "empty embeddings must be a stream error");
        let err = item.into_result().unwrap_err();
        assert!(
            err.to_string().contains("empty `embeddings` field"),
            "error should name the empty embeddings field, got: {err}"
        );
    }
}

pub const ANNOTATION_FORMATTED_PROMPT: &str = "formatted_prompt";
pub const ANNOTATION_TOKEN_IDS: &str = "token_ids";
const DEFAULT_THINKING_MODE_RUNTIME_KEY: &str = "default_thinking_mode";

/// Drain a standalone router's forwarded `routing_data` onto this request's tracker so the
/// frontend's timing/worker/token surfaces populate, then drop the field to keep it off the
/// client wire. Worker attribution is drained so `build_response_nvext` can surface it on the
/// split-router query-only (`query_instance_id`) path; it is first-write-wins, so the
/// frontend's own recordings (when present) take precedence over the forwarded values.
fn drain_router_routing_data(
    data: &mut Option<BackendOutput>,
    tracker: Option<&crate::protocols::common::timing::RequestTracker>,
) {
    let Some(routing_data) = data.as_mut().and_then(|d| d.routing_data.take()) else {
        return;
    };
    let Some(tracker) = tracker else {
        return;
    };
    if let Some(timing) = routing_data.timing {
        tracker.set_external_timing(timing);
    }
    if let Some(worker_id) = routing_data.worker_id {
        tracker.set_external_worker_info(worker_id);
    }
    if let Some(token_ids) = routing_data.token_ids {
        tracker.set_external_query_token_ids(token_ids);
    }
}

fn attach_metrics_annotation<Resp>(response: &mut Annotated<Resp>, metrics: &LLMMetricAnnotation) {
    if let Ok(metrics_annotated) = metrics.to_annotation::<()>() {
        response.event = metrics_annotated.event;
        response.comment = metrics_annotated.comment;
    } else {
        tracing::warn!("Failed to serialize LLM metrics annotation");
    }
}

fn attach_llm_metrics<Resp>(response: &mut Annotated<Resp>, metrics: LLMMetricAnnotation)
where
    Resp: 'static,
{
    if response.event.is_some() {
        return;
    }

    if let Some(data) = response.data.as_mut()
        && let Some(chat_response) =
            (data as &mut dyn Any).downcast_mut::<NvCreateChatCompletionStreamResponse>()
    {
        chat_response.llm_metrics = Some(metrics);
        return;
    }

    attach_metrics_annotation(response, &metrics);
}

#[inline]
fn build_llm_metric_annotation(
    tracker: Option<&RequestTracker>,
    input_tokens: usize,
    output_tokens: usize,
    chunk_tokens: usize,
    cached_tokens: Option<usize>,
    mm_counts: MultimodalCounts,
    image_tokens: Option<usize>,
) -> LLMMetricAnnotation {
    LLMMetricAnnotation {
        input_tokens,
        output_tokens,
        chunk_tokens,
        cached_tokens,
        image_count: mm_counts.image,
        video_count: mm_counts.video,
        audio_count: mm_counts.audio,
        image_tokens,
        prefill_worker_id: tracker.and_then(|t| t.prefill_worker_id()),
        prefill_dp_rank: tracker.and_then(|t| t.prefill_dp_rank()),
        prefill_worker_type: tracker
            .and_then(|t| t.prefill_worker_type())
            .map(String::from),
        decode_worker_id: tracker.and_then(|t| t.decode_worker_id()),
        decode_dp_rank: tracker.and_then(|t| t.decode_dp_rank()),
        decode_worker_type: tracker
            .and_then(|t| t.decode_worker_type())
            .map(String::from),
        tokenize_latency: tracker.and_then(|t| t.tokenize_latency()),
        detokenize_total_latency: tracker.and_then(|t| t.detokenize_total_latency()),
        detokenize_count: tracker.map(|t| t.detokenize_count()),
    }
}

// Reasoning State for reasoning parsing transformation step.
//
// The reasoning parser and the guided-JSON bypass decision are kept per
// `choice.index` so that with `n > 1` one choice's bare-JSON bypass cannot
// suppress another choice's reasoning split. This mirrors the per-choice state
// already used by the tool-call jail and the leading-`<think>` strip stage.
struct ChoiceReasoningState {
    parser: Box<dyn ReasoningParser>,
    guided_json_bypass_decision: Option<bool>,
    // Reasoning text held back while it is still ambiguous. Only used on the
    // `defer_reasoning_for_nonempty_content` path — see the buffering note on
    // `ReasoningState`.
    pending_reasoning: String,
    // Whitespace-only normal text seen while still ambiguous. Held rather than
    // emitted so the streaming path agrees with the aggregator, which counts
    // whitespace-only content as empty.
    pending_content: String,
    // Set once this choice's parser has produced normal text, which for these
    // force-reasoning parsers means it left the reasoning block. From then on
    // the ambiguity is gone and deltas pass straight through.
    left_reasoning: bool,
    // Set once this choice has been drained, so the terminal-chunk drain and the
    // end-of-stream fallback cannot both emit the same bytes. Reopened if the
    // backend keeps sending content after `finish_reason`, so those bytes still
    // get a destination.
    drained: bool,
    // Set the first time this choice's parser is finalized and NEVER reset, even
    // when `drained` is reopened. `ReasoningParser::finish_reasoning_stream` is
    // not documented to be idempotent, so calling it twice could re-emit text a
    // parser had already handed over. Draining again is fine; finalizing again
    // is not.
    parser_finished: bool,
}

/// Estimates reasoning-token usage from the parser-classified Chat Completion stream.
///
/// This is intentionally chunk-granular: if one decoded chunk contains both reasoning
/// and visible content, every token in that chunk is counted as reasoning. The estimate
/// therefore overcounts visible-content tokens in mixed chunks. A positive count supplied
/// by the backend remains authoritative.
#[derive(Debug, Default)]
struct ReasoningUsageEstimator {
    total: u32,
    active_choices: HashSet<u32>,
}

impl ReasoningUsageEstimator {
    fn observe(&mut self, chunk: &NvCreateChatCompletionStreamResponse) {
        let token_count = chunk
            .llm_metrics
            .as_ref()
            .map_or(0, |metrics| metrics.chunk_tokens)
            .try_into()
            .unwrap_or(u32::MAX);

        let has_reasoning = chunk
            .inner
            .choices
            .iter()
            .any(|choice| choice.delta.reasoning_content.is_some());
        let active_without_visible_output = chunk.inner.choices.iter().any(|choice| {
            self.active_choices.contains(&choice.index) && !choice_has_visible_output(choice)
        });
        let usage_chunk_while_reasoning =
            chunk.inner.choices.is_empty() && !self.active_choices.is_empty();

        if token_count > 0
            && (has_reasoning || active_without_visible_output || usage_chunk_while_reasoning)
        {
            self.total = self.total.saturating_add(token_count);
        }

        for choice in &chunk.inner.choices {
            if choice.delta.reasoning_content.is_some() {
                self.active_choices.insert(choice.index);
            } else if choice_has_visible_output(choice) {
                self.active_choices.remove(&choice.index);
            }
        }
    }

    fn annotate(&self, usage: &mut dynamo_protocols::types::CompletionUsage) {
        let details = usage.completion_tokens_details.get_or_insert_default();
        if details.reasoning_tokens.unwrap_or(0) == 0 {
            details.reasoning_tokens = Some(self.total);
        }
    }
}

fn choice_has_visible_output(choice: &dynamo_protocols::types::ChatChoiceStream) -> bool {
    choice.delta.content.is_some()
        || choice
            .delta
            .tool_calls
            .as_ref()
            .is_some_and(|calls| !calls.is_empty())
}

fn annotate_reasoning_usage<S>(
    stream: S,
) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
where
    S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
{
    let mut estimator = ReasoningUsageEstimator::default();
    stream.map(move |mut response| {
        if let Some(chunk) = response.data.as_mut() {
            estimator.observe(chunk);
            if let Some(usage) = chunk.inner.usage.as_mut() {
                estimator.annotate(usage);
            }
        }
        response
    })
}

/// Drain what a choice still holds on the `defer_reasoning_for_nonempty_content`
/// path, returning `(content, reasoning_content)` to add to its delta. Shared by
/// the terminal-chunk drain and the end-of-stream fallback so the two cannot
/// disagree about which channel the leftover bytes belong to.
fn drain_deferred_reasoning(state: &mut ChoiceReasoningState) -> (Option<String>, Option<String>) {
    if state.drained {
        return (None, None);
    }
    state.drained = true;
    let pending = std::mem::take(&mut state.pending_reasoning);
    let pending_content = std::mem::take(&mut state.pending_content);
    // Finalize at most once per choice; see `parser_finished`.
    let result = if state.parser_finished {
        ParserResult::default()
    } else {
        state.parser_finished = true;
        state.parser.finish_reasoning_stream()
    };

    if state.left_reasoning {
        // An answer already streamed as content, so the non-empty-content
        // promise is met and the parser's own split stands: a later truncated
        // reasoning block stays reasoning instead of being appended to the
        // answer. `pending_content` is empty here — it was released with the
        // answer when the choice left reasoning.
        let mut content = pending_content;
        content.push_str(&result.normal_text);
        (
            (!content.is_empty()).then_some(content),
            (!result.reasoning_text.is_empty()).then_some(result.reasoning_text),
        )
    } else {
        // No real answer ever arrived, so everything held is all the response
        // has and must land in content — including a truncated `<think>` prefix,
        // which the parser reports as reasoning or normal text depending on
        // where it stopped. Held whitespace is dropped rather than prepended when
        // there is reasoning to surface, matching the aggregator, which replaces
        // whitespace-only content with the reasoning text instead of
        // concatenating.
        let mut text = pending;
        text.push_str(&result.reasoning_text);
        text.push_str(&result.normal_text);
        if text.is_empty() {
            // ...but if whitespace is genuinely all the turn produced, it is the
            // whole response. Returning nothing here would hand back an empty
            // `content` to a request that explicitly asked for non-empty content.
            text = pending_content;
        }
        ((!text.is_empty()).then_some(text), None)
    }
}

struct ReasoningState {
    stream: Pin<Box<dyn Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send>>,
    parser_name: String,
    prompt_injected_reasoning: bool,
    bypass_bare_guided_json: bool,
    choices: HashMap<u32, ChoiceReasoningState>,
    // Last emitted content-bearing response, reused as the envelope to carry any
    // text the parsers are still buffering when the upstream stream ends. Only
    // retained when `defer_reasoning_for_nonempty_content` is set, to keep the
    // per-token clone off the common reasoning hot path. Chunks with no choices
    // (the trailing usage-only chunk) are never retained — that envelope has no
    // delta slot to attach the flushed bytes to, so the flush would be dropped.
    last_response: Option<Annotated<NvCreateChatCompletionStreamResponse>>,
    // Nemotron force-reasoning parsers start inside the reasoning block, so
    // leading model output with no `<think>` is reported as reasoning even when
    // it is really the whole answer. Under `force_nonempty_content=true` the
    // chat template promises non-empty `content`, so emitting that text as
    // `reasoning_content` would leave `content` empty — the exact failure the
    // flag exists to prevent.
    //
    // When this is set, reasoning deltas are held in each choice's
    // `pending_reasoning` until the ambiguity resolves:
    //   - the parser produces normal text (it left the reasoning block), so the
    //     buffer really was reasoning: emit it as `reasoning_content` and stream
    //     the answer as `content` from then on; or
    //   - the stream ends first, so no answer is coming: emit the buffer (plus
    //     anything `finish_reasoning_stream` still holds, e.g. a truncated
    //     `<think>` prefix) as `content`.
    //
    // The cost is real and worth stating plainly: everything held is delivered
    // in one delta rather than token by token. For a turn that does reason, that
    // is the `reasoning_content` up to `</think>`, after which the answer streams
    // normally. For a turn with no `</think>` at all the held text IS the answer,
    // so the whole answer lands in a single delta on the terminal chunk — on
    // `main` (parser off, leading `<think>` stripped) that case streamed
    // incrementally.
    //
    // There is no cheaper split available: these parsers emit reasoning with no
    // opening `<think>` (see the `nemotron_nano` mapping in dynamo-parsers), so
    // until `</think>` arrives the same bytes are equally consistent with
    // reasoning and with a plain answer. Emitting eagerly is what leaked reasoning
    // into `content` in the first place. Scoped to the flag so no other parser
    // pays it.
    defer_reasoning_for_nonempty_content: bool,
    // Set once the backend has sent an error annotation. The end-of-stream
    // flush must not run after that: an error is terminal, and emitting
    // recovered reasoning as ordinary `content` after it would put text on the
    // wire that the generation never successfully produced.
    //
    // This matters because the flush is the only place bytes can arrive after
    // the last upstream chunk. `/v1/chat/completions` ends its SSE on the error
    // and never sees it, but `/v1/responses` and `/v1/messages` both record the
    // error and keep consuming (`saw_error = true; continue;`), so without this
    // latch they emit the synthetic content chunk and only then report failure.
    saw_terminal_error: bool,
}

#[derive(Default)]
struct DeferredUnifiedChoice {
    pending_reasoning: String,
    pending_content: String,
    saw_visible_output: bool,
    drained: bool,
}

impl DeferredUnifiedChoice {
    fn release_split(&mut self) -> (Option<String>, Option<String>) {
        let content = std::mem::take(&mut self.pending_content);
        let reasoning = std::mem::take(&mut self.pending_reasoning);
        (
            (!content.is_empty()).then_some(content),
            (!reasoning.is_empty()).then_some(reasoning),
        )
    }

    fn drain(&mut self) -> (Option<String>, Option<String>) {
        if self.drained {
            return (None, None);
        }
        self.drained = true;
        if self.saw_visible_output {
            return self.release_split();
        }
        let reasoning = std::mem::take(&mut self.pending_reasoning);
        let content = std::mem::take(&mut self.pending_content);
        if !reasoning.trim().is_empty() {
            (Some(reasoning), None)
        } else {
            ((!content.is_empty()).then_some(content), None)
        }
    }
}

/// Per-image routing payload accumulated by `gather_multi_modal_data` and
/// consumed by `gather_mm_exact_routing_info`.
#[derive(Debug, Clone, Copy)]
pub struct MmImageEntry {
    pub mm_hash: u64,
    pub width: u32,
    pub height: u32,
}

/// One replacement tracked in both the worker-visible and canonical routing
/// token spaces. vLLM includes MM metadata on every block intersecting a
/// feature span, including timestamp/delimiter-only boundary blocks. Those
/// blocks need the worker token form plus `block_mm_infos`; blocks with an
/// exact placeholder/object mapping use the canonical pad-value form.
#[cfg(feature = "mm-routing")]
#[derive(Debug, Clone, PartialEq, Eq)]
struct TrackedMmRoutingReplacement {
    mm_hash: u64,
    target_tokens: Vec<TokenIdType>,
    worker_tokens: Vec<TokenIdType>,
    routing_tokens: Vec<TokenIdType>,
}

/// Modality-aware routing payload accumulated in original message order.
#[cfg_attr(
    not(feature = "mm-routing"),
    allow(
        dead_code,
        reason = "the default build keeps the shared media-gathering return type but emits no routing entries"
    )
)]
#[derive(Debug, Clone)]
enum MmRoutingEntry {
    Image {
        mm_hash: u64,
        width: u32,
        height: u32,
    },
    #[cfg_attr(
        not(feature = "media-ffmpeg"),
        allow(dead_code, reason = "video entries require the FFmpeg media decoder")
    )]
    Video {
        mm_hash: u64,
        placeholder_token_id: TokenIdType,
        target_tokens: Vec<TokenIdType>,
        replacement_tokens: Vec<TokenIdType>,
    },
}

#[cfg(feature = "mm-routing")]
impl MmRoutingEntry {
    fn mm_hash(&self) -> u64 {
        match self {
            Self::Image { mm_hash, .. } | Self::Video { mm_hash, .. } => *mm_hash,
        }
    }
}

#[cfg(feature = "mm-routing")]
fn exact_mm_routing_entries_are_unambiguous(entries: &[MmRoutingEntry]) -> bool {
    !entries.windows(2).any(|pair| {
        matches!(
            pair,
            [MmRoutingEntry::Video { .. }, MmRoutingEntry::Video { .. }]
        )
    })
}

#[cfg(feature = "mm-routing")]
fn routing_bos_to_prepend(
    configured_bos: Option<TokenIdType>,
    has_image_entry: bool,
) -> Option<TokenIdType> {
    has_image_entry.then_some(configured_bos).flatten()
}
#[cfg(feature = "mm-routing")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RoutingImagePromptLayout {
    RepeatedPad,
    KimiK3 {
        media_begin: TokenIdType,
        media_content: TokenIdType,
        media_end: TokenIdType,
    },
}

#[cfg(feature = "mm-routing")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum RoutingImageDimensionPolicy {
    Encoded,
    ExifTransposed,
}

#[cfg(feature = "mm-routing")]
fn routing_image_dimension_policy(
    runtime_config: &crate::local_model::runtime_config::ModelRuntimeConfig,
    frontend_decoding: bool,
    prompt_layout: Option<RoutingImagePromptLayout>,
) -> RoutingImageDimensionPolicy {
    use crate::local_model::runtime_config::VLLM_INFERENCE_V1_GENERATE_CAPABILITY;

    let is_vllm = runtime_config
        .get_engine_specific::<bool>(VLLM_INFERENCE_V1_GENERATE_CAPABILITY)
        .ok()
        .flatten()
        .unwrap_or(false);
    if is_vllm
        && !frontend_decoding
        && matches!(prompt_layout, Some(RoutingImagePromptLayout::KimiK3 { .. }))
    {
        RoutingImageDimensionPolicy::ExifTransposed
    } else {
        RoutingImageDimensionPolicy::Encoded
    }
}

#[cfg(feature = "mm-routing")]
fn encode_routing_segment(
    tokenizer: &dyn Tokenizer,
    text: &str,
    allow_special: bool,
) -> Result<Vec<TokenIdType>> {
    let segment = crate::tokenizers::EncodeSegment::new(text, allow_special);
    Ok(tokenizer.encode_segments(&[segment])?.token_ids().to_vec())
}

#[cfg(feature = "mm-routing")]
fn resolve_routing_image_prompt_layout(
    tokenizer: &dyn Tokenizer,
    kind: lightseek_mm::ImagePromptKind,
) -> Result<RoutingImagePromptLayout> {
    if kind == lightseek_mm::ImagePromptKind::RepeatedPad {
        return Ok(RoutingImagePromptLayout::RepeatedPad);
    }

    let resolve_control = |token: &str| -> Result<TokenIdType> {
        let ids = encode_routing_segment(tokenizer, token, true)?;
        if ids.len() != 1 {
            bail!(
                "Kimi-K3 routing control token {token:?} encoded to {} ids ({ids:?}); expected exactly one",
                ids.len()
            );
        }
        Ok(ids[0])
    };

    Ok(RoutingImagePromptLayout::KimiK3 {
        media_begin: resolve_control("<|media_begin|>")?,
        media_content: resolve_control("<|media_content|>")?,
        media_end: resolve_control("<|media_end|>")?,
    })
}

#[cfg(feature = "mm-routing")]
fn append_mm_routing_replacement(
    expanded: &mut Vec<TokenIdType>,
    tokenizer: &dyn Tokenizer,
    layout: RoutingImagePromptLayout,
    image: MmImageEntry,
    num_image_tokens: usize,
) -> Result<()> {
    let fill_token = dynamo_kv_router::protocols::pad_value_for_mm_hash(image.mm_hash);

    append_mm_routing_replacement_with_fill(
        expanded,
        tokenizer,
        layout,
        image,
        num_image_tokens,
        fill_token,
    )
}

#[cfg(feature = "mm-routing")]
fn append_mm_routing_replacement_with_fill(
    expanded: &mut Vec<TokenIdType>,
    tokenizer: &dyn Tokenizer,
    layout: RoutingImagePromptLayout,
    image: MmImageEntry,
    num_image_tokens: usize,
    fill_token: TokenIdType,
) -> Result<()> {
    match layout {
        RoutingImagePromptLayout::RepeatedPad => {
            expanded.extend(std::iter::repeat_n(fill_token, num_image_tokens));
        }
        RoutingImagePromptLayout::KimiK3 {
            media_begin,
            media_content,
            media_end,
        } => {
            expanded.push(media_begin);
            let dimensions = format!("image {}x{}", image.width, image.height);
            expanded.extend(encode_routing_segment(tokenizer, &dimensions, false)?);
            expanded.push(media_content);
            expanded.extend(std::iter::repeat_n(fill_token, num_image_tokens));
            expanded.push(media_end);
        }
    }
    Ok(())
}

/// Build the request-side hash representation that mirrors vLLM's event
/// normalizer block by block.
///
/// Most blocks use canonical pad-value tokens. If a feature-span boundary
/// does not contain an exact ordered placeholder/object mapping, vLLM keeps
/// the worker tokens and hashes the block's MM metadata instead. Reproducing
/// that fallback here keeps both sides identical without discarding the media
/// identity carried by an ambiguous boundary block.
#[cfg(feature = "mm-routing")]
fn apply_tracked_mm_replacements(
    routing_prepend_bos: Option<TokenIdType>,
    replacements: &[TrackedMmRoutingReplacement],
    token_ids: &[TokenIdType],
    block_size: usize,
    image_token_id: Option<TokenIdType>,
    video_token_id: Option<TokenIdType>,
) -> Result<(
    Vec<TokenIdType>,
    usize,
    Vec<Option<dynamo_kv_router::protocols::BlockExtraInfo>>,
)> {
    use dynamo_kv_router::protocols::{BlockExtraInfo, BlockMmObjectInfo};
    use dynamo_kv_router::zmq_wire::normalize_mm_placeholder_runs;

    anyhow::ensure!(block_size > 0, "MM routing block size must be positive");
    anyhow::ensure!(
        replacements.iter().all(|replacement| {
            !replacement.target_tokens.is_empty()
                && replacement.worker_tokens.len() == replacement.routing_tokens.len()
        }),
        "tracked MM routing replacements must have a non-empty target and equal token lengths"
    );

    let replacement_tokens = replacements.iter().try_fold(0usize, |total, replacement| {
        total
            .checked_add(replacement.routing_tokens.len())
            .context("MM routing replacement capacity overflow")
    })?;
    let capacity = token_ids
        .len()
        .checked_add(replacement_tokens)
        .and_then(|value| value.checked_add(routing_prepend_bos.is_some() as usize))
        .context("MM routing token capacity overflow")?;
    let mut worker_tokens = Vec::with_capacity(capacity);
    let mut routing_tokens = Vec::with_capacity(capacity);
    if let Some(bos) = routing_prepend_bos {
        worker_tokens.push(bos);
        routing_tokens.push(bos);
    }

    // Placeholder targets are model/modality contracts, so many media objects
    // normally share the same target. Deduplicate them once to keep the prompt
    // scan proportional to the number of modalities rather than media objects.
    let mut distinct_targets: Vec<&[TokenIdType]> = Vec::new();
    for replacement in replacements {
        let target = replacement.target_tokens.as_slice();
        if !distinct_targets.contains(&target) {
            distinct_targets.push(target);
        }
    }
    let target_matches_at = |target: &[TokenIdType], token_index: usize| {
        token_ids.get(token_index..token_index.saturating_add(target.len())) == Some(target)
    };

    let mut spans = Vec::with_capacity(replacements.len());
    let mut replacement_index = 0usize;
    let mut token_index = 0usize;
    while token_index < token_ids.len() {
        if let Some(replacement) = replacements.get(replacement_index)
            && target_matches_at(&replacement.target_tokens, token_index)
        {
            let start = worker_tokens.len();
            worker_tokens.extend_from_slice(&replacement.worker_tokens);
            routing_tokens.extend_from_slice(&replacement.routing_tokens);
            spans.push((start, worker_tokens.len(), replacement.mm_hash));
            token_index += replacement.target_tokens.len();
            replacement_index += 1;
            continue;
        }

        anyhow::ensure!(
            !distinct_targets
                .iter()
                .any(|target| target_matches_at(target, token_index)),
            "multimodal placeholders do not match request order"
        );
        worker_tokens.push(token_ids[token_index]);
        routing_tokens.push(token_ids[token_index]);
        token_index += 1;
    }

    anyhow::ensure!(
        replacement_index == replacements.len(),
        "tokenized prompt is missing multimodal placeholders"
    );
    let expanded_prompt_len = routing_tokens.len();
    let padded_len = expanded_prompt_len.div_ceil(block_size) * block_size;
    worker_tokens.resize(padded_len, 0);
    routing_tokens.resize(padded_len, 0);

    let mut block_mm_infos = vec![None; padded_len / block_size];
    for (block_index, block_start) in (0..padded_len).step_by(block_size).enumerate() {
        let block_end = block_start + block_size;
        let mm_hashes: Vec<u64> = spans
            .iter()
            .filter(|(start, end, _)| *start < block_end && *end > block_start)
            .map(|(_, _, mm_hash)| *mm_hash)
            .collect();
        if mm_hashes.is_empty() {
            continue;
        }

        let worker_block = &worker_tokens[block_start..block_end];
        let routing_block = &mut routing_tokens[block_start..block_end];
        match normalize_mm_placeholder_runs(
            worker_block,
            image_token_id,
            video_token_id,
            &mm_hashes,
        ) {
            Some((normalized, _)) => {
                anyhow::ensure!(
                    normalized == routing_block,
                    "frontend MM replacement differs from KV-event normalization"
                );
            }
            None => {
                routing_block.copy_from_slice(worker_block);
                block_mm_infos[block_index] = Some(BlockExtraInfo {
                    mm_objects: mm_hashes
                        .into_iter()
                        .map(|mm_hash| BlockMmObjectInfo {
                            mm_hash,
                            offsets: Vec::new(),
                        })
                        .collect(),
                });
            }
        }
    }

    Ok((routing_tokens, expanded_prompt_len, block_mm_infos))
}
/// Construct the unpadded routing sequence and return its exact logical
/// length. Errors are routing-only: callers must discard the partial vector
/// and fall back without failing the inference request.
#[cfg(feature = "mm-routing")]
fn expand_mm_routing_tokens(
    tokenizer: &dyn Tokenizer,
    prompt_layout: RoutingImagePromptLayout,
    routing_prepend_bos: Option<TokenIdType>,
    find_token_id: TokenIdType,
    mm_image_entries: &[MmImageEntry],
    n_tokens: &[usize],
    token_ids: &[TokenIdType],
) -> Result<(Vec<TokenIdType>, usize)> {
    debug_assert_eq!(mm_image_entries.len(), n_tokens.len());
    let n_total: usize = n_tokens.iter().sum();
    let bos_extra = routing_prepend_bos.is_some() as usize;
    let mut expanded = Vec::with_capacity(token_ids.len() + n_total + bos_extra);
    if let Some(bos) = routing_prepend_bos {
        expanded.push(bos);
    }

    let mut image_idx = 0usize;
    for &token_id in token_ids {
        if token_id == find_token_id && image_idx < mm_image_entries.len() {
            append_mm_routing_replacement(
                &mut expanded,
                tokenizer,
                prompt_layout,
                mm_image_entries[image_idx],
                n_tokens[image_idx],
            )?;
            image_idx += 1;
        } else {
            expanded.push(token_id);
        }
    }

    let expanded_prompt_len = expanded.len();
    Ok((expanded, expanded_prompt_len))
}

#[cfg(feature = "mm-routing")]
#[allow(clippy::too_many_arguments)]
fn try_expand_mm_routing_tokens(
    tokenizer: &dyn Tokenizer,
    prompt_layout: RoutingImagePromptLayout,
    routing_prepend_bos: Option<TokenIdType>,
    find_token_id: TokenIdType,
    mm_image_entries: &[MmImageEntry],
    n_tokens: &[usize],
    token_ids: &[TokenIdType],
    model_id: &str,
) -> Option<(Vec<TokenIdType>, usize)> {
    match expand_mm_routing_tokens(
        tokenizer,
        prompt_layout,
        routing_prepend_bos,
        find_token_id,
        mm_image_entries,
        n_tokens,
        token_ids,
    ) {
        Ok(expanded) => Some(expanded),
        Err(error) => {
            tracing::warn!(
                target: "mm_routing",
                model = model_id,
                %error,
                "routing-only image prompt expansion failed; skipping MM routing info"
            );
            None
        }
    }
}

struct MediaFetchTask<'a> {
    modality: &'static str,
    slot_idx: usize,
    content_part: Cow<'a, ChatCompletionRequestUserMessageContentPart>,
}

/// Per-request media content-part counts, carried to the metrics annotation.
/// Derived from `multi_modal_data`, so independent of the `mm-routing` feature.
#[derive(Debug, Clone, Copy, Default)]
pub struct MultimodalCounts {
    pub image: usize,
    pub video: usize,
    pub audio: usize,
}

impl MultimodalCounts {
    /// Count `image_url` / `video_url` / `audio_url` parts (vec length per modality).
    fn from_preprocessed(request: &PreprocessedRequest) -> Self {
        let count = |key: &str| {
            request
                .multi_modal_data
                .as_ref()
                .and_then(|m| m.get(key))
                .map_or(0, |v| v.len())
        };
        Self {
            image: count("image_url"),
            video: count("video_url"),
            audio: count("audio_url"),
        }
    }
}

#[cfg(feature = "mm-routing")]
fn checked_add_image_tokens(total: Option<usize>, next: usize) -> Option<usize> {
    total?.checked_add(next)
}

#[cfg(feature = "mm-routing")]
fn has_mm_processor_override(value: Option<&serde_json::Value>) -> bool {
    value.is_some_and(|value| match value {
        serde_json::Value::Null => false,
        serde_json::Value::Object(map) => !map.is_empty(),
        // The schema expects an object. Fail closed for every other JSON shape
        // because its processor semantics are unknown here.
        _ => true,
    })
}

#[cfg(feature = "mm-routing")]
fn exact_mm_routing_preconditions_met(
    has_user_uuid: bool,
    resolved_image_count: usize,
    total_image_count: usize,
    has_processor_override: bool,
) -> bool {
    // Processor kwargs participate in backend feature hashing and can change
    // prompt expansion. Until the frontend reproduces those transformations,
    // exact routing must fail closed so router and worker cache keys agree.
    !has_user_uuid && !has_processor_override && resolved_image_count == total_image_count
}

#[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
fn should_hash_decoded_video(
    exact_mm_routing_eligible: bool,
    has_user_uuid: bool,
    has_processor_override: bool,
    has_video_routing_processor: bool,
) -> bool {
    exact_mm_routing_eligible
        && !has_user_uuid
        && !has_processor_override
        && has_video_routing_processor
}

#[cfg(feature = "mm-routing")]
fn exact_mm_routing_supports_modality(modality: &str, frontend_decoding: bool) -> bool {
    modality == "image_url" || (modality == "video_url" && frontend_decoding)
}

#[cfg(feature = "mm-routing")]
fn aggregate_image_tokens(
    image_tokens: Option<usize>,
    resolved_image_count: usize,
    total_image_count: usize,
    has_processor_override: bool,
) -> Option<usize> {
    if total_image_count == 0 || has_processor_override || resolved_image_count != total_image_count
    {
        return None;
    }

    image_tokens
}

/// Derive the model's local directory from the MDC. The directory is the
/// parent of `config.json` (which lives in `mdc.model_info` as `HfConfigJson`)
/// and contains the other artifacts MM-aware routing reads at startup
/// (`tokenizer.json`, `processor_config.json`, `preprocessor_config.json`).
/// Returns `None` for cards built from non-disk sources.
#[cfg(feature = "mm-routing")]
fn mdc_model_dir(mdc: &ModelDeploymentCard) -> Option<std::path::PathBuf> {
    let ModelInfoType::HfConfigJson(cf) = mdc.model_info.as_ref()?;
    cf.path()?.parent().map(std::path::PathBuf::from)
}

/// Shared SSRF-aware `MediaFetcher` + `reqwest::Client` for the dim-fetch
/// path used by MM-aware routing and image-token metrics. Inherits the same
/// policy contract as the frontend-decode path (`MediaLoader`): blocklist DNS
/// resolver, redirect revalidation, hostname/IP blocklist,
/// `DYN_MM_ALLOW_INTERNAL` opt-in.
///
/// **Lifecycle:** `LazyLock` so the closure runs on first access. For MM-
/// countable or routable preprocessors, `OpenAIPreprocessor::new_with_parts` calls
/// `LazyLock::force(...)` at startup — that surfaces TLS-root / reqwest-
/// init / env-misconfig failures at deployment time, not on the first MM
/// request 20 minutes in. Text-only deployments skip the force, leaving
/// the LazyLock dormant.
#[cfg(feature = "mm-routing")]
static DIM_FETCH_MEDIA_FETCHER: std::sync::LazyLock<crate::preprocessor::media::MediaFetcher> =
    std::sync::LazyLock::new(crate::preprocessor::media::MediaFetcher::from_env);

#[cfg(feature = "mm-routing")]
static DIM_FETCH_HTTP_CLIENT: std::sync::LazyLock<reqwest::Client> =
    std::sync::LazyLock::new(|| {
        DIM_FETCH_MEDIA_FETCHER
            .build_http_client()
            .expect("dim-fetch http client construction failed")
    });

pub(crate) const PRESERVE_OMITTED_MAX_TOKENS_CONTEXT_KEY: &str =
    "dynamo.llm.preserve_omitted_max_tokens";

const EMBEDDING_ADD_SPECIAL_TOKENS_ENV: &str = "DYN_EMBEDDING_TOKENIZATION_ADD_SPECIAL_TOKENS";

fn parse_embedding_add_special_tokens(value: &str) -> Option<bool> {
    parse_bool_opt(value)
}

fn embedding_add_special_tokens_env() -> Result<Option<bool>> {
    match std::env::var(EMBEDDING_ADD_SPECIAL_TOKENS_ENV) {
        Ok(value) => match parse_embedding_add_special_tokens(&value) {
            Some(value) => Ok(Some(value)),
            None => bail!(
                "invalid value {value:?} for {EMBEDDING_ADD_SPECIAL_TOKENS_ENV}; \
                 expected true/false/on/off/yes/no/1/0"
            ),
        },
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => bail!(
            "{EMBEDDING_ADD_SPECIAL_TOKENS_ENV} must be valid Unicode and one of \
             true/false/on/off/yes/no/1/0"
        ),
    }
}

#[cfg(test)]
mod embedding_add_special_tokens_env_tests {
    use super::parse_embedding_add_special_tokens;

    #[test]
    fn parser_uses_the_documented_truth_table() {
        for value in ["1", "true", "on", "yes", " TRUE ", "On", "Yes"] {
            assert_eq!(parse_embedding_add_special_tokens(value), Some(true));
        }
        for value in ["0", "false", "off", "no", " FALSE ", "Off", "No"] {
            assert_eq!(parse_embedding_add_special_tokens(value), Some(false));
        }
        for value in ["", "yes-please"] {
            assert_eq!(parse_embedding_add_special_tokens(value), None);
        }
    }
}

fn embedding_chat_template_present(mdc: &ModelDeploymentCard) -> Result<bool> {
    if mdc.chat_template_file.is_some() {
        return Ok(true);
    }

    let Some(artifact) = mdc.prompt_formatter.as_ref() else {
        return Ok(false);
    };
    let PromptFormatterArtifact::HfTokenizerConfigJson(checked_file) = artifact else {
        return Ok(true);
    };
    let Some(path) = checked_file.path() else {
        return Ok(true);
    };

    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("fs:read_to_string '{}'", path.display()))?;
    let config: serde_json::Value = serde_json::from_str(&contents)
        .with_context(|| format!("Failed to parse '{}'", path.display()))?;
    Ok(config
        .get("chat_template")
        .is_some_and(|template| !template.is_null()))
}

fn embedding_prompt_formatter(mdc: &ModelDeploymentCard) -> Result<PromptFormatter> {
    match prompt_formatter_from_mdc(mdc) {
        Ok(formatter) => Ok(formatter),
        Err(_) if !embedding_chat_template_present(mdc)? => Ok(PromptFormatter::no_op()),
        Err(err) => Err(err),
    }
}

fn attach_agent_context_from_context(
    request: &mut PreprocessedRequest,
    context: &PipelineContext<()>,
) {
    if let Ok(agent_context) = context.get::<crate::protocols::common::extensions::AgentContext>(
        crate::protocols::common::extensions::AGENT_CONTEXT_CONTEXT_KEY,
    ) {
        request.agent_context = Some(agent_context.as_ref().clone());
    }
}

/// Thin wrapper that prepares messages for MiniJinja. Normalizes historical
/// `function.arguments` when the model opts in (GLM-5.2), and appends
/// HuggingFace's unique continue-final-message marker when that flag is set.
/// All other trait methods delegate to the inner request.
struct NormalizedArgsRequest<'a, R> {
    inner: &'a R,
    normalize_tool_call_args: bool,
    continue_final_message: bool,
}

impl<R: OAIChatLikeRequest> OAIChatLikeRequest for NormalizedArgsRequest<'_, R> {
    fn model(&self) -> String {
        self.inner.model()
    }

    fn messages(&self) -> minijinja::value::Value {
        let mut json = serde_json::to_value(self.inner.typed_messages().unwrap_or_default())
            .unwrap_or_default();
        if self.normalize_tool_call_args
            && let Err(e) = crate::preprocessor::prompt::normalize_tool_call_arguments(&mut json)
        {
            tracing::error!(
                error = %e,
                "tool_call arguments normalization failed; template rendering may fail \
                 if it calls .items() on a string"
            );
        }
        if self.continue_final_message
            && let Err(e) =
                crate::preprocessor::prompt::append_continue_final_message_tag(&mut json)
        {
            tracing::debug!(
                error = %e,
                "continue_final_message marker not appended; truncation will reject the request"
            );
        }
        minijinja::value::Value::from_serialize(&json)
    }

    fn typed_messages(&self) -> Option<&[dynamo_protocols::types::ChatCompletionRequestMessage]> {
        self.inner.typed_messages()
    }

    fn tools(&self) -> Option<minijinja::value::Value> {
        self.inner.tools()
    }

    fn tool_choice(&self) -> Option<minijinja::value::Value> {
        self.inner.tool_choice()
    }

    fn response_format(&self) -> Option<minijinja::value::Value> {
        self.inner.response_format()
    }

    fn should_add_generation_prompt(&self) -> bool {
        self.inner.should_add_generation_prompt()
    }

    fn extract_text(&self) -> Option<TextInput> {
        self.inner.extract_text()
    }

    fn chat_template_args(&self) -> Option<&std::collections::HashMap<String, serde_json::Value>> {
        self.inner.chat_template_args()
    }

    fn mm_processor_kwargs(&self) -> Option<&serde_json::Value> {
        self.inner.mm_processor_kwargs()
    }
}

impl<R: AnnotationsProvider> AnnotationsProvider for NormalizedArgsRequest<'_, R> {
    fn annotations(&self) -> Option<Vec<String>> {
        self.inner.annotations()
    }
}

impl<R: SamplingOptionsProvider> SamplingOptionsProvider for NormalizedArgsRequest<'_, R> {
    fn extract_sampling_options(
        &self,
    ) -> anyhow::Result<crate::protocols::common::SamplingOptions> {
        self.inner.extract_sampling_options()
    }
}

impl<R: StopConditionsProvider> StopConditionsProvider for NormalizedArgsRequest<'_, R> {
    fn extract_stop_conditions(&self) -> anyhow::Result<crate::protocols::common::StopConditions> {
        self.inner.extract_stop_conditions()
    }
}

impl<R: OutputOptionsProvider> OutputOptionsProvider for NormalizedArgsRequest<'_, R> {
    fn extract_output_options(&self) -> anyhow::Result<crate::protocols::common::OutputOptions> {
        self.inner.extract_output_options()
    }
}

impl<R: NvExtProvider> NvExtProvider for NormalizedArgsRequest<'_, R> {
    fn nvext(&self) -> Option<&crate::protocols::common::extensions::NvExt> {
        self.inner.nvext()
    }

    fn raw_prompt(&self) -> Option<String> {
        self.inner.raw_prompt()
    }

    fn unsupported_fields(&self) -> Option<&std::collections::HashMap<String, serde_json::Value>> {
        self.inner.unsupported_fields()
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct PreprocessRequestOptions {
    preserve_omitted_max_tokens: bool,
}

struct EmbeddingTokenizerState {
    model_card: ModelDeploymentCard,
    with_special_tokens: OnceLock<Arc<dyn Tokenizer>>,
    without_special_tokens: OnceLock<Arc<dyn Tokenizer>>,
    initialization_lock: Mutex<()>,
    add_special_tokens_default: Option<bool>,
}

impl EmbeddingTokenizerState {
    fn new(model_card: &ModelDeploymentCard) -> Result<Self> {
        Ok(Self {
            model_card: model_card.clone(),
            with_special_tokens: OnceLock::new(),
            without_special_tokens: OnceLock::new(),
            initialization_lock: Mutex::new(()),
            add_special_tokens_default: embedding_add_special_tokens_env()?,
        })
    }

    fn tokenizer(&self, add_special_tokens: bool) -> Result<Arc<dyn Tokenizer>> {
        let tokenizer = if add_special_tokens {
            &self.with_special_tokens
        } else {
            &self.without_special_tokens
        };
        if let Some(tokenizer) = tokenizer.get() {
            return Ok(tokenizer.clone());
        }

        let _guard = self
            .initialization_lock
            .lock()
            .map_err(|_| anyhow::anyhow!("embedding tokenizer initialization lock was poisoned"))?;
        if let Some(tokenizer) = tokenizer.get() {
            return Ok(tokenizer.clone());
        }

        let initialized = self.model_card.embedding_tokenizer_with_options(
            crate::tokenizers::TokenizerOptions { add_special_tokens },
        )?;
        let initialized: Arc<dyn Tokenizer> = (*initialized).clone();
        Ok(tokenizer.get_or_init(|| initialized).clone())
    }
}

pub struct OpenAIPreprocessor {
    mdcsum: String,
    formatter: Arc<dyn OAIPromptFormatter>,
    tokenizer: Arc<dyn Tokenizer>,
    /// Present only for token-input embedding pipelines. The two tokenizer
    /// variants are initialized independently on demand.
    embedding_tokenizers: Option<EmbeddingTokenizerState>,
    model_info: Arc<dyn ModelInfo>,
    lora_name: Option<String>,
    /// Per-model runtime configuration propagated to response generator (e.g., reasoning/tool parser)
    runtime_config: crate::local_model::runtime_config::ModelRuntimeConfig,
    /// KV cache block size published in the model deployment card.
    kv_cache_block_size: usize,
    tool_call_parser: Option<String>,
    /// Normalize historical tool-call `function.arguments` from a JSON string
    /// to an object before MiniJinja rendering.  Enabled for GLM-5.2 (glm47
    /// parser) and any model that sets `normalize_tool_call_args: true` in its
    /// ModelRuntimeConfig; disabled for all other models.
    normalize_tool_call_args: bool,
    media_loader: Option<MediaLoader>,
    /// Engine-published request-token admission policy.
    token_budget: Option<TokenBudget>,
    /// Model context limit used by the embedding truncation contract.
    context_length: u32,
    /// Per-image token-count engine. `None` when the feature is disabled, the
    /// model isn't covered by the registry, or `preprocessor_config.json` is
    /// unreadable.
    #[cfg(feature = "mm-routing")]
    image_token_counter: Option<lightseek_mm::LightseekMmCounter>,
    /// Lightweight model-visible video expansion. Unlike the image counter,
    /// this does not resize or normalize pixels in the frontend.
    #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
    video_routing_processor: Option<mm_routing::VideoRoutingProcessor>,
    /// Image-placeholder token id the routing-side sequence fills per image.
    /// Resolved from `config.json`'s `image_token_id` field when present,
    /// otherwise falls back to the `ModelProcessorSpec` registry value. This
    /// is the id the backend's HF processor emits in the expanded sequence
    /// (per-patch token for Qwen-VL families, the single placeholder for
    /// LLaVA), so block hashes align bit-for-bit with the worker.
    ///
    /// `None` disables MM-aware routing for this model and the router falls
    /// back to text-prefix routing.
    #[cfg(feature = "mm-routing")]
    routing_image_token_id: Option<crate::protocols::TokenIdType>,
    /// Model-specific routing-side image prompt shape. Most families replace
    /// only an existing pad token; Kimi-K3 also inserts its structural wrapper
    /// and pre-resize dimensions. `None` disables exact MM routing.
    #[cfg(feature = "mm-routing")]
    routing_image_prompt_layout: Option<RoutingImagePromptLayout>,
    /// Dimension semantics used by URL-passthrough routing. Kimi-K3's vLLM
    /// processor applies EXIF transpose before rendering its dimension block.
    #[cfg(feature = "mm-routing")]
    routing_image_dimension_policy: RoutingImageDimensionPolicy,
    /// BOS token id to prepend to the routing-side sequence so per-block
    /// hashes match the backend's HF processor output on models with
    /// `add_bos_token: true` (LLaVA-1.5 and other `LlamaTokenizer`
    /// families). Applied only to requests containing images; video-only
    /// routing starts from the frontend-tokenized prompt. `None` when the
    /// model doesn't need it or `bos_token` doesn't round-trip to one id.
    #[cfg(feature = "mm-routing")]
    routing_prepend_bos: Option<crate::protocols::TokenIdType>,
}

pub(crate) const LORA_NAME_CONTEXT_KEY: &str = "discovery.lora_name";

impl OpenAIPreprocessor {
    fn omitted_max_tokens_default(
        prompt_len: usize,
        token_limit: Option<u32>,
        options: PreprocessRequestOptions,
    ) -> Option<u32> {
        if options.preserve_omitted_max_tokens {
            return None;
        }
        token_limit.map(|limit| limit.saturating_sub(prompt_len as u32))
    }

    /// Return the exact prompt length when the frontend can prove it.
    ///
    /// MM routing currently expands image placeholders only. Therefore any
    /// other non-empty media modality makes even an image-expanded length
    /// incomplete and forces backend validation.
    fn exact_prompt_len(
        expanded_image_prompt_len: Option<usize>,
        multi_modal_data: Option<&MultimodalDataMap>,
        token_ids_len: usize,
    ) -> Option<usize> {
        let has_images = multi_modal_data
            .and_then(|media| media.get("image_url"))
            .is_some_and(|items| !items.is_empty());
        let has_other_media = multi_modal_data.is_some_and(|media| {
            media
                .iter()
                .any(|(kind, items)| kind != "image_url" && !items.is_empty())
        });

        if has_other_media {
            None
        } else if let Some(expanded_prompt_len) =
            expanded_image_prompt_len.filter(|length| *length > 0)
        {
            Some(expanded_prompt_len)
        } else if has_images {
            None
        } else {
            Some(token_ids_len)
        }
    }

    /// Apply the engine-published rejection policy to an exact request length.
    fn validate_requested_token_budget(
        prompt_len: usize,
        max_tokens: Option<u32>,
        token_budget: Option<&TokenBudget>,
    ) -> Result<()> {
        let Some(token_budget) = token_budget else {
            return Ok(());
        };
        let combined_limit = token_budget.combined_limit as usize;

        // A prompt that fills the combined budget leaves no room for generation.
        // When prompt overflow is backend-owned, its effective length may change.
        if prompt_len >= combined_limit {
            if !token_budget.reject_prompt_overflow {
                return Ok(());
            }
            return Err(Self::prompt_overflow_error(prompt_len, combined_limit).into());
        }

        // Generation requires at least one output token when the cap is omitted.
        let requested_tokens = prompt_len.saturating_add(max_tokens.unwrap_or(1) as usize);
        if requested_tokens > combined_limit && token_budget.reject_total_overflow {
            let request_description = match max_tokens {
                Some(max_tokens) => format!(
                    "your request has {prompt_len} input tokens and asks for {max_tokens} output \
                     tokens ({requested_tokens} tokens total)"
                ),
                None => format!(
                    "your request has {prompt_len} input tokens and requires room for at least one \
                     output token ({requested_tokens} tokens minimum)"
                ),
            };
            return Err(DynamoError::builder()
                .error_type(ErrorType::InvalidArgument)
                .message(format!(
                    "This model configuration accepts at most {} combined input and output \
                     tokens. However, {}. Please reduce the input length or requested output \
                     length.",
                    combined_limit, request_description,
                ))
                .build()
                .into());
        }

        Ok(())
    }

    /// Validate a preprocessed request when its frontend-visible prompt length
    /// is exact, returning that length for other context-budget decisions.
    fn validate_preprocessed_token_budget(
        request: &PreprocessedRequest,
        token_budget: Option<&TokenBudget>,
    ) -> Result<Option<usize>> {
        if request.prompt_embeds.is_some() {
            return Ok(None);
        }

        let exact_prompt_len = Self::exact_prompt_len(
            request
                .mm_routing_info
                .as_ref()
                .map(|mm| mm.expanded_prompt_len),
            request.multi_modal_data.as_ref(),
            request.token_ids.len(),
        );
        if let Some(prompt_len) = exact_prompt_len {
            Self::validate_requested_token_budget(
                prompt_len,
                request.stop_conditions.max_tokens,
                token_budget,
            )?;
        }

        Ok(exact_prompt_len)
    }

    fn nvext_passthrough_args<R: NvExtProvider>(
        request: &R,
    ) -> Option<serde_json::Map<String, serde_json::Value>> {
        let mut nvext_passthrough = serde_json::Map::new();

        if let Some(nvext) = request.nvext() {
            if let Some(ref fields) = nvext.extra_fields {
                nvext_passthrough.insert("extra_fields".to_string(), serde_json::json!(fields));
            }
            if let Some(ref metadata_upload) = nvext.metadata_upload {
                nvext_passthrough.insert(
                    "metadata_upload".to_string(),
                    serde_json::json!(metadata_upload),
                );
            }
            if nvext.token_data.is_some() {
                nvext_passthrough.insert("token_in".to_string(), serde_json::Value::Bool(true));
            }
        }

        if let Some(salt) = request_cache_salt(request) {
            nvext_passthrough.insert("cache_salt".to_string(), serde_json::json!(salt));
        }

        if nvext_passthrough.is_empty() {
            None
        } else {
            Some(nvext_passthrough)
        }
    }

    fn sampling_passthrough_args<R: NvExtProvider>(
        request: &R,
    ) -> Option<serde_json::Map<String, serde_json::Value>> {
        let mut sampling_passthrough = serde_json::Map::new();

        if let Some(fields) = request.unsupported_fields() {
            for key in [
                "detokenize",
                "allowed_token_ids",
                "bad_words_token_ids",
                "logprob_token_ids",
            ] {
                if let Some(value) = fields.get(key) {
                    sampling_passthrough.insert(key.to_string(), value.clone());
                }
            }
        }

        if sampling_passthrough.is_empty() {
            None
        } else {
            Some(sampling_passthrough)
        }
    }

    fn backend_extra_args<R: OAIChatLikeRequest + NvExtProvider>(
        request: &R,
        reasoning_parser_configured: bool,
        reasoning_ended: Option<bool>,
    ) -> Option<serde_json::Value> {
        let mut extra_args = serde_json::Map::new();

        if let Some(nvext_passthrough) = Self::nvext_passthrough_args(request) {
            extra_args.insert(
                "nvext".to_string(),
                serde_json::Value::Object(nvext_passthrough),
            );
        }

        if let Some(sampling_passthrough) = Self::sampling_passthrough_args(request) {
            extra_args.insert(
                "sampling_options".to_string(),
                serde_json::Value::Object(sampling_passthrough),
            );
        }

        // vLLM constructs some native reasoning parsers per request. Forward
        // the accepted public template arguments through the internal request
        // so its guided-decoding gate observes the same thinking mode used to
        // render the prompt.
        if reasoning_parser_configured
            && let Some(chat_template_args) = request.chat_template_args()
        {
            extra_args.insert(
                "reasoning_parser_kwargs".to_string(),
                serde_json::json!({ "chat_template_kwargs": chat_template_args }),
            );
        }
        if reasoning_parser_configured && let Some(reasoning_ended) = reasoning_ended {
            extra_args.insert("reasoning_ended".to_string(), reasoning_ended.into());
        }

        if extra_args.is_empty() {
            None
        } else {
            Some(serde_json::Value::Object(extra_args))
        }
    }

    fn has_request_thinking_control(
        chat_template_args: Option<&HashMap<String, serde_json::Value>>,
    ) -> bool {
        chat_template_args.is_some_and(|args| {
            [
                "thinking",
                "enable_thinking",
                "thinking_mode",
                "reasoning_effort",
            ]
            .iter()
            .any(|key| args.contains_key(*key))
        })
    }

    fn request_has_client_thinking_control(request: &NvCreateChatCompletionRequest) -> bool {
        request.thinking.is_some()
            || Self::has_request_thinking_control(request.chat_template_args.as_ref())
    }

    fn apply_default_thinking_mode_from_runtime_config(
        runtime_config: &crate::local_model::runtime_config::ModelRuntimeConfig,
        request: &mut NvCreateChatCompletionRequest,
    ) {
        if Self::request_has_client_thinking_control(request) {
            return;
        }

        let Some(default_mode) = runtime_config
            .runtime_data
            .get(DEFAULT_THINKING_MODE_RUNTIME_KEY)
            .and_then(|value| value.as_str())
        else {
            return;
        };

        let enabled = match default_mode {
            "enabled" => true,
            "disabled" => false,
            other => {
                tracing::warn!(
                    default_thinking_mode = other,
                    "Ignoring invalid runtime_config default_thinking_mode; expected 'enabled' or 'disabled'"
                );
                return;
            }
        };

        let args = request.chat_template_args.get_or_insert_with(HashMap::new);
        args.insert("thinking".to_string(), serde_json::Value::Bool(enabled));
        args.insert(
            "enable_thinking".to_string(),
            serde_json::Value::Bool(enabled),
        );
        args.insert(
            "thinking_mode".to_string(),
            serde_json::Value::String(if enabled { "enabled" } else { "disabled" }.to_string()),
        );
    }

    fn apply_default_thinking_mode(&self, request: &mut NvCreateChatCompletionRequest) {
        Self::apply_default_thinking_mode_from_runtime_config(&self.runtime_config, request);
    }

    fn guided_output_requires_reasoning<R: OAIChatLikeRequest>(
        request: &R,
        reasoning_parser: Option<&str>,
    ) -> bool {
        if reasoning_parser.is_none() {
            return false;
        }

        let is_guided_tool_choice = Self::has_guided_tool_choice(request);
        let is_structured_response = Self::has_structured_response_format(request);
        let structured_response_requires_reasoning = is_structured_response
            && Self::structured_response_supports_sglang_reasoning_gate(reasoning_parser);

        (is_guided_tool_choice || structured_response_requires_reasoning)
            && Self::sglang_effective_reasoning_enabled(
                reasoning_parser,
                request.chat_template_args(),
            )
    }

    fn structured_response_supports_sglang_reasoning_gate(reasoning_parser: Option<&str>) -> bool {
        // GPT-OSS/Harmony must skip SGLang's `require_reasoning + json_schema`
        // path for structured output until upstream fixes malformed Harmony:
        // https://github.com/sgl-project/sglang/issues/31019
        // Tool calling still uses `require_reasoning`.
        !matches!(reasoning_parser, Some("gpt_oss"))
    }

    fn has_structured_response_format<R: OAIChatLikeRequest>(request: &R) -> bool {
        request.response_format().is_some_and(|format| {
            format
                .get_attr("type")
                .ok()
                .is_some_and(|kind| kind.as_str().is_some_and(|kind| kind != "text"))
        })
    }

    /// Match the rendered prompt's reasoning mode before selecting SGLang NativeGrammar.
    fn sglang_effective_reasoning_enabled(
        reasoning_parser: Option<&str>,
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
    ) -> bool {
        let thinking_enabled = dynamo_renderer::thinking_bool_from_args(chat_template_args);

        match reasoning_parser {
            // These SGLang reasoners are enabled unless the request opts out.
            Some("qwen3" | "glm45" | "nemotron_nano" | "nemotron3" | "nemotron_v3") => {
                thinking_enabled != Some(false)
            }
            Some("kimi_k25" | "kimi_k3" | "kimi-k3") => thinking_enabled != Some(false),
            Some("minimax_m2") => {
                Self::deepseek_renderer_reasoning_enabled(chat_template_args, true)
            }

            // DeepSeek V3/V3.1 templates are opt-in. The native V3.2/V4
            // renderers default to thinking; all honor the same aliases.
            Some("deepseek_v3" | "deepseek_v3_1") => {
                Self::deepseek_renderer_reasoning_enabled(chat_template_args, false)
            }
            Some("deepseek_v3_2" | "deepseek_v4" | "deepseek-v4" | "deepseekv4") => {
                Self::deepseek_renderer_reasoning_enabled(chat_template_args, true)
            }
            Some("gemma4" | "gemma-4") => thinking_enabled == Some(true),

            // SGLang's Mistral reasoner is active only for a concrete effort.
            Some("mistral") => Self::mistral_reasoning_enabled(chat_template_args),

            // MiniMax M3 defaults to adaptive reasoning unless disabled.
            Some("minimax_m3" | "minimax-m3") => chat_template_args
                .and_then(|args| args.get("thinking_mode"))
                .and_then(serde_json::Value::as_str)
                .is_none_or(|mode| mode != "disabled"),

            // These SGLang reasoners do not expose a per-request off mode.
            Some("deepseek_r1" | "step3" | "gpt_oss" | "kimi") => true,
            _ => false,
        }
    }

    /// Mirror dynamo-renderer's DeepSeek reasoning-toggle precedence.
    fn deepseek_renderer_reasoning_enabled(
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
        default_enabled: bool,
    ) -> bool {
        if let Some(enabled) = dynamo_renderer::thinking_bool_from_args(chat_template_args) {
            return enabled;
        }
        if let Some(mode) = chat_template_args
            .and_then(|args| args.get("thinking_mode"))
            .and_then(serde_json::Value::as_str)
        {
            return match mode {
                "chat" => false,
                "thinking" => true,
                _ => default_enabled,
            };
        }
        default_enabled
    }

    #[cfg(test)]
    fn normalize_thinking_arg(
        request: &mut NvCreateChatCompletionRequest,
        reasoning_parser: Option<&str>,
        tool_call_parser: Option<&str>,
    ) {
        let thinking_control_from_client = Self::request_has_client_thinking_control(request);
        Self::normalize_thinking_arg_with_source(
            request,
            reasoning_parser,
            tool_call_parser,
            thinking_control_from_client,
        );
    }

    fn normalize_thinking_arg_with_source(
        request: &mut NvCreateChatCompletionRequest,
        reasoning_parser: Option<&str>,
        tool_call_parser: Option<&str>,
        thinking_control_from_client: bool,
    ) {
        let normalized = Self::normalize_thinking_aliases(request, reasoning_parser);

        if Self::is_minimax_m3_family(reasoning_parser, tool_call_parser) {
            Self::normalize_minimax_m3_thinking_mode(
                request,
                normalized,
                thinking_control_from_client,
            );
            return;
        }

        Self::apply_normalized_thinking_aliases(request, normalized);
    }

    fn normalize_thinking_aliases(
        request: &NvCreateChatCompletionRequest,
        reasoning_parser: Option<&str>,
    ) -> Option<bool> {
        request
            .chat_template_args
            .as_ref()
            .and_then(|args| {
                // Normalize public aliases in array order: `thinking`,
                // `enable_thinking`, then `thinking_mode`.
                // Preserve "adaptive" as tri-state by returning None.
                for key in ["thinking", "enable_thinking", "thinking_mode"] {
                    match args.get(key) {
                        Some(serde_json::Value::Bool(b)) => {
                            // `thinking_bool_from_args` ignores `thinking_mode`,
                            // so read that bool directly.
                            if key == "thinking_mode" {
                                return Some(*b);
                            }
                            return dynamo_renderer::thinking_bool_from_args(Some(args));
                        }
                        Some(serde_json::Value::String(value)) => {
                            // Parse `thinking_mode` explicitly so
                            // "enabled"/"disabled" and boolean spellings
                            // behave predictably. Preserve unrecognized strings
                            // such as "adaptive" or DeepSeek's "chat"/"thinking".
                            if key == "thinking_mode" {
                                if value.eq_ignore_ascii_case("enabled") {
                                    return Some(true);
                                }
                                if value.eq_ignore_ascii_case("disabled") {
                                    return Some(false);
                                }
                                if let Some(b) = parse_bool_opt(value) {
                                    return Some(b);
                                }
                                return None;
                            }
                            return Some(is_truthy(value));
                        }
                        Some(serde_json::Value::Number(value)) => {
                            if let Some(value) = value.as_f64() {
                                return Some(value != 0.0);
                            }
                        }
                        _ => {}
                    }
                }
                None
            })
            .or_else(|| {
                matches!(reasoning_parser, Some("kimi_k25" | "kimi_k3" | "kimi-k3")).then_some(true)
            })
    }

    fn normalize_minimax_m3_thinking_mode(
        request: &mut NvCreateChatCompletionRequest,
        normalized: Option<bool>,
        thinking_control_from_client: bool,
    ) {
        // MiniMax M3 defaults `thinking_mode` to "adaptive", which breaks
        // constrained JSON/schema and forced-tool generation. If the client
        // did not set thinking controls, force "disabled" for those requests.
        let explicit_thinking_mode_is_adaptive = request
            .chat_template_args
            .as_ref()
            .and_then(|args| args.get("thinking_mode"))
            .and_then(|v| v.as_str())
            .is_some_and(|s| s.eq_ignore_ascii_case("adaptive"));
        if !thinking_control_from_client && Self::has_minimax_m3_constrained_generation(request) {
            let args = request.chat_template_args.get_or_insert_default();
            args.insert(
                "thinking_mode".to_string(),
                serde_json::Value::String("disabled".to_string()),
            );
            args.insert("thinking".to_string(), serde_json::Value::Bool(false));
            args.insert(
                "enable_thinking".to_string(),
                serde_json::Value::Bool(false),
            );
            return;
        }

        Self::apply_normalized_thinking_aliases(request, normalized);

        let Some(normalized) = normalized else {
            return;
        };

        // Canonicalize for M3 because its template only treats exact
        // "disabled" as off. Preserve explicit "adaptive" as client intent.
        if !explicit_thinking_mode_is_adaptive {
            let args = request.chat_template_args.get_or_insert_default();
            args.insert(
                "thinking_mode".to_string(),
                serde_json::Value::String(
                    if normalized { "enabled" } else { "disabled" }.to_string(),
                ),
            );
        }
    }

    fn apply_normalized_thinking_aliases(
        request: &mut NvCreateChatCompletionRequest,
        normalized: Option<bool>,
    ) {
        let Some(normalized) = normalized else {
            return;
        };
        let args = request.chat_template_args.get_or_insert_default();
        args.insert("thinking".to_string(), serde_json::Value::Bool(normalized));
        args.insert(
            "enable_thinking".to_string(),
            serde_json::Value::Bool(normalized),
        );
    }

    /// True when the deployment renders MiniMax M3's `thinking_mode` template.
    /// Either parser is sufficient, and tool-call aliases include `_nom`.
    fn is_minimax_m3_family(
        reasoning_parser: Option<&str>,
        tool_call_parser: Option<&str>,
    ) -> bool {
        matches!(reasoning_parser, Some("minimax_m3") | Some("minimax-m3"))
            || matches!(
                tool_call_parser,
                Some("minimax_m3")
                    | Some("minimax-m3")
                    | Some("minimax_m3_nom")
                    | Some("minimax-m3-nom")
            )
    }

    fn has_minimax_m3_constrained_generation<R: OAIChatLikeRequest>(request: &R) -> bool {
        Self::has_structured_response_format(request) || Self::has_guided_tool_choice(request)
    }

    /// True when `tool_choice` forces a tool call.
    /// Shared by guided-output reasoning checks and the M3 default.
    fn has_guided_tool_choice<R: OAIChatLikeRequest>(request: &R) -> bool {
        request.tool_choice().is_some_and(|tool_choice| {
            match tool_choice.as_str() {
                Some("required") => true,
                Some(_) => false,
                // The only supported non-string tool choice is a named function.
                None => true,
            }
        })
    }

    /// Apply Moonshot's named-tool exception for Kimi K3.
    ///
    /// The public K3 API treats a specified function as incompatible with
    /// thinking. Normalize that rule onto the request before prompt rendering
    /// so every downstream consumer observes the same effective mode:
    ///
    /// - the K3 renderer omits current and preserved thinking channels,
    /// - prompt-injected reasoning detection stays false,
    /// - backend reasoning-parser kwargs carry the disabled state, and
    /// - response postprocessing does not try to parse a reasoning stream.
    fn normalize_kimi_k3_named_tool_choice(
        request: &mut NvCreateChatCompletionRequest,
        tool_call_parser: Option<&str>,
    ) {
        let uses_kimi_k3_parser =
            tool_call_parser.is_some_and(|parser| matches!(parser, "kimi_k3" | "kimi-k3"));
        let is_named = matches!(
            request.inner.tool_choice.as_ref(),
            Some(ChatCompletionToolChoiceOption::Named(_))
        );
        if !uses_kimi_k3_parser || !is_named {
            return;
        }

        let args = request.chat_template_args.get_or_insert_default();
        args.insert("thinking".to_string(), serde_json::Value::Bool(false));
        args.insert(
            "enable_thinking".to_string(),
            serde_json::Value::Bool(false),
        );
    }

    fn mistral_reasoning_enabled(
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
    ) -> bool {
        chat_template_args
            .and_then(|args| args.get("reasoning_effort"))
            .and_then(serde_json::Value::as_str)
            .is_some_and(|effort| effort != "none")
    }

    pub fn new(mdc: ModelDeploymentCard) -> Result<Arc<Self>> {
        let formatter = prompt_formatter_from_mdc(&mdc)?;
        let tokenizer = mdc.tokenizer()?;
        match formatter {
            PromptFormatter::OAI(formatter) => Self::new_with_parts(mdc, formatter, tokenizer),
        }
    }

    /// Build the preprocessor used by token-input embedding pipelines.
    pub fn new_for_embeddings(mdc: ModelDeploymentCard) -> Result<Arc<Self>> {
        if !mdc.model_type.supports_embedding() {
            anyhow::bail!("embedding preprocessor requires an embedding-capable model");
        }

        let tokenizer = mdc.tokenizer()?;
        let PromptFormatter::OAI(formatter) = embedding_prompt_formatter(&mdc)?;
        let embedding_tokenizers = EmbeddingTokenizerState::new(&mdc)?;
        Self::new_with_parts_inner(mdc, formatter, tokenizer, Some(embedding_tokenizers))
    }

    pub fn new_with_parts(
        mdc: ModelDeploymentCard,
        formatter: Arc<dyn OAIPromptFormatter>,
        tokenizer: crate::tokenizers::Tokenizer,
    ) -> Result<Arc<Self>> {
        Self::new_with_parts_inner(mdc, formatter, tokenizer, None)
    }

    fn new_with_parts_inner(
        mdc: ModelDeploymentCard,
        formatter: Arc<dyn OAIPromptFormatter>,
        tokenizer: crate::tokenizers::Tokenizer,
        embedding_tokenizers: Option<EmbeddingTokenizerState>,
    ) -> Result<Arc<Self>> {
        let mdcsum = mdc.mdcsum().to_string();
        let tokenizer: Arc<dyn Tokenizer> = (*tokenizer).clone();
        let lora_name = mdc.lora.as_ref().map(|l| l.name.clone());
        let Some(ref model_info) = mdc.model_info else {
            anyhow::bail!(
                "Blank ModelDeploymentCard cannot be used for pre-processing, no model_info"
            );
        };
        let model_info = model_info.get_model_info()?;
        let tool_call_parser = mdc.runtime_config.tool_call_parser.clone();
        let normalize_tool_call_args = mdc.runtime_config.tool_call_arguments_format
            == crate::local_model::runtime_config::ToolCallArgumentsFormat::JsonObject
            || mdc.runtime_config.tool_call_parser.as_deref() == Some("glm47");

        if let Some(ref lora_name) = lora_name {
            tracing::info!(model = %mdc.display_name, lora_name, "LoRA adapter detected in MDC");
        }

        // // Initialize runtime config from the ModelDeploymentCard
        let runtime_config = mdc.runtime_config.clone();
        let token_budget = match runtime_config
            .get_engine_specific::<TokenBudget>(TOKEN_BUDGET_RUNTIME_KEY)
        {
            Ok(token_budget) => token_budget,
            Err(error) => {
                tracing::warn!(
                    %error,
                    key = TOKEN_BUDGET_RUNTIME_KEY,
                    "Ignoring invalid runtime metadata; token overflow handling will be delegated to the backend"
                );
                None
            }
        };
        let kv_cache_block_size = mdc.kv_cache_block_size as usize;
        let context_length = mdc.effective_context_length();

        // Capture MM-routing inputs before mdc is partially moved into MediaLoader.
        // model_type comes from config.json (e.g. "qwen3_vl") and lets the
        // image-processor registry resolve fine-tunes loaded from
        // custom-named directories where the family substring isn't in the path.
        #[cfg(feature = "mm-routing")]
        let model_dir_for_routing: Option<std::path::PathBuf> = mdc_model_dir(&mdc);
        #[cfg(feature = "mm-routing")]
        let fastokens_active = runtime_config.effective_tokenizer_backend().is_fastokens();
        // TODO(mm-routing): fastokens lacks a special-token mutator, so it
        // can't merge tokenizer_config.json specials and would BPE-shatter
        // placeholders (e.g. Qwen2-VL `<|image_pad|>`). Disable MM-routing
        // token resolution here, but keep SMG image-token counting enabled.
        // Remove this split once fastokens upstream exposes the mutator.
        #[cfg(feature = "mm-routing")]
        if fastokens_active && model_dir_for_routing.is_some() {
            tracing::warn!(
                target: "mm_routing",
                "fastokens tokenizer backend is active; MM-aware KV routing disabled. \
                 Image-token metrics remain enabled when SMG supports the model."
            );
        }
        #[cfg(feature = "mm-routing")]
        let image_token_inputs: Option<(String, String, std::path::PathBuf)> =
            model_dir_for_routing.as_ref().map(|p| {
                (
                    mdc.source_path().to_string(),
                    model_info.model_type(),
                    p.clone(),
                )
            });

        let media_loader = match mdc.media_decoder {
            Some(media_decoder) => Some(MediaLoader::new(media_decoder, mdc.media_fetcher)?),
            None => None,
        };

        #[cfg(feature = "mm-routing")]
        let (
            image_token_counter,
            routing_image_token_id,
            routing_image_prompt_layout,
            bos_token_string,
        ) = match image_token_inputs.as_ref() {
            Some((model_id, model_type, model_dir)) => {
                // Resolve counter + image-token id independently so the
                // summary log can name which piece is missing.
                let (counter, counter_err): (
                    Option<lightseek_mm::LightseekMmCounter>,
                    Option<String>,
                ) = match lightseek_mm::LightseekMmCounter::try_new(
                    model_id,
                    Some(model_type),
                    model_dir,
                ) {
                    Ok(c) => (Some(c), None),
                    Err(e) => (None, Some(e.to_string())),
                };
                let (img_tok, prompt_layout, bos_tok_string) = if fastokens_active {
                    (None, None, None)
                } else {
                    // One-shot config/tokenizer_config read for all
                    // routing-side token info. Parsing lives next to the
                    // spec resolution in the MM-routing module.
                    let routing_tokens =
                        lightseek_mm::resolve_routing_tokens(model_id, model_dir, counter.as_ref());
                    let prompt_layout =
                            routing_tokens.image_prompt_kind.and_then(|kind| {
                                match resolve_routing_image_prompt_layout(tokenizer.as_ref(), kind) {
                                    Ok(layout) => Some(layout),
                                    Err(e) => {
                                        tracing::warn!(
                                            target: "mm_routing",
                                            model = %model_id,
                                            error = %e,
                                            "model-specific routing image prompt could not be resolved; exact MM routing disabled"
                                        );
                                        None
                                    }
                                }
                            });
                    // Exact routing is enabled only as an all-or-nothing
                    // bundle: counter, placeholder id, and prompt layout.
                    // The worker resolves the same static prerequisites; the
                    // frontend-issued MM UUID marks request-time readiness.
                    let exact_mm_routing_ready = counter.is_some() && prompt_layout.is_some();
                    (
                        routing_tokens.exact_routing_image_token_id(exact_mm_routing_ready),
                        prompt_layout.filter(|_| counter.is_some()),
                        routing_tokens.bos_token_string,
                    )
                };

                match (counter.is_some(), img_tok.is_some()) {
                    (true, true) => tracing::info!(
                        target: "mm_routing",
                        model = %model_id,
                        model_dir = %model_dir.display(),
                        "MM-aware KV routing enabled"
                    ),
                    _ if fastokens_active => {}
                    (counter_ok, img_ok) => {
                        let mut reasons: Vec<String> = Vec::new();
                        if !counter_ok {
                            reasons.push(format!(
                                "model not supported by the MM-routing registry ({})",
                                counter_err.as_deref().unwrap_or("unknown error")
                            ));
                        }
                        if !img_ok {
                            reasons.push(
                                "image-placeholder token or model-specific prompt layout \
                                     unresolvable from \
                                     config.json / processor_config.json / \
                                     tokenizer_config.json / vocab probe"
                                    .to_string(),
                            );
                        }
                        tracing::warn!(
                            target: "mm_routing",
                            model = %model_id,
                            reasons = %reasons.join("; "),
                            "{} is not supported for MM-aware KV routing ({}). \
                             Falling back to KV routing without MM awareness — \
                             text-prefix overlap still works but the router \
                             cannot distinguish requests by image content.",
                            model_id,
                            reasons.join("; ")
                        );
                    }
                }
                (counter, img_tok, prompt_layout, bos_tok_string)
            }
            None => {
                tracing::debug!(
                    target: "mm_routing",
                    "model directory not derivable from MDC; MM-aware routing disabled"
                );
                (None, None, None, None)
            }
        };

        #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
        let video_routing_processor = {
            let processor_contract = match runtime_config
                .get_engine_specific::<mm_routing::QwenVideoProcessorContract>(
                    VLLM_QWEN_VIDEO_PROCESSOR_CONTRACT_RUNTIME_KEY,
                ) {
                Ok(target) => target,
                Err(error) => {
                    tracing::warn!(
                        target: "mm_routing",
                        %error,
                        key = VLLM_QWEN_VIDEO_PROCESSOR_CONTRACT_RUNTIME_KEY,
                        "invalid Qwen video processor runtime metadata; exact video routing disabled"
                    );
                    None
                }
            };
            if fastokens_active {
                None
            } else {
                match (image_token_inputs.as_ref(), processor_contract) {
                    (Some((model_id, model_type, model_dir)), Some(processor_contract)) => {
                        match mm_routing::VideoRoutingProcessor::try_new(
                            model_id,
                            model_type,
                            model_dir,
                            tokenizer.clone(),
                            processor_contract,
                        ) {
                            Ok(processor) => processor,
                            Err(error) => {
                                tracing::warn!(
                                    target: "mm_routing",
                                    model = %model_id,
                                    %error,
                                    "exact video-aware KV routing disabled for this model"
                                );
                                None
                            }
                        }
                    }
                    _ => None,
                }
            }
        };
        #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
        if video_routing_processor.is_some()
            && let Some((model_id, model_type, _)) = image_token_inputs.as_ref()
        {
            tracing::info!(
                target: "mm_routing",
                model = %model_id,
                model_type = %model_type,
                "exact video-aware KV routing enabled"
            );
        }

        #[cfg(feature = "mm-routing")]
        let routing_image_dimension_policy = routing_image_dimension_policy(
            &runtime_config,
            media_loader.is_some(),
            routing_image_prompt_layout,
        );

        // Force the dim-fetch HTTP client to build at startup for any
        // MM-countable or routable preprocessor, so TLS / env-var / reqwest-init
        // failures fail the deployment instead of crashing the first
        // image request 20 minutes in. Other preprocessors skip the
        // force when both image-routing hooks resolve to `None` — no point
        // building a client they'll never use.
        #[cfg(feature = "mm-routing")]
        if image_token_counter.is_some() || routing_image_token_id.is_some() {
            std::sync::LazyLock::force(&DIM_FETCH_MEDIA_FETCHER);
            std::sync::LazyLock::force(&DIM_FETCH_HTTP_CLIENT);
        }

        // Resolve the routing-side BOS prepend for models with
        // `add_bos_token: true` (see `routing_prepend_bos` doc). Only kept
        // when the configured `bos_token` round-trips to a single id. The
        // BOS string was harvested above by `resolve_routing_tokens` from
        // the same `tokenizer_config.json` pass.
        #[cfg(feature = "mm-routing")]
        let routing_prepend_bos = match bos_token_string {
            Some(bos_text) => match tokenizer.encode(&bos_text) {
                Ok(enc) if enc.token_ids().len() == 1 => {
                    let id = enc.token_ids()[0];
                    tracing::debug!(
                        target: "mm_routing",
                        bos_token = %bos_text,
                        bos_token_id = id,
                        "routing-side BOS prepend enabled (tokenizer_config.json add_bos_token=true)"
                    );
                    Some(id)
                }
                Ok(enc) => {
                    tracing::debug!(
                        target: "mm_routing",
                        bos_token = %bos_text,
                        round_trip_ids = ?enc.token_ids(),
                        "BOS token does not round-trip to a single id; routing-side prepend disabled"
                    );
                    None
                }
                Err(e) => {
                    tracing::debug!(
                        target: "mm_routing",
                        bos_token = %bos_text,
                        error = %e,
                        "BOS token failed to re-encode; routing-side prepend disabled"
                    );
                    None
                }
            },
            None => None,
        };

        Ok(Arc::new(Self {
            formatter,
            tokenizer,
            embedding_tokenizers,
            model_info,
            mdcsum,
            lora_name,
            runtime_config,
            kv_cache_block_size,
            tool_call_parser,
            normalize_tool_call_args,
            media_loader,
            token_budget,
            context_length,
            #[cfg(feature = "mm-routing")]
            image_token_counter,
            #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
            video_routing_processor,
            #[cfg(feature = "mm-routing")]
            routing_image_token_id,
            #[cfg(feature = "mm-routing")]
            routing_image_prompt_layout,
            #[cfg(feature = "mm-routing")]
            routing_image_dimension_policy,
            #[cfg(feature = "mm-routing")]
            routing_prepend_bos,
        }))
    }

    /// Encode a string to it's tokens
    pub fn tokenize(&self, s: &str) -> anyhow::Result<Encoding> {
        self.tokenizer.encode(s)
    }

    /// Encode a rendered prompt while preserving model-specific special-token
    /// boundaries.
    pub fn tokenize_rendered_prompt(&self, prompt: &RenderedPrompt) -> anyhow::Result<Encoding> {
        match prompt.encode_segments() {
            Some(segments) => self.tokenizer.encode_segments(&segments),
            None => self.tokenize(prompt.as_str()),
        }
    }

    /// Translate a [`NvCreateChatCompletionRequest`] request to a common completion request.
    /// Returns the common completion request, a hashmap of annotations, and a boolean
    /// indicating whether the rendered prompt ends with a reasoning start token (e.g.,
    /// `<think>`), meaning the model's completion will begin mid-reasoning.
    ///
    /// Annotations evaluated by this method include:
    /// - `formatted_prompt`
    /// - `token_ids`
    pub async fn preprocess_request<
        R: OAIChatLikeRequest
            + MediaRequestExt
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider
            + CommonExtProvider,
    >(
        &self,
        request: &R,
        tracker: Option<&RequestTracker>,
    ) -> Result<(PreprocessedRequest, HashMap<String, String>, bool)> {
        let (request, annotations, prompt_injected_reasoning, _image_tokens) = self
            .preprocess_request_with_options(
                request,
                tracker,
                PreprocessRequestOptions::default(),
                None,
            )
            .await?;
        Ok((request, annotations, prompt_injected_reasoning))
    }

    async fn preprocess_request_with_options<
        R: OAIChatLikeRequest
            + MediaRequestExt
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider
            + CommonExtProvider,
    >(
        &self,
        request: &R,
        tracker: Option<&RequestTracker>,
        options: PreprocessRequestOptions,
        lora_name: Option<String>,
    ) -> Result<(
        PreprocessedRequest,
        HashMap<String, String>,
        bool,
        Option<usize>,
    )> {
        let _stage_guard = StageGuard::new(STAGE_PREPROCESS, "");
        let preprocess_start = Instant::now();
        let mut builder = self.builder_with_lora(request, lora_name)?;

        let template_start = Instant::now();
        let formatted_prompt = {
            let _nvtx = dynamo_nvtx_range!("preprocess.template");
            self.apply_template(request)
                .with_context(|| "Failed to apply prompt template")?
        };
        TEMPLATE_SECONDS.observe(template_start.elapsed().as_secs_f64());

        // Generic reasoning parsers start from `<think>`; MiniMax M3 starts
        // from `<mm:think>`. If the chat template injected that opener at the
        // end of the prompt, the model completion starts mid-reasoning.
        let prompt_injected_reasoning = Self::prompt_injected_reasoning_start(
            self.runtime_config.reasoning_parser.as_deref(),
            formatted_prompt.as_ref().map(RenderedPrompt::as_str),
        );

        let tokenize_start = Instant::now();
        let (token_ids, annotations) = {
            let _nvtx = dynamo_nvtx_range!("preprocess.tokenize");
            self.gather_tokens(request, formatted_prompt.as_ref(), tracker)
                .await
                .with_context(|| "Failed to gather tokens")?
        };
        TOKENIZE_SECONDS.observe(tokenize_start.elapsed().as_secs_f64());

        let (_mm_routing_entries, image_tokens) = self
            .gather_multi_modal_data_with_image_tokens(
                request,
                &mut builder,
                formatted_prompt.as_ref().map(RenderedPrompt::as_str),
                &token_ids,
            )
            .await
            .with_context(|| "Failed to gather multimodal data")?;

        // Install tokens on the builder. Done after MM routing built its
        // view so the routing-side borrow stays cheap and builder ownership
        // moves once.
        builder.token_ids(token_ids);

        STAGE_DURATION_SECONDS
            .with_label_values(&[STAGE_PREPROCESS])
            .observe(preprocess_start.elapsed().as_secs_f64());

        if let Some(nvext) = request.nvext()
            && let Some(router_params) = &nvext.router
        {
            builder.router(Some(router_params.clone()));
        }

        let mut preprocessed = builder.build()?;
        if let Some(reasoning_ended) = Self::prompt_injected_reasoning_ended_arg(
            self.runtime_config.reasoning_parser.as_deref(),
            formatted_prompt.as_ref().map(RenderedPrompt::as_str),
        ) {
            let extra_args = preprocessed
                .extra_args
                .get_or_insert_with(|| serde_json::json!({}));
            let extra_args = extra_args
                .as_object_mut()
                .context("preprocessed extra_args must be an object")?;
            extra_args.insert("reasoning_ended".to_string(), reasoning_ended.into());
        }

        // If omitted, allow generation up to the remaining context length. Responses requests
        // preserve omission so backend adapters can compute the dynamic cap from their
        // effective prompt length/tokenization.
        //
        // Multimodal `token_ids` carry unexpanded image placeholders, so prefer
        // the MM-expanded length when available, else defer to the backend.
        let exact_prompt_len =
            Self::validate_preprocessed_token_budget(&preprocessed, self.token_budget.as_ref())?;
        if preprocessed.stop_conditions.max_tokens.is_none()
            && let Some(prompt_len) = exact_prompt_len
            // Preserve omission when the prompt itself is backend-owned. In
            // particular, setting a saturating zero here would interfere with
            // SGLang's auto-truncation before the backend sees the request.
            && !self.token_budget.is_some_and(|token_budget| {
                prompt_len >= token_budget.combined_limit as usize
                    && !token_budget.reject_prompt_overflow
            })
            && let Some(max_tokens) = Self::omitted_max_tokens_default(
                prompt_len,
                self.token_budget
                    .map(|token_budget| token_budget.combined_limit),
                options,
            )
        {
            preprocessed.stop_conditions.max_tokens = Some(max_tokens);
            // A strict limit may be smaller than the raw context window because
            // the engine reserves tokens. Revalidate the derived budget so an
            // already-over-limit prompt fails before streaming begins.
            Self::validate_preprocessed_token_budget(&preprocessed, self.token_budget.as_ref())?;
        }

        Ok((
            preprocessed,
            annotations,
            prompt_injected_reasoning,
            image_tokens,
        ))
    }

    pub fn builder<
        R: OAIChatLikeRequest
            + MediaRequestExt
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider,
    >(
        &self,
        request: &R,
    ) -> Result<PreprocessedRequestBuilder> {
        self.builder_with_lora(request, None)
    }

    fn builder_with_lora<
        R: OAIChatLikeRequest
            + MediaRequestExt
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider,
    >(
        &self,
        request: &R,
        lora_name_override: Option<String>,
    ) -> Result<PreprocessedRequestBuilder> {
        let mut builder = PreprocessedRequest::builder();
        builder.model(request.model());

        let mut stop_conditions = request.extract_stop_conditions()?;
        let eos_token_ids = self.model_info.eos_token_ids();
        let hidden_eos_token_ids = eos_token_ids.clone();
        if let Some(stop_tokens) = &mut stop_conditions.stop_token_ids_hidden {
            for eos_token_id in hidden_eos_token_ids {
                if !stop_tokens.contains(&eos_token_id) {
                    stop_tokens.push(eos_token_id);
                }
            }
        } else {
            stop_conditions.stop_token_ids_hidden = Some(hidden_eos_token_ids);
        }
        // Some tool-call parsers terminate on a token that is also a model
        // EOS (e.g. Harmony's `<|call|>` for gpt-oss). Left in the hidden
        // set, the engine stops AND strips it, so the parser sees a
        // truncated envelope and drops the call. Move such tokens to the
        // visible set so the engine still stops on them but the token
        // survives into output for the parser to consume. See PR #9778.
        let mut visible_tool_parser_end_token_ids = Vec::new();
        if let Some(stop_tokens) = &mut stop_conditions.stop_token_ids_hidden {
            visible_tool_parser_end_token_ids =
                self.remove_tool_parser_end_tokens_from_hidden_stops(request, stop_tokens)?;
        }
        if !visible_tool_parser_end_token_ids.is_empty() {
            let visible_stops = stop_conditions
                .stop_token_ids_visible
                .get_or_insert_with(Vec::new);
            for token_id in visible_tool_parser_end_token_ids {
                if !visible_stops.contains(&token_id) {
                    visible_stops.push(token_id);
                }
            }
        }

        // apply ignore eos if not already set
        stop_conditions.apply_ignore_eos();

        if !stop_conditions.ignore_eos.unwrap_or(false) {
            builder.eos_token_ids(eos_token_ids);
        }

        builder.stop_conditions(stop_conditions);
        builder.sampling_options(request.extract_sampling_options()?);

        // Some parsers rely on `<|tool_call>`, `<|channel>`, etc. being
        // visible in the decoded text. The default `skip_special_tokens=true`
        // strips them and silently bypasses parsing. Mirror upstream's
        // per-parser `adjust_request` hook by flipping the default to false
        // for parsers that need special tokens preserved, unless the caller
        // has explicitly set `skip_special_tokens`.
        let mut output_options = request.extract_output_options()?;
        if output_options.skip_special_tokens.is_none()
            && Self::parser_requires_special_tokens(
                self.tool_call_parser.as_deref(),
                self.runtime_config.reasoning_parser.as_deref(),
            )
        {
            output_options.skip_special_tokens = Some(false);
        } else if Self::special_tokens_will_be_stripped(
            output_options.skip_special_tokens,
            self.tool_call_parser.as_deref(),
            self.runtime_config.reasoning_parser.as_deref(),
        ) {
            // Caller forced `skip_special_tokens=true` while a special-token-
            // dependent parser is active. The engine's markers (e.g. harmony
            // `<|channel|>` / `<|message|>`) get stripped before the parser
            // runs, so tool_calls / reasoning_content come back empty and the
            // markup leaks into `content`. Warn once: this is a silent,
            // deterministic correctness loss that no parser fixture can catch.
            static WARNED: std::sync::Once = std::sync::Once::new();
            WARNED.call_once(|| {
                tracing::warn!(
                    tool_call_parser = ?self.tool_call_parser,
                    reasoning_parser = ?self.runtime_config.reasoning_parser,
                    "skip_special_tokens=true requested while a special-token-dependent parser is active; the engine's special tokens will be stripped before parsing, so tool_calls/reasoning_content will be empty and the markup will leak into content. Unset skip_special_tokens (Dynamo defaults it to false for these parsers) or set it to false."
                );
            });
        }
        builder.output_options(output_options);
        builder.annotations(request.annotations().unwrap_or_default());
        builder.mdc_sum(Some(self.mdcsum.clone()));
        let lora_name = self.lora_name.clone().or(lora_name_override);
        let cache_namespace = request_cache_salt(request).map(str::to_owned);

        // Extract routing hints from nvext if present
        if let Some(nvext) = request.nvext() {
            // Build routing hints from nvext fields
            let hints = nvext.agent_hints.as_ref();
            let (priority_jump, strict_priority, priority) = routing_priorities(hints);
            builder.request_timestamp_ms(nvext.request_timestamp_ms);
            let routing = RoutingHints {
                backend_instance_id: nvext.backend_instance_id,
                prefill_worker_id: nvext.prefill_worker_id,
                decode_worker_id: nvext.decode_worker_id,
                dp_rank: nvext.dp_rank,
                prefill_dp_rank: nvext.prefill_dp_rank,
                expected_output_tokens: hints.and_then(|h| h.osl),
                priority_jump,
                strict_priority,
                priority,
                lora_name,
                cache_namespace: cache_namespace.clone(),
                allowed_worker_ids: None,
                routing_constraints: nvext
                    .routing_constraints
                    .clone()
                    .map(routing_constraints_to_kv),
            };
            builder.routing(Some(routing));
        } else if lora_name.is_some() || cache_namespace.is_some() {
            // Ensure routing hints exist when we have LoRA or a legacy
            // top-level cache_salt, even when nvext is absent.
            builder.routing(Some(RoutingHints {
                lora_name,
                cache_namespace,
                ..Default::default()
            }));
        }

        if let Some(extra_args) = Self::backend_extra_args(
            request,
            self.runtime_config.reasoning_parser.is_some(),
            None,
        ) {
            builder.extra_args(Some(extra_args));
        }

        // SGLang needs this request-scoped signal in addition to its native
        // reasoning parser so guided JSON starts after the reasoning boundary.
        builder.require_reasoning(Self::guided_output_requires_reasoning(
            request,
            self.runtime_config.reasoning_parser.as_deref(),
        ));

        // Forward mm_processor_kwargs (e.g. use_audio_in_video) to the backend.
        builder.mm_processor_kwargs(request.mm_processor_kwargs().cloned());

        // Forward media_io_kwargs untouched only when the worker owns decoding. With a
        // media loader the frontend consumes them itself, so re-sending would risk the
        // worker applying them a second time.
        if self.media_loader.is_none() {
            builder.media_io_kwargs(request.media_io_kwargs().cloned());
        }

        Ok(builder)
    }

    fn remove_tool_parser_end_tokens_from_hidden_stops<R: OAIChatLikeRequest>(
        &self,
        request: &R,
        hidden_stop_token_ids: &mut Vec<TokenIdType>,
    ) -> Result<Vec<TokenIdType>> {
        let has_tools = request
            .tools()
            .as_ref()
            .and_then(|tools| tools.len())
            .is_some_and(|len| len > 0);
        let tool_choice_none = request
            .tool_choice()
            .as_ref()
            .and_then(|tool_choice| tool_choice.as_str())
            == Some("none");

        if !Self::should_keep_tool_parser_end_tokens_visible(has_tools, tool_choice_none) {
            return Ok(Vec::new());
        }

        let Some(tool_call_parser) = self.tool_call_parser.as_deref().filter(|p| !p.is_empty())
        else {
            return Ok(Vec::new());
        };
        let Some(tool_call_config) = get_tool_parser_map().get(tool_call_parser) else {
            return Ok(Vec::new());
        };

        let mut visible_stop_token_ids = Vec::new();
        for end_token in tool_call_config.parser_config.tool_call_end_tokens() {
            if end_token.is_empty() {
                continue;
            }
            let encoded = self.tokenizer.encode(&end_token).with_context(|| {
                format!(
                    "Failed to encode tool-call end token {end_token:?} for parser {tool_call_parser:?}"
                )
            })?;
            let was_hidden_eos =
                Self::remove_single_token_marker(hidden_stop_token_ids, encoded.token_ids());
            if !was_hidden_eos {
                tracing::debug!(
                    token_ids = ?encoded.token_ids(),
                    end_token,
                    parser = tool_call_parser,
                    "Tool-call end token was not a single hidden EOS token"
                );
                continue;
            }
            if let [token_id] = encoded.token_ids()
                && !visible_stop_token_ids.contains(token_id)
            {
                visible_stop_token_ids.push(*token_id);
            }
        }

        Ok(visible_stop_token_ids)
    }

    fn should_keep_tool_parser_end_tokens_visible(has_tools: bool, tool_choice_none: bool) -> bool {
        has_tools && !tool_choice_none
    }

    fn remove_single_token_marker(
        hidden_eos_token_ids: &mut Vec<TokenIdType>,
        marker_token_ids: &[TokenIdType],
    ) -> bool {
        let [marker_token_id] = marker_token_ids else {
            return false;
        };
        let before = hidden_eos_token_ids.len();
        hidden_eos_token_ids.retain(|token_id| token_id != marker_token_id);
        hidden_eos_token_ids.len() != before
    }

    /// Rendering is driven by the request, so its failures are reported as 400 rather than
    /// 500, matching vLLM. A misconfigured template can also fail here, for instance a
    /// `chat_template` map that omits the `tool_use` key, so log the cause chain before it
    /// is flattened into the client-facing message.
    fn map_prompt_render_error(error: anyhow::Error) -> anyhow::Error {
        tracing::debug!(?error, "Chat template rendering failed");
        let message = match error.downcast_ref::<PromptRenderError>() {
            Some(PromptRenderError::InvalidRequest(message)) => message.clone(),
            None => format!("{error:#}"),
        };
        invalid_argument_error(message)
    }

    pub fn apply_template<
        R: OAIChatLikeRequest
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider
            + CommonExtProvider,
    >(
        &self,
        request: &R,
    ) -> Result<Option<RenderedPrompt>> {
        let continue_final = request.get_continue_final_message() == Some(true);
        let formatted_prompt = if self.normalize_tool_call_args || continue_final {
            self.apply_template_inner(&NormalizedArgsRequest {
                inner: request,
                normalize_tool_call_args: self.normalize_tool_call_args,
                continue_final_message: continue_final,
            })?
        } else {
            self.apply_template_inner(request)?
        };
        let Some(prompt) = formatted_prompt else {
            return Ok(None);
        };
        if !continue_final {
            return Ok(Some(prompt));
        }
        apply_continue_final_message(prompt)
            .map_err(|error| invalid_argument_error(format!("{error:#}")))
            .map(Some)
    }

    fn apply_template_inner<
        R: OAIChatLikeRequest
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider,
    >(
        &self,
        request: &R,
    ) -> Result<Option<RenderedPrompt>> {
        if let PromptInput::Text(_) = request.prompt_input_type()
            && let Some(TextInput::Single(_)) = request.extract_text()
        {
            let use_raw_prompt = request
                .nvext()
                .is_some_and(|ext| ext.use_raw_prompt.unwrap_or(false));

            let formatted_prompt = if use_raw_prompt {
                match request.raw_prompt() {
                    Some(prompt) => RenderedPrompt::text(prompt),
                    None => {
                        tracing::warn!("Raw prompt requested but not available");
                        self.formatter
                            .render_prompt(request)
                            .map_err(Self::map_prompt_render_error)?
                    }
                }
            } else {
                self.formatter
                    .render_prompt(request)
                    .map_err(Self::map_prompt_render_error)?
            };
            Ok(Some(formatted_prompt))
        } else {
            Ok(None)
        }
    }

    /// Replace inline `data:` URLs with empty strings in message content parts.
    /// Preserves HTTP(S) URLs, text content, and overall message structure.
    fn strip_inline_data_urls(messages: &mut serde_json::Value) {
        let Some(arr) = messages.as_array_mut() else {
            return;
        };
        for msg in arr {
            let Some(content) = msg.get_mut("content") else {
                continue;
            };
            let Some(parts) = content.as_array_mut() else {
                continue;
            };
            for part in parts {
                for key in ["image_url", "video_url", "audio_url"] {
                    if let Some(media) = part.get_mut(key)
                        && let Some(url) = media.get_mut("url")
                        && url.as_str().is_some_and(|s| s.starts_with("data:"))
                    {
                        *url = serde_json::Value::String(String::new());
                    }
                }
            }
        }
    }

    fn replace_reserved_media_slot(
        media_map: &mut MultimodalDataMap,
        modality: &str,
        slot_idx: usize,
        value: MultimodalData,
    ) -> Result<()> {
        let slot = media_map
            .get_mut(modality)
            .and_then(|slots| slots.get_mut(slot_idx))
            .with_context(|| {
                format!(
                    "missing reserved multimodal slot {modality}[{slot_idx}] during media decode"
                )
            })?;
        *slot = value;
        Ok(())
    }

    pub async fn gather_multi_modal_data<
        R: OAIChatLikeRequest + MediaRequestExt + NvExtProvider,
    >(
        &self,
        request: &R,
        builder: &mut PreprocessedRequestBuilder,
        formatted_prompt: Option<&str>,
        // Worker-bound token ids; used (mm-routing only) to build the exact
        // routing sequence and atomically gate worker `mm_hashes`.
        token_ids: &[crate::protocols::TokenIdType],
    ) -> Result<Vec<MmImageEntry>> {
        let (entries, _image_tokens) = self
            .gather_multi_modal_data_with_image_tokens(
                request,
                builder,
                formatted_prompt,
                token_ids,
            )
            .await?;
        Ok(entries
            .into_iter()
            .filter_map(|entry| match entry {
                MmRoutingEntry::Image {
                    mm_hash,
                    width,
                    height,
                } => Some(MmImageEntry {
                    mm_hash,
                    width,
                    height,
                }),
                MmRoutingEntry::Video { .. } => None,
            })
            .collect())
    }

    async fn gather_multi_modal_data_with_image_tokens<
        R: OAIChatLikeRequest + MediaRequestExt + NvExtProvider,
    >(
        &self,
        request: &R,
        builder: &mut PreprocessedRequestBuilder,
        formatted_prompt: Option<&str>,
        token_ids: &[crate::protocols::TokenIdType],
    ) -> Result<(Vec<MmRoutingEntry>, Option<usize>)> {
        // `token_ids` is only consumed by exact MM-routing construction below.
        #[cfg(not(feature = "mm-routing"))]
        let _ = token_ids;

        let mut media_map: MultimodalDataMap = HashMap::new();
        let mut uuid_map: MultimodalUuidMap = HashMap::new();
        let mut has_user_uuid = false;
        // Decoded results are written back into these reserved modality slots so
        // URL-backed and UUID-only inputs retain request order.
        let mut fetch_tasks: Vec<MediaFetchTask<'_>> = Vec::new();
        #[cfg(feature = "mm-routing")]
        let mut mm_routing_entries: Vec<MmRoutingEntry> = Vec::new();
        // Private per-request total for frontend metrics. `None` means the SMG
        // counter is unavailable or checked addition overflowed.
        #[cfg(feature = "mm-routing")]
        let mut image_tokens = self.image_token_counter.as_ref().map(|_| 0usize);
        // A raw/passthrough video or unsupported decoded-video processor makes
        // the model-visible token sequence unknowable. In that case the whole
        // request falls back rather than publishing a partial routing view.
        #[cfg(feature = "mm-routing")]
        let mut exact_mm_routing_eligible = true;
        // Total `image_url` content parts in the request. Bumped at every
        // image part regardless of which fetch path handles it. Used at
        // hash forwarding time: if fewer image entries were resolved, we omit
        // exact routing hashes for the whole request rather than
        // ship a partial / misaligned UUID list to vLLM.
        //
        // The mismatch is only reachable on the URL-passthrough path when
        // there is no media loader. Each recoverable `fetch_image_dims_uncached`
        // failure logs a warning and skips its `mm_image_entries.push`.
        // Security-policy failures remain terminal. The decoded path
        // (`has_media_loader`) propagates any fetch failure via `?`.
        #[cfg(feature = "mm-routing")]
        let mut total_image_count: usize = 0;
        // For the URL-passthrough case (media_loader is None) we collect image
        // URLs here and resolve dims via header-only HTTP after the loop so we
        // can issue all fetches in parallel.
        #[cfg(feature = "mm-routing")]
        let mut url_passthrough_images: Vec<(u64, String)> = Vec::new();

        let Some(messages) = request.typed_messages() else {
            return Ok((Vec::new(), None));
        };
        let has_media_loader = self.media_loader.is_some();

        for message in messages.iter() {
            let Some(content_parts) = multimodal_content_parts(message) else {
                continue;
            };
            for content_part in content_parts {
                let Some((type_str, url, uuid)) = content_part.media_info() else {
                    continue;
                };

                if type_str != "image_url" && uuid.is_some() {
                    return Err(invalid_argument_error(
                        "multimodal cache UUIDs are supported only for image_url parts with vLLM",
                    ));
                }

                #[cfg(feature = "mm-routing")]
                if type_str == "image_url" {
                    total_image_count += 1;
                }
                #[cfg(feature = "mm-routing")]
                if !exact_mm_routing_supports_modality(type_str, has_media_loader) {
                    exact_mm_routing_eligible = false;
                }

                if uuid.as_deref().is_some_and(str::is_empty) {
                    return Err(invalid_argument_error(format!(
                        "{type_str} uuid must be a non-empty string"
                    )));
                }

                let slots = media_map.entry(type_str.to_string()).or_default();
                let slot_idx = slots.len();
                has_user_uuid |= uuid.is_some();
                if type_str == "image_url" {
                    uuid_map
                        .entry(type_str.to_string())
                        .or_default()
                        .push(uuid.clone());
                }

                match (url, uuid) {
                    (Some(url), _) => {
                        if has_media_loader {
                            fetch_tasks.push(MediaFetchTask {
                                modality: type_str,
                                slot_idx,
                                content_part: content_part.as_user(),
                            });
                        } else {
                            #[cfg(feature = "mm-routing")]
                            if type_str == "image_url" {
                                let mm_hash = Self::hash_image_url(url.as_str());
                                url_passthrough_images.push((mm_hash, url.as_str().to_string()));
                            }
                        }
                        slots.push(MultimodalData::Url(url));
                    }
                    (None, Some(uuid)) => {
                        slots.push(MultimodalData::UuidOnly(uuid));
                    }
                    (None, None) => {
                        return Err(invalid_argument_error(format!(
                            "{type_str} part has neither `url` nor `uuid`; at least one is required"
                        )));
                    }
                }
            }
        }

        #[cfg(feature = "mm-routing")]
        let has_processor_override = has_mm_processor_override(request.mm_processor_kwargs());
        #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
        let hash_decoded_video = should_hash_decoded_video(
            exact_mm_routing_eligible,
            has_user_uuid,
            has_processor_override,
            self.video_routing_processor.is_some(),
        );
        #[cfg(not(all(feature = "mm-routing", feature = "media-ffmpeg")))]
        let hash_decoded_video = false;

        // Execute all fetch tasks
        if !fetch_tasks.is_empty() {
            let loader = self.media_loader.as_ref().unwrap();
            // The frontend owns decoding here, so the opaque request kwargs are parsed
            // into the decoder config -- borrowing the `Value`, no clone. Mapped to
            // InvalidArgument so a malformed payload stays a 400 rather than a 500.
            let media_io_kwargs = request
                .media_io_kwargs()
                .map(<MediaDecoder as serde::Deserialize>::deserialize)
                .transpose()
                .map_err(|e| invalid_argument_error(format!("invalid media_io_kwargs: {e}")))?;
            let results = futures::future::join_all(fetch_tasks.iter().map(|task| {
                loader.fetch_and_decode_media_part_with_video_hash(
                    task.content_part.as_ref(),
                    media_io_kwargs.as_ref(),
                    hash_decoded_video,
                )
            }))
            .await;

            for (task, result) in fetch_tasks.into_iter().zip(results) {
                // if one item fails, errors the whole request, other items will be cleaned up by Drop
                let rdma_descriptor = result?;

                #[cfg(feature = "mm-routing")]
                if task.modality == "image_url" {
                    let shape = &rdma_descriptor.tensor_info.shape;
                    if shape.len() >= 2 {
                        let h = shape[0] as u32;
                        let w = shape[1] as u32;
                        // Frontend-decode path: hash the decoded RGB bytes so
                        // the same image reached via different (signed) URLs
                        // collides on the same `mm_hash` and routes to the
                        // worker that already has those KV blocks. Fall back
                        // to URL hashing only if the descriptor lost local
                        // storage (e.g. reconstructed from the wire), which
                        // shouldn't happen on the frontend.
                        let (mm_hash, hash_source) = match rdma_descriptor.content_hash() {
                            Some(h) => (h, "decoded_bytes"),
                            None => {
                                let source_url = image_content_part_url(task.content_part.as_ref())
                                    .ok_or_else(|| {
                                        invalid_argument_error(
                                            "image_url task must contain an image URL",
                                        )
                                    })?;
                                (Self::hash_image_url(source_url), "url_fallback")
                            }
                        };
                        if let Some(counter) = self.image_token_counter.as_ref() {
                            let n = counter.count_tokens(w, h);
                            tracing::debug!(
                                target: "mm_routing",
                                model = counter.model_id(),
                                width = w,
                                height = h,
                                tokens = n,
                                mm_hash = mm_hash,
                                source = hash_source,
                                "image-token count"
                            );
                            image_tokens = checked_add_image_tokens(image_tokens, n);
                        }
                        mm_routing_entries.push(MmRoutingEntry::Image {
                            mm_hash,
                            width: w,
                            height: h,
                        });
                    }
                } else if task.modality == "video_url" {
                    #[cfg(feature = "media-ffmpeg")]
                    {
                        let video_entry = (|| -> Result<MmRoutingEntry> {
                            let processor =
                                self.video_routing_processor.as_ref().ok_or_else(|| {
                                    anyhow::anyhow!("model has no exact video routing processor")
                                })?;
                            anyhow::ensure!(
                                !has_processor_override,
                                "request mm_processor_kwargs can change the video token layout"
                            );
                            let (frame_count, width, height) =
                                rdma_descriptor.video_dimensions()?;
                            let metadata = rdma_descriptor.video_metadata()?;
                            let mm_hash = rdma_descriptor.video_content_hash()?;
                            let routing =
                                processor.build_replacement(&mm_routing::VideoRoutingInput {
                                    frame_count,
                                    width,
                                    height,
                                    source_fps: metadata.source_fps,
                                    sampled_timestamps: &metadata.sampled_timestamps,
                                })?;
                            tracing::debug!(
                                target: "mm_routing",
                                n_frames = frame_count,
                                width,
                                height,
                                replacement_tokens = routing.replacement_tokens.len(),
                                mm_hash,
                                "video routing metadata resolved"
                            );
                            Ok(MmRoutingEntry::Video {
                                mm_hash,
                                placeholder_token_id: routing.placeholder_token_id,
                                target_tokens: routing.target_tokens,
                                replacement_tokens: routing.replacement_tokens,
                            })
                        })();
                        match video_entry {
                            Ok(entry) => mm_routing_entries.push(entry),
                            Err(error) => {
                                exact_mm_routing_eligible = false;
                                tracing::debug!(
                                    target: "mm_routing",
                                    %error,
                                    "mm-routing: decoded video is not eligible for exact routing; falling back to text-prefix routing"
                                );
                            }
                        }
                    }
                    #[cfg(not(feature = "media-ffmpeg"))]
                    {
                        exact_mm_routing_eligible = false;
                    }
                }

                Self::replace_reserved_media_slot(
                    &mut media_map,
                    task.modality,
                    task.slot_idx,
                    MultimodalData::Decoded(rdma_descriptor),
                )?;
            }
        }

        // URL-passthrough path (media_loader is None): fetch image headers in
        // parallel to get (W, H) per image without downloading the full bytes.
        // Enables MM-aware routing for backends that register
        // `media_decoder: null` and decode images on the worker.
        #[cfg(feature = "mm-routing")]
        if !has_user_uuid && !url_passthrough_images.is_empty() {
            let dim_results =
                futures::future::join_all(url_passthrough_images.iter().map(|(mm_hash, url)| {
                    Self::fetch_image_dims(*mm_hash, url, self.routing_image_dimension_policy)
                }))
                .await;
            for ((mm_hash, url), dim_res) in url_passthrough_images.into_iter().zip(dim_results) {
                match dim_res {
                    Ok((w, h)) => {
                        if let Some(counter) = self.image_token_counter.as_ref() {
                            let n = counter.count_tokens(w, h);
                            tracing::debug!(
                                target: "mm_routing",
                                model = counter.model_id(),
                                width = w,
                                height = h,
                                tokens = n,
                                mm_hash = mm_hash,
                                source = "url_passthrough_header_fetch",
                                "image-token count"
                            );
                            image_tokens = checked_add_image_tokens(image_tokens, n);
                        }
                        mm_routing_entries.push(MmRoutingEntry::Image {
                            mm_hash,
                            width: w,
                            height: h,
                        });
                    }
                    Err(e) => {
                        if MediaFetcher::is_policy_rejection(&e) {
                            return Err(e);
                        }
                        // Redact `data:` URIs to just the media-type prefix —
                        // the comma-separated payload is the entire (base64)
                        // image body and ships in logs would be log bloat /
                        // potential PII spillage if logs are aggregated.
                        let url_for_log = if url.starts_with("data:") {
                            url.split_once(',')
                                .map(|(p, _)| format!("{p},<redacted>"))
                                .unwrap_or_else(|| "data:<redacted>".to_string())
                        } else {
                            url.to_string()
                        };
                        tracing::warn!(
                            target: "mm_routing",
                            url = %url_for_log,
                            error = %e,
                            "mm-routing: failed to fetch image dims; MM routing entry skipped"
                        );
                    }
                }
            }
        }

        if !media_map.is_empty() {
            builder.multi_modal_data(Some(media_map));
            if has_user_uuid {
                builder.multi_modal_uuids(Some(uuid_map));
            }

            // User cache identities are opaque and cannot be converted into the
            // router's canonical image hashes. Fall back to text-prefix routing
            // instead of routing and publishing under different cache keys.
            #[cfg(feature = "mm-routing")]
            if has_user_uuid {
                mm_routing_entries.clear();
            }

            // Preserve original messages and formatted prompt in extra_args for multimodal
            // workers (e.g., TRT-LLM needs messages and the template-rendered prompt with
            // <image> placeholders for embedding-path / NIXL flows).
            let messages_json = serde_json::to_value(request.messages())?;
            let mut extra_args = serde_json::json!({
                "messages": messages_json
            });

            // Strip redundant inline data: URLs only when frontend decoding is active
            // (media_loader decoded the images into RDMA descriptors). TRT-LLM and
            // other backends that pass URLs through still need the original data: URIs.
            if self.media_loader.is_some() {
                Self::strip_inline_data_urls(&mut extra_args["messages"]);
            }

            if let Some(prompt) = formatted_prompt {
                // Clone here is the single owned allocation we actually need:
                // the prompt is inserted into the request's `extra_args` JSON.
                // The caller still holds the original `String`; passing
                // `Option<&str>` keeps text-only requests (no MM) clone-free.
                extra_args["formatted_prompt"] = serde_json::Value::String(prompt.to_string());
            }

            if let Some(serde_json::Value::Object(backend_extra_args)) = Self::backend_extra_args(
                request,
                self.runtime_config.reasoning_parser.is_some(),
                Self::prompt_injected_reasoning_ended_arg(
                    self.runtime_config.reasoning_parser.as_deref(),
                    formatted_prompt,
                ),
            ) {
                let extra_args_obj = extra_args
                    .as_object_mut()
                    .expect("multimodal extra_args must be an object");
                extra_args_obj.extend(backend_extra_args);
            }

            // Build and install routing info + worker hashes atomically. If any
            // mixed-media precondition misses, neither side receives exact keys
            // and the request cleanly uses text-prefix routing.
            #[cfg(feature = "mm-routing")]
            let resolved_image_count = mm_routing_entries
                .iter()
                .filter(|entry| matches!(entry, MmRoutingEntry::Image { .. }))
                .count();
            #[cfg(feature = "mm-routing")]
            let mm_routing_info = if exact_mm_routing_eligible
                && exact_mm_routing_preconditions_met(
                    has_user_uuid,
                    resolved_image_count,
                    total_image_count,
                    has_processor_override,
                ) {
                self.build_mm_exact_routing_info(&mm_routing_entries, token_ids)
            } else {
                None
            };
            #[cfg(feature = "mm-routing")]
            if let Some(mm_routing_info) = mm_routing_info {
                let hex = |entry: &MmRoutingEntry| {
                    serde_json::Value::String(format!("{:016x}", entry.mm_hash()))
                };
                if mm_routing_entries
                    .iter()
                    .all(|entry| matches!(entry, MmRoutingEntry::Image { .. }))
                {
                    // Preserve the legacy image-only worker protocol.
                    extra_args["mm_hashes"] =
                        serde_json::Value::Array(mm_routing_entries.iter().map(hex).collect());
                } else {
                    let mut grouped = serde_json::Map::new();
                    let image_hashes: Vec<_> = mm_routing_entries
                        .iter()
                        .filter(|entry| matches!(entry, MmRoutingEntry::Image { .. }))
                        .map(hex)
                        .collect();
                    let video_hashes: Vec<_> = mm_routing_entries
                        .iter()
                        .filter(|entry| matches!(entry, MmRoutingEntry::Video { .. }))
                        .map(hex)
                        .collect();
                    if !image_hashes.is_empty() {
                        grouped.insert("image".to_string(), serde_json::Value::Array(image_hashes));
                    }
                    if !video_hashes.is_empty() {
                        grouped.insert("video".to_string(), serde_json::Value::Array(video_hashes));
                    }
                    extra_args["mm_hashes_by_modality"] = serde_json::Value::Object(grouped);
                }
                builder.mm_routing_info(Some(mm_routing_info));
            } else if has_processor_override && total_image_count > 0 {
                tracing::debug!(
                    target: "mm_routing",
                    "mm-routing: exact MM routing disabled because mm_processor_kwargs is non-empty"
                );
            } else if !mm_routing_entries.is_empty() {
                tracing::warn!(
                    target: "mm_routing",
                    resolved = mm_routing_entries.len(),
                    expected_images = total_image_count,
                    "mm-routing: exact MM routing info not built (media resolution or placeholder-order mismatch); skipping mm_hashes forwarding"
                );
            }

            builder.extra_args(Some(extra_args));
        }

        #[cfg(feature = "mm-routing")]
        let image_tokens = aggregate_image_tokens(
            image_tokens,
            mm_routing_entries
                .iter()
                .filter(|entry| matches!(entry, MmRoutingEntry::Image { .. }))
                .count(),
            total_image_count,
            has_processor_override,
        );
        #[cfg(feature = "mm-routing")]
        return Ok((mm_routing_entries, image_tokens));
        #[cfg(not(feature = "mm-routing"))]
        Ok((Vec::new(), None))
    }

    /// Build image-only exact routing info without changing the worker-bound
    /// token IDs. Kept as the public compatibility surface; request
    /// preprocessing uses the mixed-media builder internally.
    #[cfg(feature = "mm-routing")]
    pub fn gather_mm_exact_routing_info(
        &self,
        builder: &mut PreprocessedRequestBuilder,
        image_entries: &[MmImageEntry],
        token_ids: &[crate::protocols::TokenIdType],
    ) -> Result<()> {
        let entries: Vec<_> = image_entries
            .iter()
            .map(|entry| MmRoutingEntry::Image {
                mm_hash: entry.mm_hash,
                width: entry.width,
                height: entry.height,
            })
            .collect();
        if let Some(info) = self.build_mm_exact_routing_info(&entries, token_ids) {
            builder.mm_routing_info(Some(info));
        }
        Ok(())
    }

    #[cfg(feature = "mm-routing")]
    fn build_mm_exact_routing_info(
        &self,
        entries: &[MmRoutingEntry],
        token_ids: &[crate::protocols::TokenIdType],
    ) -> Option<crate::protocols::common::preprocessor::MmRoutingInfo> {
        use crate::protocols::common::preprocessor::MmRoutingInfo;

        if entries.is_empty() {
            return None;
        }
        if !exact_mm_routing_entries_are_unambiguous(entries) {
            tracing::debug!(
                target: "mm_routing",
                "consecutive video objects cannot be mapped exactly in vLLM KV events; skipping MM routing info"
            );
            return None;
        }
        let image_token_id = self.routing_image_token_id;
        let image_counter_required = entries
            .iter()
            .any(|entry| matches!(entry, MmRoutingEntry::Image { .. }));
        if image_counter_required && self.image_token_counter.is_none() {
            tracing::debug!(
                target: "mm_routing",
                "image_token_counter unavailable; skipping MM routing info"
            );
            return None;
        }
        if image_counter_required && image_token_id.is_none() {
            tracing::debug!(
                target: "mm_routing",
                "routing_image_token_id unresolved; skipping MM routing info"
            );
            return None;
        }
        if image_counter_required && self.routing_image_prompt_layout.is_none() {
            tracing::debug!(
                target: "mm_routing",
                "routing_image_prompt_layout unresolved; skipping MM routing info"
            );
            return None;
        }
        let block_size = self.kv_cache_block_size;
        if block_size == 0 {
            tracing::debug!(
                target: "mm_routing",
                "kv_cache_block_size is 0; skipping MM routing info"
            );
            return None;
        }
        let (mut expanded, expanded_prompt_len, block_mm_infos) = if entries
            .iter()
            .all(|entry| matches!(entry, MmRoutingEntry::Image { .. }))
        {
            let counter = self
                .image_token_counter
                .as_ref()
                .expect("image counter requirement checked above");
            let images: Vec<MmImageEntry> = entries
                .iter()
                .map(|entry| match entry {
                    MmRoutingEntry::Image {
                        mm_hash,
                        width,
                        height,
                    } => MmImageEntry {
                        mm_hash: *mm_hash,
                        width: *width,
                        height: *height,
                    },
                    MmRoutingEntry::Video { .. } => unreachable!("all entries checked as images"),
                })
                .collect();
            let image_token_id = image_token_id.expect("image token requirement checked above");
            let placeholder_count = token_ids
                .iter()
                .filter(|&&token_id| token_id == image_token_id)
                .count();
            if placeholder_count != images.len() {
                tracing::warn!(
                    target: "mm_routing",
                    placeholder_count,
                    image_count = images.len(),
                    routing_image_token_id = image_token_id,
                    "placeholder token count in tokenized prompt does not match image count; \
                     skipping MM routing info (text-prefix routing only)"
                );
                return None;
            }
            let n_tokens: Vec<usize> = images
                .iter()
                .map(|image| counter.count_tokens(image.width, image.height))
                .collect();
            let (expanded, expanded_prompt_len) = try_expand_mm_routing_tokens(
                self.tokenizer.as_ref(),
                self.routing_image_prompt_layout
                    .expect("image prompt layout requirement checked above"),
                self.routing_prepend_bos,
                image_token_id,
                &images,
                &n_tokens,
                token_ids,
                counter.model_id(),
            )?;
            (expanded, expanded_prompt_len, Vec::new())
        } else {
            let mut replacements = Vec::with_capacity(entries.len());
            let video_token_id = entries.iter().find_map(|entry| match entry {
                MmRoutingEntry::Video {
                    placeholder_token_id,
                    ..
                } => Some(*placeholder_token_id),
                MmRoutingEntry::Image { .. } => None,
            });
            for entry in entries {
                let replacement = match entry {
                    MmRoutingEntry::Image {
                        mm_hash,
                        width,
                        height,
                    } => {
                        let counter = self
                            .image_token_counter
                            .as_ref()
                            .expect("image counter requirement checked above");
                        let token_count = counter.count_tokens(*width, *height);
                        let mut routing_tokens = Vec::with_capacity(token_count);
                        let mut worker_tokens = Vec::with_capacity(token_count);
                        let image = MmImageEntry {
                            mm_hash: *mm_hash,
                            width: *width,
                            height: *height,
                        };
                        let layout = self
                            .routing_image_prompt_layout
                            .expect("image prompt layout requirement checked above");
                        let image_token_id =
                            image_token_id.expect("image token requirement checked above");
                        let result = append_mm_routing_replacement(
                            &mut routing_tokens,
                            self.tokenizer.as_ref(),
                            layout,
                            image,
                            token_count,
                        )
                        .and_then(|()| {
                            append_mm_routing_replacement_with_fill(
                                &mut worker_tokens,
                                self.tokenizer.as_ref(),
                                layout,
                                image,
                                token_count,
                                image_token_id,
                            )
                        });
                        if let Err(error) = result {
                            tracing::warn!(
                                target: "mm_routing",
                                model = counter.model_id(),
                                %error,
                                "routing-only image prompt expansion failed; skipping MM routing info"
                            );
                            return None;
                        }
                        TrackedMmRoutingReplacement {
                            mm_hash: *mm_hash,
                            target_tokens: vec![image_token_id],
                            worker_tokens,
                            routing_tokens,
                        }
                    }
                    MmRoutingEntry::Video {
                        mm_hash,
                        placeholder_token_id,
                        target_tokens,
                        replacement_tokens,
                    } => {
                        let fill_token =
                            dynamo_kv_router::protocols::pad_value_for_mm_hash(*mm_hash);
                        TrackedMmRoutingReplacement {
                            mm_hash: *mm_hash,
                            target_tokens: target_tokens.clone(),
                            worker_tokens: replacement_tokens.clone(),
                            routing_tokens: replacement_tokens
                                .iter()
                                .map(|replacement_id| {
                                    if *replacement_id == *placeholder_token_id {
                                        fill_token
                                    } else {
                                        *replacement_id
                                    }
                                })
                                .collect(),
                        }
                    }
                };
                replacements.push(replacement);
            }

            // Configured BOS is image-specific; video-only routing starts from
            // the frontend-tokenized prompt.
            let routing_bos =
                routing_bos_to_prepend(self.routing_prepend_bos, image_counter_required);
            match apply_tracked_mm_replacements(
                routing_bos,
                &replacements,
                token_ids,
                block_size,
                image_token_id,
                video_token_id,
            ) {
                Ok(expanded) => expanded,
                Err(error) => {
                    tracing::warn!(
                        target: "mm_routing",
                        media_count = entries.len(),
                        %error,
                        "placeholder token sequence does not match multimodal content order; \
                         skipping MM routing info (text-prefix routing only)"
                    );
                    return None;
                }
            }
        };

        // Pad to a whole multiple of kv_cache_block_size. The router's
        // compute_block_hash_for_seq only hashes whole blocks, so the partial
        // tail block doesn't influence routing either way; aligning the length
        // keeps our routing_token_ids and `block_mm_infos` agreeing on count.
        // `div_ceil` guarantees `total_tokens >= expanded.len()`, so resize
        // only ever grows.
        let total_tokens = expanded.len().div_ceil(block_size) * block_size;
        if expanded.len() < total_tokens {
            expanded.resize(total_tokens, 0);
        }

        // Exact blocks carry MM identity in pad-value tokens. Ambiguous
        // feature-span boundaries carry the same block metadata vLLM hashes.
        tracing::debug!(
            target: "mm_routing",
            n_media = entries.len(),
            block_size,
            total_tokens,
            "MmRoutingInfo built (exact, pad_value)"
        );

        Some(MmRoutingInfo {
            routing_token_ids: expanded,
            block_mm_infos,
            expanded_prompt_len,
        })
    }

    /// xxh3-64 of the raw URL bytes. Used as the routing `mm_hash` in the
    /// URL-passthrough path: two requests with byte-identical URLs route to
    /// the same worker, anything else routes independently.
    ///
    /// We deliberately do NOT strip cache-buster / signed-URL query
    /// parameters — a query string like `?v=2` could mean either "new
    /// cache-busted fetch of the same image" or "version 2 of a different
    /// image", and the URL alone doesn't tell us which. Keeping the hash
    /// URL-identical avoids the heuristic and the false-positive collisions
    /// that come with it. Workloads with rotating signed URLs (S3, GCS,
    /// Azure SAS) should use `--frontend-decoding`: that path hashes the
    /// decoded RGB bytes instead, so cross-URL cache reuse is restored
    /// without depending on URL conventions.
    #[cfg(feature = "mm-routing")]
    fn hash_image_url(url: &str) -> u64 {
        xxhash_rust::xxh3::xxh3_64(url.as_bytes())
    }

    /// Header-only image dim fetch. For HTTP/HTTPS we issue a Range request
    /// for the first 64 KB (covers PNG/WebP in <1 KB and JPEG SOF in worst
    /// case). For data: URIs we decode the base64 payload locally and parse
    /// the header. Non-policy failures make the MM routing entry unavailable.
    /// Policy rejections remain terminal for the request.
    ///
    /// Results are cached by `(mm_hash, dimension_policy)` so repeated
    /// requests for the same image (typical of multi-turn / session workloads)
    /// hit the cache and skip the HTTP fetch entirely. Without this cache,
    /// sticky-routing workloads pay 4–5× HTTP Range fetches per request just
    /// to compute routing tokens.
    #[cfg(feature = "mm-routing")]
    async fn fetch_image_dims(
        mm_hash: u64,
        url: &str,
        dimension_policy: RoutingImageDimensionPolicy,
    ) -> Result<(u32, u32)> {
        use moka::future::Cache;
        use std::sync::LazyLock;

        // Bounded sharded LRU (moka uses TinyLFU internally — sharded write
        // locks, lock-free reads). Replaces an earlier hand-rolled DashMap +
        // tokio::sync::Notify singleflight; moka's `try_get_with` provides
        // both singleflight and bounded LRU eviction in one primitive.
        //
        //   max_capacity:  100k entries (~5 MB at ~50 B/entry incl. moka
        //                  bookkeeping). Caps memory under unbounded URL
        //                  pools (signed-URL refresh, image proxies).
        //   time_to_live:  24h. Bounds staleness if a URL is re-uploaded
        //                  with new content. Independent of capacity-based
        //                  eviction, which kicks in earlier under load.
        static DIM_CACHE: LazyLock<Cache<(u64, RoutingImageDimensionPolicy), (u32, u32)>> =
            LazyLock::new(|| {
                Cache::builder()
                    .max_capacity(100_000)
                    .time_to_live(std::time::Duration::from_secs(24 * 60 * 60))
                    .build()
            });

        // Hot path: avoid allocating an owned URL on cache hit. moka's
        // `get` is async because it may do a small amount of bookkeeping
        // for the LRU/TinyLFU policy.
        let cache_key = (mm_hash, dimension_policy);
        if let Some(dims) = DIM_CACHE.get(&cache_key).await {
            return Ok(dims);
        }

        // Cold path: take an owned String so the init future can be
        // 'static (moka may move waiters across executor threads). Because
        // try_get_with does built-in singleflight, concurrent callers for
        // the same `mm_hash` collapse into a single fetch.
        let url_owned = url.to_string();
        DIM_CACHE
            .try_get_with(cache_key, async move {
                Self::fetch_image_dims_uncached(&url_owned, dimension_policy)
                    .await
                    .map_err(ImageDimFetchFailure::from_error)
            })
            .await
            .map_err(|error| error.to_error())
    }

    #[cfg(feature = "mm-routing")]
    async fn fetch_image_dims_uncached(
        url: &str,
        dimension_policy: RoutingImageDimensionPolicy,
    ) -> Result<(u32, u32)> {
        // Most JPEG SOF markers and PNG/WebP headers fit in the first 4 KB.
        // Start small and only escalate to 64 KB if the parser fails on the
        // truncated header.
        const SMALL_RANGE: usize = 4 * 1024 - 1;
        const LARGE_RANGE: usize = 64 * 1024 - 1;
        // Per-Range tighter bound than MediaFetcher's 30 s default — dim
        // fetch is best-effort; on a slow remote we'd rather skip MM
        // routing for this image than starve the request.
        const DIM_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

        if let Some(rest) = url.strip_prefix("data:") {
            let comma = rest
                .find(',')
                .ok_or_else(|| anyhow::anyhow!("malformed data URI: no comma"))?;
            let prefix = &rest[..comma];
            let payload = &rest[comma + 1..];
            let bytes: Vec<u8> = if prefix.contains(";base64") {
                use base64::Engine;
                base64::engine::general_purpose::STANDARD
                    .decode(payload)
                    .map_err(|e| anyhow::anyhow!("data URI base64 decode: {}", e))?
            } else {
                payload.as_bytes().to_vec()
            };
            return Self::dimensions_from_image_bytes(&bytes, dimension_policy);
        }

        if !(url.starts_with("http://") || url.starts_with("https://")) {
            anyhow::bail!("unsupported url scheme for dim fetch: {}", url);
        }

        // `DIM_FETCH_MEDIA_FETCHER` and `DIM_FETCH_HTTP_CLIENT` are
        // module-scope `LazyLock`s forced at startup in `new_with_parts`
        // for MM-routable preprocessors — see their definitions for the
        // lifecycle and policy contract.

        // Pre-flight SSRF check on the original URL. Redirect targets are
        // revalidated by the Client's redirect policy, and DNS-resolved
        // IPs are filtered by the resolver — so a URL that passes here
        // can't escape the contract on the wire either.
        let parsed = url::Url::parse(url)?;
        DIM_FETCH_MEDIA_FETCHER
            .check_if_url_allowed_with_dns(&parsed)
            .await?;

        let mut range_end = SMALL_RANGE;
        loop {
            let resp = DIM_FETCH_HTTP_CLIENT
                .get(url)
                .header("Range", format!("bytes=0-{}", range_end))
                .timeout(DIM_FETCH_TIMEOUT)
                .send()
                .await
                .map_err(|error| {
                    crate::preprocessor::media::MediaFetcher::map_fetch_error(error.into())
                })?;
            let status = resp.status();
            // Require 206 Partial Content — if the origin ignored the
            // Range header and answered 200 OK, `.bytes()` would buffer
            // the full image into memory. Bail in that case rather than
            // download an unbounded payload just to peek at dimensions.
            // The caller treats Err as "MM routing entry unavailable for
            // this image", which falls back to text-prefix routing.
            if status != reqwest::StatusCode::PARTIAL_CONTENT {
                anyhow::bail!(
                    "image dim fetch expected 206 Partial Content, got HTTP {}",
                    status
                );
            }
            let bytes = resp.bytes().await?;
            match Self::dimensions_from_image_bytes(&bytes, dimension_policy) {
                Ok((w, h)) => return Ok((w, h)),
                Err(_) if range_end < LARGE_RANGE => {
                    range_end = LARGE_RANGE;
                    continue;
                }
                Err(e) => anyhow::bail!("image header parse failed after 64KB: {}", e),
            }
        }
    }

    #[cfg(feature = "mm-routing")]
    fn dimensions_from_image_bytes(
        bytes: &[u8],
        dimension_policy: RoutingImageDimensionPolicy,
    ) -> Result<(u32, u32)> {
        use image::{ImageDecoder, ImageReader, metadata::Orientation};
        use std::io::Cursor;

        let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?;
        if dimension_policy == RoutingImageDimensionPolicy::Encoded {
            return Ok(reader.into_dimensions()?);
        }

        let mut decoder = reader.into_decoder()?;
        let (width, height) = decoder.dimensions();
        let swaps_axes = matches!(
            decoder.orientation()?,
            Orientation::Rotate90
                | Orientation::Rotate270
                | Orientation::Rotate90FlipH
                | Orientation::Rotate270FlipH
        );
        Ok(if swaps_axes {
            (height, width)
        } else {
            (width, height)
        })
    }

    /// Tokenize the request and return the token ids alongside any annotations
    /// the caller asked for. The caller owns the result and is responsible for
    /// installing it on the builder via `builder.token_ids(...)` once any
    /// downstream consumers (e.g. MM-routing) have borrowed it.
    pub async fn gather_tokens<
        R: OAIChatLikeRequest
            + AnnotationsProvider
            + SamplingOptionsProvider
            + StopConditionsProvider
            + OutputOptionsProvider
            + NvExtProvider,
    >(
        &self,
        request: &R,
        formatted_prompt: Option<&RenderedPrompt>,
        tracker: Option<&RequestTracker>,
    ) -> Result<(Vec<crate::protocols::TokenIdType>, HashMap<String, String>)> {
        let mut annotations = HashMap::new();
        let mut tokens_out: Vec<crate::protocols::TokenIdType> = Vec::new();
        // match request type before any conversion/processing
        match request.prompt_input_type() {
            PromptInput::Tokens(_) => {
                if let Some(token_input) = request.extract_tokens() {
                    match token_input {
                        TokenInput::Single(tokens) => {
                            tokens_out = tokens;
                        }
                        TokenInput::Batch(token_batches) => {
                            if token_batches.len() == 1 {
                                tokens_out = token_batches[0].clone();
                            } else {
                                bail!(
                                    "Batch token input not supported for more than one token in requests (got {})",
                                    token_batches.len()
                                );
                            }
                        }
                    }
                }
            }
            PromptInput::Text(_) => {
                if let Some(text_input) = request.extract_text() {
                    match text_input {
                        TextInput::Single(raw_prompt) => {
                            if let Some(f) = formatted_prompt
                                && request.has_annotation(ANNOTATION_FORMATTED_PROMPT)
                            {
                                annotations.insert(
                                    ANNOTATION_FORMATTED_PROMPT.to_string(),
                                    f.as_str().to_string(),
                                );
                            }

                            // Completions will use raw_prompt, no template.
                            // K3 keeps control-token spans distinct from user text until
                            // tokenization; all other renderers use the plain text path.

                            // If nvext.token_data is present, use the pre-computed tokens
                            // directly and skip tokenization.  This avoids redundant
                            // tokenization when an external component (e.g. the GAIE EPP
                            // KV-router) has already tokenized the prompt.
                            // When backend_instance_id is set without token_data, warn
                            // but fall back to tokenization (backward compat for non-GAIE
                            // routers that set the header without providing tokens).
                            let has_backend_instance_id = request
                                .nvext()
                                .and_then(|ext| ext.backend_instance_id)
                                .is_some();

                            let token_data =
                                request.nvext().and_then(|ext| ext.token_data.as_ref());

                            let (tokens_vec, skip_token_annotation) = if let Some(tokens) =
                                token_data
                            {
                                tracing::info!(
                                    token_count = tokens.len(),
                                    first_tokens = ?&tokens[..std::cmp::min(5, tokens.len())],
                                    "[SIDECAR-SKIP-TOKENIZE] Found nvext.token_data — using pre-computed tokens, SKIPPING tokenization"
                                );
                                (tokens.clone(), true)
                            } else if has_backend_instance_id {
                                tracing::warn!(
                                    "backend_instance_id provided but no token_data; tokenizing prompt"
                                );
                                let encoding = self
                                    .encode_prompt_with_timing(
                                        formatted_prompt,
                                        raw_prompt.as_str(),
                                        tracker,
                                    )
                                    .await?;
                                (encoding.token_ids().to_vec(), false)
                            } else {
                                let encoding = self
                                    .encode_prompt_with_timing(
                                        formatted_prompt,
                                        raw_prompt.as_str(),
                                        tracker,
                                    )
                                    .await?;
                                (encoding.token_ids().to_vec(), false)
                            };

                            if request.has_annotation(ANNOTATION_TOKEN_IDS)
                                && !skip_token_annotation
                            {
                                annotations.insert(
                                    ANNOTATION_TOKEN_IDS.to_string(),
                                    serde_json::to_string(&tokens_vec)?,
                                );
                            }

                            tokens_out = tokens_vec;
                        }
                        TextInput::Batch(texts) => {
                            if texts.len() == 1 {
                                let encoding = self.encode_with_timing(&texts[0], tracker).await?;
                                let tokens = encoding.token_ids().to_vec();
                                tokens_out = tokens;
                            } else {
                                bail!(
                                    "Batch text input not supported for more than one text in requests (got {})",
                                    texts.len()
                                );
                            }
                        }
                    }
                }
            }
        }

        Self::capture_prompt_token_ids(request, tracker, &tokens_out);

        Ok((tokens_out, annotations))
    }

    /// Retain the authoritative rendered prompt only for clients that request
    /// the named response field. Ordinary requests do not clone the token list.
    fn capture_prompt_token_ids<R: NvExtProvider>(
        request: &R,
        tracker: Option<&RequestTracker>,
        token_ids: &[TokenIdType],
    ) {
        let requested = request
            .nvext()
            .and_then(|nvext| nvext.extra_fields.as_ref())
            .is_some_and(|fields| fields.iter().any(|field| field == "prompt_token_ids"));
        if requested && let Some(tracker) = tracker {
            tracker.set_prompt_token_ids(token_ids.to_vec());
        }
    }

    fn prompt_overflow_error(token_count: usize, combined_limit: usize) -> DynamoError {
        DynamoError::builder()
            .error_type(ErrorType::InvalidArgument)
            .message(format!(
                "This model's maximum context length is {} tokens. \
                 However, your messages resulted in {} tokens. \
                 Please reduce the length of the messages.",
                combined_limit, token_count,
            ))
            .build()
    }

    async fn encode_with_timing(
        &self,
        prompt: &str,
        tracker: Option<&RequestTracker>,
    ) -> anyhow::Result<Encoding> {
        let encode_start = Instant::now();
        // Offload the CPU-heavy BPE encode to the bounded blocking pool instead of running it on
        // the async event loop. For long prompts at high concurrency, a synchronous encode here
        // stalls the frontend tokio runtime for seconds, starving the I/O tasks that share the
        // runtime. Own the prompt + clone the tokenizer (Arc) so the closure is 'static + Send;
        // mirrors the embedding path's spawn_blocking offload.
        let owned = if prompt.contains('\0') {
            tracing::debug!("Prompt contains null bytes; stripping to avoid tokenizer divergence");
            prompt.replace('\0', "")
        } else {
            prompt.to_string()
        };
        let tokenizer = self.tokenizer.clone();
        let encoding = tokio::task::spawn_blocking(move || tokenizer.encode(&owned)).await??;
        if let Some(t) = tracker {
            t.record_tokenize_latency(encode_start.elapsed());
        }
        Ok(encoding)
    }

    async fn encode_prompt_with_timing(
        &self,
        formatted_prompt: Option<&RenderedPrompt>,
        raw_prompt: &str,
        tracker: Option<&RequestTracker>,
    ) -> anyhow::Result<Encoding> {
        let Some(prompt) = formatted_prompt
            .filter(|prompt| prompt.segments().is_some())
            .cloned()
        else {
            return self
                .encode_with_timing(
                    formatted_prompt
                        .map(RenderedPrompt::as_str)
                        .unwrap_or(raw_prompt),
                    tracker,
                )
                .await;
        };

        let encode_start = Instant::now();
        let tokenizer = self.tokenizer.clone();
        let encoding = tokio::task::spawn_blocking(move || {
            let segments = prompt
                .encode_segments()
                .expect("prompt was checked for rendered segments");
            tokenizer.encode_segments(&segments)
        })
        .await??;
        if let Some(t) = tracker {
            t.record_tokenize_latency(encode_start.elapsed());
        }
        Ok(encoding)
    }

    /// Preprocess an embedding request, handling both text and token ID inputs.
    ///
    /// For text inputs, tokenizes the text using the configured tokenizer.
    /// For token ID inputs, uses the provided token IDs directly and skips tokenization.
    ///
    /// Returns both the preprocessed request and a hashmap of annotations.
    pub async fn preprocess_embedding_request(
        &self,
        request: &NvCreateEmbeddingRequest,
    ) -> Result<(PreprocessedEmbeddingRequest, HashMap<String, String>)> {
        let _stage_guard = StageGuard::new(STAGE_PREPROCESS, "");
        let mut annotations = HashMap::new();
        let mut builder = PreprocessedEmbeddingRequest::builder();

        let embedding_tokenizers = self.embedding_tokenizers.as_ref().ok_or_else(|| {
            anyhow::anyhow!(
                "embedding tokenization is unavailable; construct the preprocessor with \
                 OpenAIPreprocessor::new_for_embeddings"
            )
        })?;
        let effective_add_special_tokens = request
            .add_special_tokens
            .or(embedding_tokenizers.add_special_tokens_default)
            .unwrap_or(true);
        let is_text_input = matches!(
            &request.inner.input,
            dynamo_protocols::types::EmbeddingInput::String(_)
                | dynamo_protocols::types::EmbeddingInput::StringArray(_)
        );
        let truncation_limit =
            self.embedding_truncation_limit(request.truncate_prompt_tokens, is_text_input)?;
        let mut all_token_ids = match &request.inner.input {
            dynamo_protocols::types::EmbeddingInput::String(s) => {
                let tokenizer = embedding_tokenizers.tokenizer(effective_add_special_tokens)?;
                let encoding = tokenizer.encode(s)?;
                vec![encoding.token_ids().to_vec()]
            }
            dynamo_protocols::types::EmbeddingInput::StringArray(arr) => {
                let tokenizer = embedding_tokenizers.tokenizer(effective_add_special_tokens)?;
                let input_strs: Vec<String> = arr.to_vec();
                let encodings = tokio::task::spawn_blocking({
                    let tokenizer = tokenizer.clone();
                    let strs = input_strs.clone();
                    move || {
                        tokenizer.encode_batch(&strs.iter().map(|s| s.as_str()).collect::<Vec<_>>())
                    }
                })
                .await??;
                encodings
                    .into_iter()
                    .map(|encoding| encoding.token_ids().to_vec())
                    .collect()
            }
            dynamo_protocols::types::EmbeddingInput::IntegerArray(token_ids) => {
                vec![token_ids.clone()]
            }
            dynamo_protocols::types::EmbeddingInput::ArrayOfIntegerArray(token_arrays) => {
                token_arrays.clone()
            }
        };
        if let Some(limit) = truncation_limit {
            for token_ids in &mut all_token_ids {
                // This integration intentionally follows right truncation:
                // preserve the first N tokens.
                token_ids.truncate(limit);
            }
        }

        // Handle annotations
        if request.has_annotation(ANNOTATION_TOKEN_IDS) {
            annotations.insert(
                ANNOTATION_TOKEN_IDS.to_string(),
                serde_json::to_string(&all_token_ids)?,
            );
        }

        builder.token_ids(all_token_ids);
        builder.model(request.inner.model.clone());
        builder.encoding_format(request.inner.encoding_format.as_ref().map(|f| match f {
            EncodingFormat::Float => "float".to_string(),
            EncodingFormat::Base64 => "base64".to_string(),
        }));
        builder.truncate_prompt_tokens(request.truncate_prompt_tokens);
        builder.dimensions(request.inner.dimensions);

        builder.annotations(request.annotations().unwrap_or_default());
        builder.mdc_sum(Some(self.mdcsum.clone()));

        Ok((builder.build()?, annotations))
    }

    fn embedding_truncation_limit(
        &self,
        requested: Option<i64>,
        is_text_input: bool,
    ) -> Result<Option<usize>> {
        let Some(requested) = requested else {
            return Ok(None);
        };

        if requested < -1 {
            return Err(invalid_argument_error(format!(
                "truncate_prompt_tokens must be >= -1, got {requested}"
            )));
        }

        // Caller-supplied token IDs are already preprocessed; do not mutate them.
        if !is_text_input {
            return Ok(None);
        }

        let model_limit = self.context_length as usize;
        if requested == -1 {
            if model_limit == 0 {
                return Err(invalid_argument_error(
                    "truncate_prompt_tokens=-1 requires a configured model context length",
                ));
            }
            return Ok(Some(model_limit));
        }

        let requested = usize::try_from(requested).map_err(|_| {
            invalid_argument_error("truncate_prompt_tokens is too large for this platform")
        })?;
        if model_limit > 0 && requested > model_limit {
            return Err(invalid_argument_error(format!(
                "truncate_prompt_tokens={requested} cannot be greater than \
                 max_model_len={model_limit}. Please request a smaller truncation size."
            )));
        }

        Ok(Some(requested))
    }

    fn apply_unified_response_policies<S>(
        stream: S,
        emit_tool_calls: bool,
        defer_reasoning_for_nonempty_content: bool,
    ) -> Pin<Box<dyn Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send>>
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> = Box::pin(
            Self::apply_tool_call_response_policy(stream, emit_tool_calls),
        );
        // Observe parser classification before force_nonempty deferral removes the
        // reasoning delta. The annotated usage trailer can still be held below until
        // every deferred recovery chunk has been emitted.
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> =
            Box::pin(annotate_reasoning_usage(stream));
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> = if defer_reasoning_for_nonempty_content
        {
            Box::pin(Self::defer_unified_reasoning_for_nonempty_content(stream))
        } else {
            stream
        };
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> = if defer_reasoning_for_nonempty_content
        {
            Box::pin(Self::hold_usage_until_stream_end(stream))
        } else {
            stream
        };
        stream
    }

    fn tool_processing_route(
        &self,
        request: &NvCreateChatCompletionRequest,
        guided_tool_constraint: &crate::protocols::openai::GuidedToolConstraint,
    ) -> anyhow::Result<ToolProcessingRoute> {
        use crate::protocols::openai::chat_completions::{tool_parser_v2, unified_parser};

        let uses_tool_call_structural_tag = guided_tool_constraint.uses_structural_tag();
        if let Some(family) = tool_parser_v2::unified_family(
            self.tool_call_parser.as_deref(),
            self.runtime_config.reasoning_parser.as_deref(),
        ) && !uses_tool_call_structural_tag
            && matches!(
                request.inner.tool_choice.as_ref(),
                None | Some(ChatCompletionToolChoiceOption::Auto)
                    | Some(ChatCompletionToolChoiceOption::None)
            )
        {
            return Ok(ToolProcessingRoute::MuseUnified(family));
        }

        if let Some(family) = unified_parser::selected_family(
            self.tool_call_parser.as_deref(),
            self.runtime_config.reasoning_parser.as_deref(),
        ) {
            return Ok(ToolProcessingRoute::QwenUnified(family));
        }

        let effective_tool_call_parser = self.tool_call_parser.clone().or_else(|| {
            self.runtime_config
                .reasoning_parser
                .as_deref()
                .filter(|parser| matches!(*parser, "kimi_k3" | "kimi-k3"))
                .map(str::to_string)
        });
        let parser_unwraps_all_kimi_k3_responses = effective_tool_call_parser
            .as_deref()
            .is_some_and(|parser| matches!(parser, "kimi_k3" | "kimi-k3"));
        let tool_call_parsing_enabled = Self::tool_call_parsing_enabled(request);
        let has_tools = request
            .inner
            .tools
            .as_ref()
            .is_some_and(|tools| !tools.is_empty());
        let should_jail = if tool_call_parsing_enabled || parser_unwraps_all_kimi_k3_responses {
            Self::should_apply_tool_jail(
                effective_tool_call_parser.as_ref(),
                request.inner.tool_choice.as_ref(),
                has_tools,
            )?
        } else {
            false
        };

        if !should_jail {
            return Ok(ToolProcessingRoute::PassThrough);
        }

        if let Some(parser_name) = effective_tool_call_parser.as_deref()
            && tool_parser_v2::enabled()
            && tool_parser_v2::supports_family(parser_name)
            && !uses_tool_call_structural_tag
            && matches!(
                request.inner.tool_choice.as_ref(),
                None | Some(ChatCompletionToolChoiceOption::Auto)
            )
        {
            Ok(ToolProcessingRoute::ParserV2(parser_name.to_string()))
        } else {
            Ok(ToolProcessingRoute::LegacyJail(effective_tool_call_parser))
        }
    }

    pub fn postprocessor_parsing_stream<S>(
        &self,
        stream: S,
        request: &NvCreateChatCompletionRequest,
        prompt_injected_reasoning: bool,
        uses_tool_call_structural_tag: bool,
    ) -> anyhow::Result<
        impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    >
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        let guided_tool_constraint = crate::preprocessor::tool_choice::guided_tool_constraint(
            request,
            self.tool_call_parser.as_deref(),
            self.runtime_config.reasoning_parser.as_deref(),
            uses_tool_call_structural_tag,
        )?;
        let tool_processing_route = self.tool_processing_route(request, &guided_tool_constraint)?;
        self.postprocessor_parsing_stream_with_constraint(
            stream,
            request,
            prompt_injected_reasoning,
            guided_tool_constraint,
            tool_processing_route,
        )
    }

    fn postprocessor_parsing_stream_with_constraint<S>(
        &self,
        stream: S,
        request: &NvCreateChatCompletionRequest,
        prompt_injected_reasoning: bool,
        guided_tool_constraint: crate::protocols::openai::GuidedToolConstraint,
        tool_processing_route: ToolProcessingRoute,
    ) -> anyhow::Result<
        impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    >
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        use crate::protocols::openai::chat_completions::{tool_parser_v2, unified_parser};
        let uses_tool_call_structural_tag = guided_tool_constraint.uses_structural_tag();
        let defer_reasoning_for_nonempty_content =
            Self::wants_reasoning_as_content_when_empty(request.chat_template_args.as_ref());
        // Two different streaming paths can release a grammar-constrained tool call
        // before its payload closes: the unified (v2) adapter below and the jail near
        // the end of this function. Both must obey the same rollback lever, so
        // `DYN_ENABLE_GUIDED_TOOL_STREAMING` is read ONCE, here, and the single decision
        // is handed to whichever path runs. Reading it again at either site would be a
        // second predicate that can drift; a site with no read at all makes the lever
        // silently inert for every request routed through it.
        let guided_tool_streaming = Self::guided_tool_streaming_release(
            guided_tool_constraint.installs_guided_json(),
            env_is_falsey(env_llm::DYN_ENABLE_GUIDED_TOOL_STREAMING),
        );

        // Two independent families each own ONE unified parser (ordered reasoning +
        // content + tool calls) that replaces the v1 reasoning stage AND the tool
        // jail outright: muse (`tool_parser_v2`, default-on — its v1 reasoning
        // parser is gone, so `get_reasoning_parser_from_name` falls back to
        // `Basic`, which cannot read the `to=self<|message|>` grammar) and Qwen3
        // (`unified_parser`, gated on `DYN_ENABLE_EXPERIMENTAL_PARSERS_V2`). Both
        // run regardless of has_tools — they own reasoning and strip its markers
        // even with zero tools — and both route their output through the SAME
        // shared response policy below, which is what suppresses `tool_calls` for
        // a no-tools or `tool_choice: none` request, exactly as it does for every
        // other family's jail output.
        //
        // A forced/structural-tag `tool_choice` still excludes muse: its
        // `apply_unified_stream` only reads native markup, so a guided-JSON or
        // structural-tag request would misparse the grammar it does not speak. The
        // newer Qwen3 `apply_stream` handles every `tool_choice` itself (guided
        // JSON for named/required, native markup for auto/none/structural-tag), so
        // it does not need the same entry gate.
        //
        if let ToolProcessingRoute::MuseUnified(family) = &tool_processing_route {
            let tool_definitions = request.inner.tools.as_ref().map(|tools| {
                tools
                    .iter()
                    .map(|tool| dynamo_parsers::tool_calling::ToolDefinition {
                        name: tool.function.name.clone(),
                        parameters: tool.function.parameters.clone(),
                        strict: tool.function.strict,
                    })
                    .collect()
            });
            let unified: Pin<Box<dyn Stream<Item = _> + Send>> =
                Box::pin(tool_parser_v2::apply_unified_stream(
                    stream,
                    tool_definitions,
                    family.clone(),
                    true,
                ));
            return Ok(Self::apply_unified_response_policies(
                unified,
                Self::tool_call_parsing_enabled(request),
                defer_reasoning_for_nonempty_content,
            ));
        }

        if let ToolProcessingRoute::QwenUnified(family) = &tool_processing_route {
            let tool_definitions = request.inner.tools.as_ref().map(|tools| {
                tools
                    .iter()
                    .map(|tool| dynamo_parsers::tool_calling::ToolDefinition {
                        name: tool.function.name.clone(),
                        parameters: tool.function.parameters.clone(),
                        strict: tool.function.strict,
                    })
                    .collect()
            });
            let unified: Pin<Box<dyn Stream<Item = _> + Send>> =
                Box::pin(unified_parser::apply_stream_with_constraint(
                    stream,
                    tool_definitions,
                    guided_tool_constraint,
                    unified_parser::stream_prefill(family, prompt_injected_reasoning),
                    family,
                    guided_tool_streaming,
                ));
            return Ok(Self::apply_unified_response_policies(
                unified,
                Self::tool_call_parsing_enabled(request),
                defer_reasoning_for_nonempty_content,
            ));
        }

        // Guided output may be bare JSON or `reasoning</think>JSON`. Supported
        // parsers inspect the stream shape before deciding whether to parse it.
        let is_guided_tool_choice = matches!(
            request.inner.tool_choice,
            Some(ChatCompletionToolChoiceOption::Required)
                | Some(ChatCompletionToolChoiceOption::Named(_))
        );
        let is_structured_response = Self::has_structured_response_format(request);
        let is_guided_output = is_guided_tool_choice || is_structured_response;
        let reasoning_parser = self.runtime_config.reasoning_parser.as_deref();
        // Force parsers opt in by capability; prompt-seeded parsers opt in per request.
        // Structural-tag tool formats do not use this guided-JSON detection path.
        let inspect_force_reasoning_guided_output = is_guided_output
            && !uses_tool_call_structural_tag
            && Self::supports_reasoning_before_guided_json(reasoning_parser);
        let inspect_prompt_injected_guided_output = is_guided_output
            && prompt_injected_reasoning
            && !uses_tool_call_structural_tag
            && (Self::skips_guided_json_when_prompt_injected(reasoning_parser)
                || (is_structured_response
                    && Self::skips_structured_response_when_prompt_injected(reasoning_parser)));
        let inspect_unsupported_structured_response_reasoning_gate = is_structured_response
            && !uses_tool_call_structural_tag
            && !Self::structured_response_supports_sglang_reasoning_gate(reasoning_parser);
        let bypass_reasoning_for_bare_guided_json = inspect_force_reasoning_guided_output
            || inspect_prompt_injected_guided_output
            || inspect_unsupported_structured_response_reasoning_gate;
        // Preserve the legacy bypass for force-reasoning parsers not yet opted in.
        let skip_reasoning_for_guided_json = is_guided_output
            && !uses_tool_call_structural_tag
            && Self::is_force_reasoning_parser(reasoning_parser)
            && !inspect_force_reasoning_guided_output;

        let reasoning_disabled_by_request = Self::is_reasoning_disabled_by_request(
            self.runtime_config.reasoning_parser.as_deref(),
            request.chat_template_args.as_ref(),
        );

        // Try to parse reasoning content only if parser is configured.
        let should_parse_reasoning = self.runtime_config.reasoning_parser.is_some()
            && !reasoning_disabled_by_request
            && !skip_reasoning_for_guided_json;
        let should_strip_disabled_reasoning_start = reasoning_disabled_by_request
            && Self::is_nemotron_force_reasoning(self.runtime_config.reasoning_parser.as_deref())
            && !skip_reasoning_for_guided_json;
        let guided_reasoning_start_token =
            if should_parse_reasoning && bypass_reasoning_for_bare_guided_json {
                Self::guided_json_reasoning_start_token(reasoning_parser)
            } else {
                None
            };

        // Reasoning Content Parsing Transformation Step
        // Current Solution:
        // This step operates on Deltas created by the transform_postprocessor_stream function
        // Only access to text and not token_ids - so can not support parsing based on token_ids for now
        // Future Solution:
        // To address the limitation if needed in future: move this step before transform_postprocessor_stream and add new field of reasoning_content to the backend output
        // Use backend_output.reasoning_content field to fill out the deltas.
        // A bracket-prefixed reasoning opener is indistinguishable from JSON
        // until enough bytes arrive. Strip only a configured complete marker;
        // nonmatching bare JSON is restored unchanged for shape detection.
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> =
            if let Some(start_token) = guided_reasoning_start_token {
                Box::pin(Self::strip_leading_reasoning_start_from_stream(
                    stream,
                    start_token,
                ))
            } else {
                Box::pin(stream)
            };

        // Only a force_nonempty_content request needs the deferral and the EOF
        // flush of a truncated `<think>` prefix; gating on the request keeps the
        // per-token clone and the finish_reasoning_stream() flush off every
        // other request's path. Same predicate the aggregator uses, so the
        // streaming and non-streaming paths cannot disagree.
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> = if should_parse_reasoning {
            Box::pin(Self::parse_reasoning_content_from_stream_inner(
                stream,
                self.runtime_config.reasoning_parser.clone().unwrap(), // Safety: We already checked that parser is some, so gtg
                prompt_injected_reasoning,
                bypass_reasoning_for_bare_guided_json,
                defer_reasoning_for_nonempty_content,
            ))
        } else if should_strip_disabled_reasoning_start {
            Box::pin(Self::strip_leading_reasoning_start_from_stream(
                stream, "<think>",
            ))
        } else {
            Box::pin(stream)
        };
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> =
            if defer_reasoning_for_nonempty_content || should_strip_disabled_reasoning_start {
                Box::pin(Self::hold_usage_until_stream_end(stream))
            } else {
                stream
            };
        let stream: Pin<Box<dyn Stream<Item = _> + Send>> = if should_parse_reasoning {
            Box::pin(annotate_reasoning_usage(stream))
        } else {
            stream
        };

        let tool_call_parsing_enabled = Self::tool_call_parsing_enabled(request);

        // Convert OpenAI tools to parser ToolDefinition format before applying jail
        let tool_definitions = request.inner.tools.as_ref().map(|tools| {
            tools
                .iter()
                .map(|tool| dynamo_parsers::tool_calling::ToolDefinition {
                    name: tool.function.name.clone(),
                    parameters: tool.function.parameters.clone(),
                    strict: tool.function.strict,
                })
                .collect()
        });

        let transformed_stream: Pin<Box<dyn Stream<Item = _> + Send>> =
            match tool_processing_route {
                ToolProcessingRoute::ParserV2(parser_name) => Box::pin(
                    tool_parser_v2::apply_stream(stream, tool_definitions, parser_name),
                ),
                ToolProcessingRoute::LegacyJail(effective_tool_call_parser) => {
                    // A forced tool_choice installed a JSON grammar, so the jail may release
                    // calls as they arrive instead of buffering to the closing brace. The
                    // jail keeps its own native fallback, so a backend that ignores the
                    // grammar (MiniMax M2 emits XML under `required`) still parses normally.
                    // Same request-scoped decision the unified path above was given.
                    Box::pin(Self::apply_tool_calling_jail(
                        effective_tool_call_parser,
                        request.inner.tool_choice.clone(),
                        tool_definitions,
                        uses_tool_call_structural_tag,
                        guided_tool_streaming,
                        stream,
                    ))
                }
                ToolProcessingRoute::PassThrough => Box::pin(stream),
                ToolProcessingRoute::MuseUnified(_) | ToolProcessingRoute::QwenUnified(_) => {
                    unreachable!("unified routes return before legacy response processing")
                }
            };

        Ok(Self::apply_tool_call_response_policy(
            transformed_stream,
            tool_call_parsing_enabled,
        ))
    }

    /// Enforce the request's tool-call policy after model-specific parsing.
    ///
    /// Kimi K3 must keep its jail active even when the request does not permit
    /// tools because the same parser unwraps ordinary XTML response channels.
    /// The jail can still emit structured tool-call deltas while doing that
    /// decoding, so parser activation alone is not an output-policy boundary.
    /// Apply the policy to the shared stream before the HTTP streaming and
    /// non-streaming paths diverge. This policy deliberately fails closed: when
    /// a decoder consumes a tool-only turn, suppressing the unauthorized call
    /// may leave an empty assistant turn with `finish_reason: stop`. Reconstructing
    /// parser-specific wire markup as assistant content would leak internal
    /// protocol tokens and could still be mistaken for an actionable call.
    fn apply_tool_call_response_policy<S>(
        stream: S,
        tool_call_parsing_enabled: bool,
    ) -> Pin<Box<dyn Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static>>
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        if tool_call_parsing_enabled {
            return Box::pin(stream);
        }

        Box::pin(stream.map(|mut response| {
            if let Some(data) = response.data.as_mut() {
                for choice in &mut data.inner.choices {
                    choice.delta.tool_calls = None;
                    if choice.finish_reason
                        == Some(dynamo_protocols::types::FinishReason::ToolCalls)
                    {
                        choice.finish_reason = Some(dynamo_protocols::types::FinishReason::Stop);
                    }
                }
            }
            response
        }))
    }

    /// Ensure the first emitted delta for each choice carries the assistant role.
    ///
    /// This runs after reasoning and tool-call parsing so a parser that buffers the
    /// original role-bearing delta cannot leave downstream consumers without a role.
    fn normalize_chat_stream_roles<S>(
        stream: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        let mut role_emitted_choices = HashSet::new();

        stream.map(move |mut response| {
            if let Some(data) = response.data.as_mut() {
                for choice in &mut data.inner.choices {
                    choice.delta.role = role_emitted_choices
                        .insert(choice.index)
                        .then_some(dynamo_protocols::types::Role::Assistant);
                }
            }
            response
        })
    }

    pub fn transform_postprocessor_stream<S, Resp>(
        stream: S,
        generator: Box<dyn DeltaGeneratorExt<Resp>>,
        context: Arc<dyn AsyncEngineContext>,
        emit_payload_usage_chunk: bool,
        trace_tokens_enabled: bool,
        trace_finish_reason_metadata: Option<crate::request_trace::SharedFinishReasonMetadata>,
        mm_counts: MultimodalCounts,
    ) -> impl Stream<Item = Annotated<Resp>> + Send
    where
        S: Stream<Item = Annotated<BackendOutput>> + Send + 'static,
        Resp: Send + Sync + Clone + 'static + std::fmt::Debug,
    {
        Self::transform_postprocessor_stream_with_image_tokens(
            stream,
            generator,
            context,
            emit_payload_usage_chunk,
            trace_tokens_enabled,
            trace_finish_reason_metadata,
            mm_counts,
            None,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn transform_postprocessor_stream_with_image_tokens<S, Resp>(
        stream: S,
        generator: Box<dyn DeltaGeneratorExt<Resp>>,
        context: Arc<dyn AsyncEngineContext>,
        emit_payload_usage_chunk: bool,
        trace_tokens_enabled: bool,
        trace_finish_reason_metadata: Option<crate::request_trace::SharedFinishReasonMetadata>,
        mm_counts: MultimodalCounts,
        image_tokens: Option<usize>,
    ) -> impl Stream<Item = Annotated<Resp>> + Send
    where
        S: Stream<Item = Annotated<BackendOutput>> + Send + 'static,
        Resp: Send + Sync + Clone + 'static + std::fmt::Debug,
    {
        struct DetokenizeMetricsGuard {
            tracker: Option<Arc<RequestTracker>>,
        }

        impl DetokenizeMetricsGuard {
            #[inline]
            fn tracker(&self) -> Option<&RequestTracker> {
                self.tracker.as_deref()
            }
        }

        impl Drop for DetokenizeMetricsGuard {
            fn drop(&mut self) {
                let Some(tracker) = self.tracker() else {
                    return;
                };
                if let Some(total) = tracker.detokenize_total_latency() {
                    DETOKENIZE_TOTAL_US.inc_by(total.as_micros() as f64);
                }
                DETOKENIZE_TOKEN_COUNT.inc_by(tracker.detokenize_count() as f64);
            }
        }

        struct State<Resp>
        where
            Resp: Send + Sync + Clone + 'static + std::fmt::Debug,
        {
            response_stream: Pin<Box<dyn Stream<Item = Annotated<BackendOutput>> + Send>>,
            response_generator: Box<dyn DeltaGeneratorExt<Resp>>,
            detokenize_metrics: DetokenizeMetricsGuard,
            context: Arc<dyn AsyncEngineContext>,
            cancelled: bool,
            cumulative_output_tokens: usize,
            finish_reason_sent: bool,
            usage_chunk_sent: bool,
            /// Buffered plain usage chunk to send to the client after the payload
            /// chunk (ANNOTATION_PAYLOAD_USAGE). Only Some when is_usage_enabled().
            pending_client_usage: Option<Annotated<Resp>>,
            finished: bool,
            emit_payload_usage_chunk: bool,
            trace_tokens_enabled: bool,
            trace_finish_reason_metadata: Option<crate::request_trace::SharedFinishReasonMetadata>,
            mm_counts: MultimodalCounts,
            image_tokens: Option<usize>,
        }

        let tracker = generator.tracker();
        let state = State {
            response_stream: Box::pin(stream),
            response_generator: generator,
            detokenize_metrics: DetokenizeMetricsGuard { tracker },
            context: context.clone(),
            cancelled: false,
            cumulative_output_tokens: 0,
            finish_reason_sent: false,
            usage_chunk_sent: false,
            pending_client_usage: None,
            finished: false,
            emit_payload_usage_chunk,
            trace_tokens_enabled,
            trace_finish_reason_metadata,
            mm_counts,
            image_tokens,
        };

        // transform the common response stream into a chat response stream

        stream::unfold(state, |mut inner| {
            async move {
                // Drain the buffered client-facing plain usage chunk first.
                // This MUST come before the `finished` guard: the stream-end
                // handler sets inner.finished = true before returning the payload
                // chunk, so on the very next iteration the finished guard would
                // terminate before we ever emit the client chunk.
                if let Some(client_chunk) = inner.pending_client_usage.take() {
                    inner.finished = true;
                    // Emit unconditionally to match the non-payload path below; the
                    // chunk is only buffered after a finish_reason, so payload capture must
                    // not alter the client SSE tail.
                    return Some((client_chunk, inner));
                }

                // If already finished (and no pending client chunk), stop.
                if inner.finished {
                    return None;
                }

                if let Some(mut response) = inner.response_stream.next().await {
                    // Split topology: overlay a standalone router's forwarded routing_data
                    // (timing, query-only token_ids) onto this request's tracker so the
                    // frontend's nvext/timing surfaces populate.
                    drain_router_routing_data(
                        &mut response.data,
                        inner.detokenize_metrics.tracker(),
                    );

                    if inner.cancelled {
                        tracing::debug!(
                            request_id = inner.context.id(),
                            "Cancellation issued last message; closing stream"
                        );
                        // inner.finished = true; // Mark as finished
                        return None;
                    }

                    tracing::trace!(
                        request_id = inner.context.id(),
                        "Processing common response: {:?}",
                        response
                    );

                    // Check if this response has a finish_reason
                    let has_finish_reason = response
                        .data
                        .as_ref()
                        .map(|d| d.finish_reason.is_some())
                        .unwrap_or(false);

                    let (chunk_tokens, isl) = if let Some(ref backend_output) = response.data {
                        let chunk_tokens = backend_output.token_ids.len();
                        inner.cumulative_output_tokens += chunk_tokens;

                        let isl = inner.response_generator.get_isl().map(|isl| isl as usize);

                        crate::request_trace::record_backend_finish_reason_metadata(
                            inner.trace_finish_reason_metadata.as_ref(),
                            backend_output.index,
                            backend_output.finish_reason.as_ref(),
                            backend_output.stop_reason.as_ref(),
                        );

                        (chunk_tokens, isl)
                    } else {
                        (0, None)
                    };

                    let current_osl = inner.cumulative_output_tokens;

                    let mut response = response.map_data(|data| {
                        inner
                            .response_generator
                            .choice_from_postprocessor(data)
                            .inspect_err(|e| {
                                tracing::error!(
                                    request_id = inner.context.id(),
                                    "Error processing common response: {:?}",
                                    e
                                );
                                inner.cancelled = true;
                                inner.context.stop_generating();
                            })
                            .map_err(|e| e.to_string())
                    });

                    // Create LLM metrics annotation with prefill/decode worker info from tracker.
                    // Worker types are stored at routing time to avoid expensive MDC lookup.
                    let tracker = inner.detokenize_metrics.tracker();
                    let llm_metrics = build_llm_metric_annotation(
                        tracker,
                        isl.unwrap_or(0),
                        current_osl,
                        chunk_tokens,
                        None,
                        inner.mm_counts,
                        inner.image_tokens,
                    );
                    if inner.trace_tokens_enabled {
                        crate::request_trace::record_llm_metric_tokens(
                            tracker,
                            isl,
                            current_osl,
                            None,
                        );
                    }

                    attach_llm_metrics(&mut response, llm_metrics);

                    // Mark if we've seen a finish_reason
                    if has_finish_reason {
                        inner.finish_reason_sent = true;
                    }

                    tracing::trace!(
                        request_id = inner.context.id(),
                        "OpenAI NvCreateChatCompletionStreamResponse: {:?}",
                        response
                    );

                    Some((response, inner))
                } else {
                    // Stream has ended - must set finished to true to prevent unfold from polling
                    // again. The stream is exhausted and will panic if polled after None.
                    inner.finished = true;

                    if inner.finish_reason_sent && !inner.usage_chunk_sent {
                        inner.usage_chunk_sent = true;

                        let usage_chunk = inner.response_generator.create_usage_chunk();
                        let usage = inner.response_generator.get_usage();
                        let tracker = inner.detokenize_metrics.tracker();
                        let cached_tokens = usage
                            .prompt_tokens_details
                            .as_ref()
                            .and_then(|d| d.cached_tokens.map(|c| c as usize));
                        let llm_metrics = build_llm_metric_annotation(
                            tracker,
                            usage.prompt_tokens as usize,
                            usage.completion_tokens as usize,
                            0,
                            cached_tokens,
                            inner.mm_counts,
                            inner.image_tokens,
                        );
                        if inner.trace_tokens_enabled {
                            crate::request_trace::record_llm_metric_tokens(
                                tracker,
                                Some(usage.prompt_tokens as usize),
                                usage.completion_tokens as usize,
                                cached_tokens,
                            );
                        }

                        let usage_requested = inner.response_generator.is_usage_enabled();

                        if inner.emit_payload_usage_chunk {
                            // Payload capture on: emit a dedicated payload-usage chunk that
                            // always carries usage for the payload DeltaAggregator
                            // (the EventConverter strips it entirely from the
                            // client), and buffer the plain client usage chunk only
                            // when include_usage was requested.
                            if usage_requested {
                                inner.pending_client_usage = Some(Annotated::<Resp> {
                                    id: None,
                                    data: Some(usage_chunk.clone()),
                                    event: None,
                                    comment: None,
                                    error: None,
                                });
                            }

                            let annotation =
                                llm_metrics.to_annotation::<()>().unwrap_or_else(|e| {
                                    tracing::warn!("Failed to serialize metrics: {}", e);
                                    Annotated::<()>::from_data(())
                                });
                            let payload_usage = Annotated::<Resp> {
                                id: None,
                                data: Some(usage_chunk),
                                event: Some(ANNOTATION_PAYLOAD_USAGE.to_string()),
                                comment: annotation.comment,
                                error: None,
                            };
                            Some((payload_usage, inner))
                        } else {
                            // Payload capture off: a single usage chunk; data is present only
                            // when include_usage was requested. Metrics ride via the
                            // typed (serde-skip) llm_metrics field for internal
                            // observation, never reaching the client.
                            let data = if usage_requested {
                                Some(usage_chunk)
                            } else {
                                None
                            };
                            let mut annotated_usage = Annotated::<Resp> {
                                id: None,
                                data,
                                event: None,
                                comment: None,
                                error: None,
                            };
                            attach_llm_metrics(&mut annotated_usage, llm_metrics);
                            Some((annotated_usage, inner))
                        }
                    } else {
                        // stream closed
                        None
                    }
                }
            }
        })
        .fuse()
    }

    /// Transform engine embedding output stream to OpenAI embedding response stream
    pub fn transform_embedding_postprocessor_stream<S>(
        stream: S,
        original_request: NvCreateEmbeddingRequest,
    ) -> impl Stream<Item = Annotated<NvCreateEmbeddingResponse>> + Send
    where
        S: Stream<Item = Annotated<EmbeddingsEngineOutput>> + Send + 'static,
    {
        // The worker always returns base64-encoded little-endian f32 bytes.
        // Pass base64 through, or decode to floats (the public default).
        let encode_base64 = matches!(
            original_request.inner.encoding_format,
            Some(dynamo_protocols::types::EncodingFormat::Base64)
        );
        stream.map(move |output| {
            output.map_data(|engine_output| {
                if engine_output.embeddings.is_empty() {
                    return Err("embedding worker returned an empty `embeddings` field".to_string());
                }
                let embeddings: Vec<dynamo_protocols::types::Embedding> = engine_output
                    .embeddings
                    .into_iter()
                    .enumerate()
                    .map(|(index, encoded)| {
                        let value = if encode_base64 {
                            dynamo_protocols::types::EmbeddingVector::Base64(encoded)
                        } else {
                            dynamo_protocols::types::EmbeddingVector::Float(
                                decode_base64_to_floats(&encoded)?,
                            )
                        };
                        Ok::<_, String>(dynamo_protocols::types::Embedding {
                            index: index as u32,
                            object: "embedding".to_string(),
                            embedding: value,
                        })
                    })
                    .collect::<Result<Vec<_>, String>>()?;

                let response = NvCreateEmbeddingResponse {
                    inner: dynamo_protocols::types::CreateEmbeddingResponse {
                        object: "list".to_string(),
                        model: original_request.inner.model.clone(),
                        data: embeddings,
                        usage: dynamo_protocols::types::EmbeddingUsage {
                            prompt_tokens: engine_output.prompt_tokens,
                            total_tokens: engine_output.total_tokens,
                        },
                    },
                };

                Ok(response)
            })
        })
    }

    /// Determine if we should apply the tool calling jail based on configuration
    /// Returns Ok(true) if jail should be applied, Ok(false) if not, or Err if invalid config
    pub fn should_apply_tool_jail(
        tool_call_parser: Option<&String>,
        tool_choice: Option<&ChatCompletionToolChoiceOption>,
        has_tools: bool,
    ) -> std::result::Result<bool, Error> {
        // Necessary for now because K3 needs a special parser for XTML channel
        // parsing on all responses, regardless of tool or reasoning usage.
        // Keep its parser active so response/message wrappers never leak into
        // OpenAI `content`, even when the request has no tools.
        if tool_call_parser.is_some_and(|parser| matches!(parser.as_str(), "kimi_k3" | "kimi-k3")) {
            return Ok(true);
        }

        match (tool_call_parser, tool_choice, has_tools) {
            // tool_choice=required/named work without parser (use Immediate jail mode)
            (None, Some(ChatCompletionToolChoiceOption::Required), true) => Ok(true),
            (None, Some(ChatCompletionToolChoiceOption::Named(_)), true) => Ok(true),

            // tool_choice=auto requires a parser
            (None, Some(ChatCompletionToolChoiceOption::Auto), true) => {
                tracing::warn!(
                    "Tool choice 'auto' specified but no tool parser configured; proceeding without jailing"
                );
                Ok(false)
            }

            // Parser exists and tools might be called
            (Some(_), Some(ChatCompletionToolChoiceOption::None), _) => {
                Ok(false) // Explicitly disabled
            }
            (Some(_), Some(_), true) => Ok(true), // Any other tool_choice with tools
            (Some(_), None, true) => Ok(true),    // Default behavior when tools present

            // No tools or no parser
            _ => Ok(false),
        }
    }

    /// Whether a forced tool_choice's installed JSON grammar should release
    /// calls incrementally, or fall back to buffer-to-completion.
    ///
    /// The SINGLE owner of that decision, for BOTH streaming paths that can act on
    /// it: the tool-calling jail (`apply_tool_calling_jail`'s `guided_streaming`)
    /// and the unified v2 adapter (`unified_parser::apply_stream_with_constraint`'s
    /// `guided_streaming`, which becomes `StreamBestEffort` vs `RecoverAsText`).
    /// `postprocessor_parsing_stream_with_constraint` calls this once per request
    /// and hands the answer to whichever path runs; neither site re-reads the env
    /// var, because two reads are two predicates that can drift.
    ///
    /// Rollback lever: the grammar-constrained decoding itself lives in the
    /// published `dynamo-parsers` / `dynamo-parsers-v2` dependencies, not in this
    /// repo, so a backend that misbehaves under guided decoding in production has
    /// no same-release fix other than `DYN_ENABLE_GUIDED_TOOL_STREAMING`. On by
    /// default; set it to a falsy value (`0`/`false`) to fall back to
    /// buffer-to-completion.
    fn guided_tool_streaming_release(installs_guided_json: bool, rollback_disabled: bool) -> bool {
        installs_guided_json && !rollback_disabled
    }

    /// Apply tool calling jail to the stream if needed.
    ///
    /// The jail itself now lives in `dynamo-parsers`
    /// (`dynamo_parsers::tool_calling::jail`), where it operates on the shared
    /// `CreateChatCompletionStreamResponse` — dynamo-parsers cannot depend on
    /// dynamo-runtime, so it does not know about `Annotated` or the `Nv`
    /// newtype. This method is the boundary adapter: it unwraps the dynamo
    /// `Annotated<Nv{inner, nvext}>` stream into the jail's
    /// `Annotated<CreateChatCompletionStreamResponse>`, runs the moved jail, and
    /// re-wraps the result.
    ///
    /// The parser can buffer and rewrite several input chunks before it emits an
    /// output. Completion token IDs therefore describe the ordered buffered
    /// group, not the rewritten text in one output delta.
    pub fn apply_tool_calling_jail<S>(
        tool_call_parser: Option<String>,
        tool_choice: Option<dynamo_protocols::types::ChatCompletionToolChoiceOption>,
        tool_definitions: Option<Vec<dynamo_parsers::tool_calling::ToolDefinition>>,
        uses_tool_call_structural_tag: bool,
        guided_streaming: bool,
        stream: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        use dynamo_parsers::tool_calling::jail::{
            Annotated as JailAnnotated, apply_tool_calling_jail,
            apply_tool_calling_jail_with_guided_streaming,
        };
        use std::sync::{Arc, Mutex};

        // The jail operates on the shared `Create` payload and never touches the
        // dynamo-only typed `llm_metrics`, which `transform_postprocessor_stream`
        // stamps *upstream* of the jail. `Create` has no slot for it, so buffer it
        // here on the way in and re-attach on the way out — keeping the metrics off
        // the shared type while preserving them across the boundary.
        //
        // `llm_metrics` is cumulative (`output_tokens`) plus per-chunk
        // (`chunk_tokens`), and the jail may fold N buffered input chunks into one
        // emitted chunk. So accumulate `chunk_tokens` and stamp the running total,
        // with the latest cumulative fields, onto the next emitted data chunk. That
        // preserves what `metrics.rs` records: `observe_response` sums `chunk_tokens`
        // and `observe_current_osl` takes the latest `output_tokens`. (The
        // annotation form on data-less usage chunks rides through untouched via
        // `event`/`comment`.)
        //
        // `nvext` uses the unary aggregator's merge rules: completion token IDs
        // are appended, while the latest supplied value wins for every other
        // top-level field. `engine_data` is replaced as one complete value.
        #[derive(Default)]
        struct PendingDynamoMetadata {
            metrics_template: Option<LLMMetricAnnotation>,
            chunk_tokens: usize,
            nvext: Option<serde_json::Value>,
            response_template: Option<dynamo_protocols::types::CreateChatCompletionStreamResponse>,
        }
        let pending = Arc::new(Mutex::new(PendingDynamoMetadata::default()));
        let pending_in = Arc::clone(&pending);

        // Per-choice recovery state — allocated only for glm47 since only that
        // parser emits <tool_call> XML that can be truncated at max_tokens.
        // Buffers raw input and tracks what the jail emitted per choice.index
        // so n > 1 is handled correctly and double-emit is avoided.
        #[derive(Default)]
        struct ChoiceRecovery {
            input_text: String,
            emitted_text: String,
            recovered: bool,
        }
        // Named so the bool in the recoveries tuple is legible at each use site.
        struct PendingRecovery {
            choice_idx: u32,
            tail: String,
            tail_already_emitted: bool,
        }
        let is_glm47 = tool_call_parser.as_deref() == Some("glm47");
        // Token strings from the parser config so recovery matches the parser
        // even if the defaults are ever overridden.
        let glm47_cfg = dynamo_parsers::tool_calling::config::Glm47ParserConfig::default();
        let glm47_start = glm47_cfg.tool_call_start;
        let glm47_end = glm47_cfg.tool_call_end;
        let choice_recovery: Arc<Mutex<std::collections::HashMap<u32, ChoiceRecovery>>> =
            Arc::new(Mutex::new(std::collections::HashMap::new()));
        let choice_recovery_in = Arc::clone(&choice_recovery);
        let glm47_start_jail = glm47_start.clone();

        // The jail's own (vendored, out-of-scope) finalize logic cannot tell an
        // error-terminated input stream from one that genuinely completed — it
        // sees a plain EOF either way — so on a natural EOF it can synthesize a
        // `tool_calls` finish chunk from whatever partial arguments it had
        // buffered, even though the request actually failed upstream. Both
        // unified adapters (`unified_parser::apply_stream_with_constraint`,
        // `tool_parser_v2::apply_stream`/`apply_unified_stream`) already give a
        // terminal upstream error this exact contract: `yield response; return;`,
        // dropping everything after. Give the jail wrapper the same contract:
        // `terminal_error` latches the first error `Annotated` observed on the
        // way in, `take_while` below stops it from ever reaching the jail (so
        // the jail's finalize never runs on an error-caused EOF at all), and the
        // matching `take_while`/`chain` on the way out (below) drops anything
        // the jail still emits after that point and substitutes the error
        // instead — never letting a synthesized completion reach the caller.
        let terminal_error: Arc<Mutex<Option<Annotated<NvCreateChatCompletionStreamResponse>>>> =
            Arc::new(Mutex::new(None));
        let terminal_error_in = Arc::clone(&terminal_error);
        let stream = stream.take_while(move |a| {
            let is_error = a.is_error();
            if is_error {
                *terminal_error_in
                    .lock()
                    .expect("jail terminal error poisoned") = Some(a.clone());
            }
            std::future::ready(!is_error)
        });

        // dynamo `Annotated<Nv>` -> jail `Annotated<Create>` (buffer Dynamo metadata)
        let jail_input = stream.map(move |mut a| {
            let has_metadata = a
                .data
                .as_ref()
                .is_some_and(|nv| nv.llm_metrics.is_some() || nv.nvext.is_some());
            if has_metadata {
                let mut p = pending_in
                    .lock()
                    .expect("jail Dynamo metadata buffer poisoned");
                if let Some(nv) = a.data.as_mut() {
                    if p.response_template.is_none() {
                        p.response_template = Some(
                            dynamo_protocols::types::CreateChatCompletionStreamResponse {
                                id: nv.inner.id.clone(),
                                object: nv.inner.object.clone(),
                                created: nv.inner.created,
                                model: nv.inner.model.clone(),
                                choices: Vec::new(),
                                usage: None,
                                service_tier: nv.inner.service_tier.clone(),
                                system_fingerprint: nv.inner.system_fingerprint.clone(),
                            },
                        );
                    }
                    if let Some(metrics) = nv.llm_metrics.take() {
                        p.chunk_tokens = p.chunk_tokens.saturating_add(metrics.chunk_tokens);
                        p.metrics_template = Some(metrics);
                    }
                    merge_response_nvext(&mut p.nvext, nv.nvext.take());
                }
            }
            // Buffer input content only for glm47 (truncation recovery).
            // Only retain from the last <tool_call> marker onward to bound
            // memory on long responses.
            if is_glm47 && let Some(data) = &a.data {
                let mut cr = choice_recovery_in.lock().expect("choice recovery poisoned");
                for choice in &data.inner.choices {
                    if let Some(ChatCompletionMessageContent::Text(content)) = &choice.delta.content
                    {
                        let state = cr.entry(choice.index).or_default();
                        state.input_text.push_str(content);
                        // Drop everything before the last marker to keep
                        // the buffer small. Walk back to a char boundary
                        // before draining so a multi-byte char split
                        // across chunks never triggers a panic.
                        let mut keep_from = match state.input_text.rfind(glm47_start_jail.as_str())
                        {
                            Some(pos) => pos,
                            // No marker yet — keep enough tail to
                            // catch a marker split across two chunks.
                            None => state
                                .input_text
                                .len()
                                .saturating_sub(glm47_start_jail.len() - 1),
                        };
                        while keep_from > 0 && !state.input_text.is_char_boundary(keep_from) {
                            keep_from -= 1;
                        }
                        state.input_text.drain(..keep_from);
                    }
                }
            }
            debug_assert!(a.error.is_none(), "terminal errors must bypass the jail");
            JailAnnotated {
                data: a.data.map(|nv| nv.inner),
                id: a.id,
                event: a.event,
                comment: a.comment,
                // Terminal errors were removed by `take_while` above and are
                // chained back as the original typed Dynamo annotation below.
                error: None,
            }
        });

        // jail `Annotated<Create>` -> dynamo `Annotated<Nv>` (re-attach Dynamo metadata)
        // The crate encodes the opt-in in WHICH entry point you call, so pick here and
        // box both arms to one type. `apply_tool_calling_jail` keeps the published
        // five-argument signature for everyone else.
        let jailed: Pin<
            Box<
                dyn Stream<
                        Item = JailAnnotated<
                            dynamo_protocols::types::CreateChatCompletionStreamResponse,
                        >,
                    > + Send,
            >,
        > = if guided_streaming {
            Box::pin(apply_tool_calling_jail_with_guided_streaming(
                tool_call_parser,
                tool_choice,
                tool_definitions,
                uses_tool_call_structural_tag,
                jail_input,
            ))
        } else {
            Box::pin(apply_tool_calling_jail(
                tool_call_parser,
                tool_choice,
                tool_definitions,
                uses_tool_call_structural_tag,
                jail_input,
            ))
        };
        let pending_out = Arc::clone(&pending);
        let pending_eof = Arc::clone(&pending);
        let jailed_output = jailed.flat_map(move |a| {
            debug_assert!(
                a.error.is_none(),
                "dynamo-parsers must not construct errors"
            );
            // Metrics can ride on payload-only usage chunks because the HTTP
            // layer observes them before removing the chunk. Client-visible
            // nvext must wait for a non-payload-usage output with a choice.
            let has_choices = a.data.as_ref().is_some_and(|data| !data.choices.is_empty());
            let is_payload_usage = a.event.as_deref() == Some(ANNOTATION_PAYLOAD_USAGE);
            let (llm_metrics, nvext) = a.data.as_ref().map_or((None, None), |_| {
                let mut p = pending_out
                    .lock()
                    .expect("jail Dynamo metadata buffer poisoned");
                let chunk_tokens = p.chunk_tokens;
                p.chunk_tokens = 0;
                let metrics = p.metrics_template.take().map(|mut metrics| {
                    metrics.chunk_tokens = chunk_tokens;
                    metrics
                });
                let nvext = if has_choices && !is_payload_usage {
                    p.nvext.take()
                } else {
                    None
                };
                (metrics, nvext)
            });
            let mut nv_chunk = Annotated {
                data: a.data.map(|inner| NvCreateChatCompletionStreamResponse {
                    inner,
                    nvext,
                    llm_metrics,
                }),
                id: a.id,
                event: a.event,
                comment: a.comment,
                // dynamo-parsers never constructs errors; Dynamo's original
                // typed terminal annotation bypasses this conversion.
                error: None,
            };

            // glm47: on finish_reason=length, recover the last incomplete
            // <tool_call> block. rfind skips complete blocks so earlier parsed
            // calls are never duplicated. Recovered content WILL contain raw
            // markup — callers that require "no tool tags in content" must
            // filter on finish_reason=length.
            //
            // TODO: this recovery runs inside apply_tool_calling_jail, which
            // the v2 path bypasses (use_parsers_v2 branch above). Adding
            // "glm47" to V2_FAMILIES in tool_parser_v2.rs silently disables
            // streaming recovery while aggregator.rs keeps running. At that
            // point hoist this above the jail/v2 branch — it only needs
            // buffered input text + finish_reason, both available there.
            // Pass 1 (immutable): compute the recovery tail per choice and
            // whether the jail already released it as content on this chunk.
            // We collect into a Vec so we can release the immutable borrow on
            // nv_chunk before mutating it in pass 2.
            let recoveries: Vec<PendingRecovery> = if is_glm47 {
                let mut cr = choice_recovery.lock().expect("choice recovery poisoned");
                nv_chunk
                    .data
                    .iter()
                    .flat_map(|data| data.inner.choices.iter())
                    .filter_map(|choice| {
                        let state = cr.entry(choice.index).or_default();
                        if !state.recovered
                            && let Some(ChatCompletionMessageContent::Text(t)) =
                                &choice.delta.content
                        {
                            state.emitted_text.push_str(t);
                            // Bound like input_text: retain only the suffix from
                            // the last marker onward — all the contains(&tail)
                            // check needs.
                            let mut keep_from = match state.emitted_text.rfind(glm47_start.as_str())
                            {
                                Some(pos) => pos,
                                None => state
                                    .emitted_text
                                    .len()
                                    .saturating_sub(glm47_start.len() - 1),
                            };
                            while keep_from > 0 && !state.emitted_text.is_char_boundary(keep_from) {
                                keep_from -= 1;
                            }
                            state.emitted_text.drain(..keep_from);
                        }
                        if state.recovered
                            || !matches!(
                                choice.finish_reason,
                                Some(dynamo_protocols::types::FinishReason::Length)
                            )
                        {
                            return None;
                        }
                        let tail =
                            state
                                .input_text
                                .rfind(glm47_start.as_str())
                                .and_then(|pos| {
                                    let t = &state.input_text[pos..];
                                    if !t.contains(glm47_end.as_str()) {
                                        Some(t.to_string())
                                    } else {
                                        None
                                    }
                                })?;
                        let tail_already_emitted = state.emitted_text.contains(&tail);
                        state.recovered = true;
                        Some(PendingRecovery {
                            choice_idx: choice.index,
                            tail,
                            tail_already_emitted,
                        })
                    })
                    .collect()
            } else {
                vec![]
            };

            // Pass 2 (mutable): when the jail already released the tail verbatim,
            // suppress the finish chunk's content entirely. The recovery chunk
            // carries just the marker-onwards tail, matching the non-streaming
            // path (rfind result only, no post-call prose).
            for pr in &recoveries {
                if !pr.tail_already_emitted {
                    continue;
                }
                if let Some(ref mut data) = nv_chunk.data {
                    for rc in data
                        .inner
                        .choices
                        .iter_mut()
                        .filter(|c| c.index == pr.choice_idx)
                    {
                        // The jail released the truncated block verbatim as content
                        // on this chunk, potentially preceded by post-call prose.
                        // glm47's parser drops post-call prose deliberately, so
                        // suppress the whole content here and let the recovery
                        // chunk carry just the marker-onwards tail — matching batch.
                        rc.delta.content = None;
                    }
                }
            }

            // Pass 3: emit a recovery chunk per affected choice carrying just
            // the truncated tail (marker onwards, no post-call prose).
            let recovery_chunks: Vec<_> = recoveries
                .into_iter()
                .filter_map(|pr| {
                    let PendingRecovery {
                        choice_idx, tail, ..
                    } = pr;
                    tracing::warn!(
                        choice_index = choice_idx,
                        recovered_bytes = tail.len(),
                        "glm47 streaming: partial <tool_call> emitted as content \
                         on length finish"
                    );
                    let mut rec = nv_chunk.clone();
                    rec.id = None;
                    scrub_synthetic_chunk_metadata(&mut rec);
                    let rd = rec.data.as_mut()?;
                    rd.inner.choices.retain(|c| c.index == choice_idx);
                    for rc in &mut rd.inner.choices {
                        rc.delta.content = Some(ChatCompletionMessageContent::Text(tail.clone()));
                        rc.delta.tool_calls = None;
                        rc.finish_reason = None;
                        rc.logprobs = None;
                    }
                    Some(rec)
                })
                .collect();

            futures::stream::iter(recovery_chunks.into_iter().chain(std::iter::once(nv_chunk)))
        });

        // Once an upstream error is latched, drop any output the jail synthesized
        // while it observed the shortened stream. The wrapper below then emits only
        // the original error and discards all pending metadata and usage.
        let terminal_error_out = Arc::clone(&terminal_error);
        let jailed_output = jailed_output.take_while(move |_| {
            let stop = terminal_error_out
                .lock()
                .expect("jail terminal error poisoned")
                .is_some();
            std::future::ready(!stop)
        });

        let with_eof_metadata = async_stream::stream! {
            tokio::pin!(jailed_output);
            while let Some(response) = jailed_output.next().await {
                yield response;
            }

            let terminal_error = {
                terminal_error
                    .lock()
                    .expect("jail terminal error poisoned")
                    .take()
            };
            if let Some(error) = terminal_error {
                {
                    let mut p = pending_eof
                        .lock()
                        .expect("jail Dynamo metadata buffer poisoned");
                    p.metrics_template = None;
                    p.chunk_tokens = 0;
                    p.nvext = None;
                    p.response_template = None;
                }
                yield error;
                return;
            }

            let eof_metadata = {
                let mut p = pending_eof
                    .lock()
                    .expect("jail Dynamo metadata buffer poisoned");
                let chunk_tokens = p.chunk_tokens;
                p.chunk_tokens = 0;
                let llm_metrics = p.metrics_template.take().map(|mut metrics| {
                    metrics.chunk_tokens = chunk_tokens;
                    metrics
                });
                let nvext = p.nvext.take();
                if llm_metrics.is_none() && nvext.is_none() {
                    None
                } else {
                    p.response_template.take().map(|inner| Annotated {
                        data: Some(NvCreateChatCompletionStreamResponse {
                            inner,
                            nvext,
                            llm_metrics,
                        }),
                        id: None,
                        event: None,
                        comment: None,
                        error: None,
                    })
                }
            };
            if let Some(response) = eof_metadata {
                yield response;
            }
        };

        Self::hold_usage_until_stream_end(with_eof_metadata)
    }

    /// Whether the selected tool-call or reasoning parser depends on the
    /// engine emitting special tokens (e.g. Gemma 4's `<|tool_call>` /
    /// `<|channel>`). Mirrors upstream vLLM's per-parser `adjust_request`
    /// hooks. Used to flip the request default for `skip_special_tokens`
    /// from `true` to `false` so the parsers actually see the markers
    /// they're matching on.
    fn parser_requires_special_tokens(
        tool_call_parser: Option<&str>,
        reasoning_parser: Option<&str>,
    ) -> bool {
        // Parsers in this allow-list match against special tokens that the
        // tokenizer would otherwise strip when `skip_special_tokens=true`
        // (the OpenAI-API default). Without the tokens preserved through
        // decode the parsers silently produce empty reasoning_content /
        // tool_calls.
        //
        // - gemma4: `<|think|>` prompt trigger plus parser-visible
        //   `<|channel>` / `<channel|>` reasoning markers and tool-call markers.
        // - harmony / gpt_oss: `<|channel|>analysis<|message|>...<|end|>`.
        // - kimi_k2: `<|tool_calls_section_begin|>` / `<|tool_calls_section_end|>`.
        // - kimi_k25: `</think>` (special token id 163607).
        // - kimi_k3: `<|open|>` / `<|close|>` / `<|sep|>` XTML markers.
        // - mistral: `[THINK]` / `[/THINK]` reasoning markers.
        // - minimax_m3: `]<]minimax[>[` tool-call namespace tokens and
        //   `<mm:think>` reasoning markers.
        // - inkling: `<|message_model|>` / `<|content_thinking|>` /
        //   `<|content_text|>` / `<|content_invoke_tool_json|>` / `<|end_message|>`
        //   channel markers, consumed by both the tool-call and reasoning parsers.
        // - muse_glimmer: `<|start|>` / `<|message|>` / `<|eom|>` / `<|eot|>`
        //   channel markers, consumed by the unified parser (reasoning + content +
        //   tool calls); matched on either parser name since the card may set only
        //   the reasoning name.
        matches!(
            tool_call_parser,
            Some("gemma4")
                | Some("gemma-4")
                | Some("harmony")
                | Some("kimi_k2")
                | Some("kimi_k3")
                | Some("kimi-k3")
                | Some("minimax_m3")
                | Some("minimax-m3")
                | Some("minimax_m3_nom")
                | Some("minimax-m3-nom")
                | Some("inkling")
                | Some("muse_glimmer")
                | Some("muse")
        ) || matches!(
            reasoning_parser,
            Some("gemma4")
                | Some("gemma-4")
                | Some("gpt_oss")
                | Some("kimi_k25")
                | Some("kimi_k3")
                | Some("kimi-k3")
                | Some("mistral")
                | Some("minimax_m3")
                | Some("minimax-m3")
                | Some("inkling")
                | Some("muse_glimmer")
                | Some("muse")
        )
    }

    /// Whether the resolved `skip_special_tokens` will strip the special-token
    /// markers an active parser depends on — guaranteeing the parser silently
    /// emits empty tool_calls / reasoning_content and the markup leaks into
    /// `content`. Only true when the caller explicitly forced
    /// `skip_special_tokens=true` while a special-token-dependent parser is
    /// active; otherwise the default is flipped to false before this check.
    fn special_tokens_will_be_stripped(
        skip_special_tokens: Option<bool>,
        tool_call_parser: Option<&str>,
        reasoning_parser: Option<&str>,
    ) -> bool {
        skip_special_tokens == Some(true)
            && Self::parser_requires_special_tokens(tool_call_parser, reasoning_parser)
    }

    fn is_nemotron_force_reasoning(reasoning_parser: Option<&str>) -> bool {
        matches!(
            reasoning_parser,
            Some("nemotron_nano" | "nemotron3" | "nemotron_v3")
        )
    }

    /// Whether a request should surface parsed `reasoning_content` as `content`
    /// when no content was generated: any request carrying
    /// `force_nonempty_content=true`.
    ///
    /// Deliberately NOT keyed on the model or its reasoning parser. The flag is a
    /// request-level contract — "this response will have non-empty content" — so
    /// it is honored generically after parsing and before the response is sent,
    /// rather than being reimplemented inside each model-specific parser. Keying
    /// it on a parser allow-list means every new alias silently loses the
    /// behavior until someone edits the list.
    ///
    /// Note it rides in on `chat_template_args` but is NOT consumed by the chat
    /// template: the Nemotron template never reads `force_nonempty_content`, and
    /// rendering with it set produces a byte-identical prompt. It is a
    /// serving-layer flag that upstream happens to transport through the template
    /// kwargs, which is why the check belongs in postprocessing and not in a
    /// parser. So a client can set it on any model, and doing so is an explicit
    /// request for non-empty content — honoring it generically is the intent, not
    /// an accident of where the flag is declared.
    ///
    /// Drives both paths. The chat and Anthropic HTTP handlers pass it to the
    /// aggregator via `ParsingOptions::move_reasoning_to_content_when_empty` for
    /// non-streaming, and `postprocessor_parsing_stream` passes it as
    /// `defer_reasoning_for_nonempty_content` so the streaming path can hold
    /// reasoning back and reach the same answer at the terminal chunk. Both must
    /// use this one predicate or the two paths would disagree on the same input.
    ///
    /// `enable_thinking` is intentionally not consulted here: when thinking is
    /// off, reasoning parsing is disabled, so `reasoning_content` is always empty
    /// and the move is vacuous rather than suppressed.
    pub(crate) fn wants_reasoning_as_content_when_empty(
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
    ) -> bool {
        chat_template_args.is_some_and(|args| {
            args.get("force_nonempty_content") == Some(&serde_json::Value::Bool(true))
        })
    }

    /// Whether this request's stream can withhold every data frame while it
    /// buffers, which is the only reason to force SSE keep-alive frames on.
    ///
    /// The HTTP handlers used to gate the heartbeat on
    /// `wants_reasoning_as_content_when_empty && reasoning_parser.is_some()`,
    /// but that is broader than the deferral it describes: the buffering only
    /// runs when `postprocessor_parsing_stream` takes its `should_parse_reasoning`
    /// branch. A `force_nonempty_content=true` request with reasoning disabled
    /// (`enable_thinking=false`) defers nothing, yet still got heartbeats — and
    /// the configured interval is opt-in precisely because some
    /// OpenAI-compatible clients do not ignore SSE comment frames.
    ///
    /// Known gap: `skip_reasoning_for_guided_json` also suppresses the deferral,
    /// but it is derived from guided-output inspection that is not available at
    /// the HTTP layer, so a guided-JSON bypass still enables the heartbeat when
    /// nothing is withheld. That direction is conservative — extra comment
    /// frames on an opt-in path rather than a silent stream — and closing it
    /// needs the guided-output derivation lifted out of the stream builder.
    pub(crate) fn stream_can_defer_all_output(
        tool_call_parser: Option<&str>,
        reasoning_parser: Option<&str>,
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
    ) -> bool {
        // Unified Qwen and Muse now use the same force-nonempty deferral as the v1
        // reasoning path, so their reasoning-only turns can withhold every meaningful
        // output delta until the terminal decision too.
        let has_reasoning_decoder = reasoning_parser.is_some()
            || crate::protocols::openai::chat_completions::tool_parser_v2::unified_family(
                tool_call_parser,
                reasoning_parser,
            )
            .is_some();
        has_reasoning_decoder
            && Self::wants_reasoning_as_content_when_empty(chat_template_args)
            && !Self::is_reasoning_disabled_by_request(reasoning_parser, chat_template_args)
    }

    /// Parsers that begin streaming in reasoning mode (force_reasoning=true).
    /// These swallow any leading text without an open `<think>` tag as
    /// reasoning_content, so they cannot run on guided-decoding output where
    /// the model emits bare JSON from token 0.
    fn is_force_reasoning_parser(reasoning_parser: Option<&str>) -> bool {
        matches!(
            reasoning_parser,
            Some(
                "deepseek_r1"
                    | "deepseek_v3"
                    | "deepseek_v3_1"
                    | "deepseek_v3_2"
                    | "step3"
                    | "kimi_k25"
                    | "mistral"
                    | "minimax_m2"
                    | "minimax_append_think"
                    | "nemotron_nano"
                    | "nemotron3"
                    | "nemotron_v3"
            )
        )
    }

    /// Force-reasoning parsers proven to receive both bare guided JSON and
    /// native-reasoner-gated `reasoning</think>JSON`. These use the stream-shape
    /// detector instead of the historical unconditional guided-JSON bypass.
    fn supports_reasoning_before_guided_json(reasoning_parser: Option<&str>) -> bool {
        matches!(
            reasoning_parser,
            Some(
                "deepseek_r1"
                    | "deepseek_v3"
                    | "deepseek_v3_1"
                    | "deepseek_v3_2"
                    | "step3"
                    | "kimi_k25"
                    | "mistral"
                    | "minimax_m2"
                    | "nemotron_nano"
                    | "nemotron3"
                    | "nemotron_v3"
            )
        )
    }

    /// Reasoning openers that overlap with a valid guided-JSON prefix.
    fn guided_json_reasoning_start_token(reasoning_parser: Option<&str>) -> Option<&'static str> {
        match reasoning_parser {
            Some("mistral") => Some("[THINK]"),
            _ => None,
        }
    }

    fn skips_guided_json_when_prompt_injected(reasoning_parser: Option<&str>) -> bool {
        matches!(
            reasoning_parser,
            Some(
                "deepseek_v4"
                    | "deepseek-v4"
                    | "deepseekv4"
                    | "glm45"
                    | "minimax_m3"
                    | "minimax-m3"
            )
        )
    }

    fn skips_structured_response_when_prompt_injected(reasoning_parser: Option<&str>) -> bool {
        matches!(reasoning_parser, Some("qwen3" | "kimi_k3" | "kimi-k3"))
            || Self::skips_guided_json_when_prompt_injected(reasoning_parser)
    }

    fn prompt_injected_reasoning_start(
        reasoning_parser: Option<&str>,
        formatted_prompt: Option<&str>,
    ) -> bool {
        let Some(prompt) = formatted_prompt.map(str::trim_end) else {
            return false;
        };

        match reasoning_parser {
            Some("minimax_m3") | Some("minimax-m3") => prompt.ends_with("<mm:think>"),
            Some("kimi_k3") | Some("kimi-k3") => prompt.ends_with("<|open|>think<|sep|>"),
            _ => prompt.ends_with("<think>"),
        }
    }

    fn prompt_injected_reasoning_ended_arg(
        reasoning_parser: Option<&str>,
        formatted_prompt: Option<&str>,
    ) -> Option<bool> {
        let should_forward = matches!(
            reasoning_parser,
            Some("minimax_m2" | "minimax_m3" | "minimax-m3" | "kimi_k3" | "kimi-k3")
        );
        if should_forward
            && Self::prompt_injected_reasoning_start(reasoning_parser, formatted_prompt)
        {
            Some(false)
        } else {
            None
        }
    }

    /// Check if reasoning parsing should be disabled based on per-request parameters.
    /// For kimi_k25/K3: disabled when chat_template_args contains "thinking": false.
    /// For Nemotron force-reasoning aliases: disabled when chat_template_args
    ///   contains "enable_thinking": false. "force_nonempty_content": true does
    ///   NOT disable parsing (streaming or non-streaming): the parser stays on so
    ///   reasoning is split from the answer, and reasoning is surfaced as content
    ///   only when no content was generated (non-streaming, in the aggregator).
    /// For DeepSeek: follows the same effective mode used by the prompt renderer.
    /// For Mistral: disabled unless `reasoning_effort` is present and not `none`.
    /// For Gemma 4: reasoning is opt-in and disabled unless chat_template_args
    ///   explicitly enables thinking. Gemma 4's chat template injects reasoning
    ///   markers only when enable_thinking=true.
    /// For MiniMax M3: disabled when chat_template_args contains
    ///   "thinking_mode": "disabled", matching SGLang's MiniMax M3 request
    ///   convention.
    fn is_reasoning_disabled_by_request(
        reasoning_parser: Option<&str>,
        chat_template_args: Option<&std::collections::HashMap<String, serde_json::Value>>,
    ) -> bool {
        match reasoning_parser {
            Some("kimi_k25" | "kimi_k3" | "kimi-k3") => {
                dynamo_renderer::thinking_bool_from_args(chat_template_args) == Some(false)
            }
            parser if Self::is_nemotron_force_reasoning(parser) => {
                // `enable_thinking=false` turns reasoning off entirely (streaming
                // and non-streaming). `force_nonempty_content=true` does NOT
                // disable parsing: keeping the parser on splits reasoning from the
                // answer, so a reasoning+answer turn no longer leaks the reasoning
                // text and `</think>` into `content`.
                //
                // The reasoning-*only* move (surface reasoning as content when the
                // answer is empty) happens on both paths, by different means.
                // Non-streaming uses the aggregator flag
                // ParsingOptions::move_reasoning_to_content_when_empty. Streaming
                // cannot retract a reasoning_content delta already sent, so it
                // instead holds reasoning back until it knows whether an answer
                // follows — see `defer_reasoning_for_nonempty_content` and
                // `drain_deferred_reasoning`. Both end with the same contract: a
                // reasoning-only turn surfaces its text as `content`.
                dynamo_renderer::thinking_bool_from_args(chat_template_args) == Some(false)
            }
            Some("deepseek_v3" | "deepseek_v3_1") => {
                !Self::deepseek_renderer_reasoning_enabled(chat_template_args, false)
            }
            Some(
                "deepseek_r1" | "deepseek_v3_2" | "deepseek_v4" | "deepseek-v4" | "deepseekv4"
                | "minimax_m2",
            ) => !Self::deepseek_renderer_reasoning_enabled(chat_template_args, true),
            Some("gemma4") | Some("gemma-4") => {
                dynamo_renderer::thinking_bool_from_args(chat_template_args) != Some(true)
            }
            Some("mistral") => !Self::mistral_reasoning_enabled(chat_template_args),
            Some("minimax_m3") | Some("minimax-m3") => {
                if let Some(args) = chat_template_args
                    && let Some(mode) = args.get("thinking_mode").and_then(|v| v.as_str())
                {
                    return mode == "disabled";
                }
                false
            }
            _ => false,
        }
    }

    // Motivation: Each transformation on the stream should be a separate step to allow for more flexibility
    // Earlier reasoning parser logic was nested under delta generation logic in choice_from_postprocessor
    // Since we have tool calling parsing as separate step, it makes sense to have reasoning parser as separate step as well
    /// Apply reasoning parsing to the output stream, splitting content into
    /// `reasoning_content` and normal `content` based on think tags.
    ///
    /// When `prompt_injected_reasoning` is `true`, the parser starts in reasoning
    /// mode immediately — use this when the chat template already appended the
    /// reasoning start token (e.g., `<think>`) to the prompt, so the model's
    /// completion begins with thinking content without an explicit start tag.
    pub fn parse_reasoning_content_from_stream<S>(
        stream: S,
        parser_name: String,
        prompt_injected_reasoning: bool,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        Self::parse_reasoning_content_from_stream_inner(
            stream,
            parser_name,
            prompt_injected_reasoning,
            false,
            false,
        )
    }

    fn parse_reasoning_content_from_stream_inner<S>(
        stream: S,
        parser_name: String,
        prompt_injected_reasoning: bool,
        bypass_bare_guided_json: bool,
        defer_reasoning_for_nonempty_content: bool,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        // Parsers and bypass decisions are created lazily per `choice.index`
        // inside the unfold loop, so `n > 1` choices never share state.
        let state = ReasoningState {
            stream: Box::pin(stream),
            parser_name,
            prompt_injected_reasoning,
            bypass_bare_guided_json,
            choices: HashMap::new(),
            last_response: None,
            defer_reasoning_for_nonempty_content,
            saw_terminal_error: false,
        };

        stream::unfold(state, |mut state| async move {
            if let Some(response) = state.stream.next().await {
                // An error is terminal for the flush: latch it so the
                // end-of-stream branch below stays quiet. The chunk still takes
                // the normal path — `is_error()` keys on the annotation event,
                // not on `data`, so short-circuiting here would change how a
                // data-carrying error chunk is processed.
                if response.is_error() {
                    state.saw_terminal_error = true;
                }
                // Split disjoint field borrows so the per-choice map and the
                // parser-factory inputs can be used together inside map_data.
                // Scoped in a block so the borrows end before `state` moves.
                let processed_response = {
                    let ReasoningState {
                        parser_name,
                        prompt_injected_reasoning,
                        bypass_bare_guided_json,
                        choices,
                        defer_reasoning_for_nonempty_content,
                        ..
                    } = &mut state;
                    let parser_name = &*parser_name;
                    let prompt_injected_reasoning = *prompt_injected_reasoning;
                    let bypass_bare_guided_json = *bypass_bare_guided_json;
                    let defer_reasoning = *defer_reasoning_for_nonempty_content;

                    response.map_data(|mut data| {
                        for choice in data.inner.choices.iter_mut() {
                            let choice_state = choices.entry(choice.index).or_insert_with(|| {
                                let mut parser =
                                    Box::new(ReasoningParserType::get_reasoning_parser_from_name(
                                        parser_name,
                                    ))
                                        as Box<dyn ReasoningParser>;
                                if prompt_injected_reasoning {
                                    parser.set_in_reasoning(true);
                                }
                                ChoiceReasoningState {
                                    parser,
                                    guided_json_bypass_decision: (!bypass_bare_guided_json)
                                        .then_some(false),
                                    pending_reasoning: String::new(),
                                    pending_content: String::new(),
                                    left_reasoning: false,
                                    drained: false,
                                    parser_finished: false,
                                }
                            });

                            // Decide once per choice, from ITS OWN first
                            // non-whitespace content, whether the backend
                            // emitted bare guided JSON (`[`/`{`) that must reach
                            // the tool jail unparsed.
                            let bypass_decision = if bypass_bare_guided_json {
                                match choice_state.guided_json_bypass_decision {
                                    Some(decision) => Some(decision),
                                    None => {
                                        let decision = match choice.delta.content.as_ref() {
                                            Some(ChatCompletionMessageContent::Text(text)) => {
                                                let text = text.trim_start();
                                                if text.is_empty() {
                                                    None
                                                } else {
                                                    Some(matches!(text.as_bytes()[0], b'[' | b'{'))
                                                }
                                            }
                                            _ => None,
                                        };
                                        if let Some(decision) = decision {
                                            choice_state.guided_json_bypass_decision =
                                                Some(decision);
                                        }
                                        decision
                                    }
                                }
                            } else {
                                Some(false)
                            };

                            // Only a choice decided NOT to bypass is parsed. A
                            // bare-JSON or still-undecided (whitespace-only)
                            // choice keeps its content untouched for the jail.
                            // Reasoning parsing only applies to text content;
                            // multimodal content passes through unchanged.
                            if bypass_decision == Some(false)
                                && let Some(ChatCompletionMessageContent::Text(text)) =
                                    choice.delta.content.as_ref()
                            {
                                let parser_result = choice_state
                                    .parser
                                    .parse_reasoning_streaming_incremental(text, &[]);

                                // A backend that keeps sending content after this
                                // choice's `finish_reason` is out of protocol, but
                                // it has still fed bytes to the parser. Reopen the
                                // drain so they have somewhere to go at EOF instead
                                // of being stranded in parser state.
                                choice_state.drained = false;

                                if defer_reasoning && !choice_state.left_reasoning {
                                    // Still ambiguous: this text may be reasoning
                                    // followed by an answer, or the answer itself
                                    // reported as reasoning because the parser
                                    // starts inside the reasoning block. Hold it.
                                    choice_state
                                        .pending_reasoning
                                        .push_str(&parser_result.reasoning_text);
                                    // Whitespace-only normal text does not settle
                                    // anything: the aggregator treats such content
                                    // as empty (matching vLLM's
                                    // `not final_content.strip()`), so releasing
                                    // here would make streaming and non-streaming
                                    // disagree on the same turn. Hold it with the
                                    // reasoning until real answer text arrives.
                                    if parser_result.normal_text.trim().is_empty() {
                                        choice_state
                                            .pending_content
                                            .push_str(&parser_result.normal_text);
                                        choice.delta.content = None;
                                        choice.delta.reasoning_content = None;
                                    } else {
                                        // Real answer text means the parser left
                                        // the reasoning block, so everything held
                                        // so far really was reasoning.
                                        choice_state.left_reasoning = true;
                                        choice.delta.reasoning_content = (!choice_state
                                            .pending_reasoning
                                            .is_empty())
                                        .then(|| {
                                            std::mem::take(&mut choice_state.pending_reasoning)
                                        });
                                        let mut text =
                                            std::mem::take(&mut choice_state.pending_content);
                                        text.push_str(&parser_result.normal_text);
                                        choice.delta.content =
                                            Some(ChatCompletionMessageContent::Text(text));
                                    }
                                } else {
                                    choice.delta.content = parser_result
                                        .get_some_normal_text()
                                        .map(ChatCompletionMessageContent::Text);
                                    choice.delta.reasoning_content =
                                        parser_result.get_some_reasoning();
                                }
                            }

                            // This choice is finishing, so drain what it holds
                            // onto THIS delta. Emitting it as a later chunk
                            // would put content after `finish_reason` (and
                            // after the trailing usage chunk), where a client
                            // that stops at the terminal chunk never sees it.
                            // A parts delta has no text slot to append to, so
                            // draining onto it would leave the recovered text
                            // nowhere to go. Leave the choice undrained and let
                            // the end-of-stream fallback emit it as its own
                            // chunk instead of dropping it.
                            let terminal_carries_parts = matches!(
                                choice.delta.content,
                                Some(ChatCompletionMessageContent::Parts(_))
                            );
                            // Also require that this choice was actually parsed.
                            // A guided-JSON choice that bypassed the parser never
                            // fed it anything, so finishing that parser could only
                            // contribute text the choice never generated.
                            if defer_reasoning
                                && choice.finish_reason.is_some()
                                && !terminal_carries_parts
                                && bypass_decision == Some(false)
                            {
                                let (content, reasoning) = drain_deferred_reasoning(choice_state);
                                if let Some(content) = content {
                                    let merged = match choice.delta.content.take() {
                                        Some(ChatCompletionMessageContent::Text(existing)) => {
                                            existing + &content
                                        }
                                        Some(other) => {
                                            // Unreachable: guarded above.
                                            choice.delta.content = Some(other);
                                            content
                                        }
                                        None => content,
                                    };
                                    if choice.delta.content.is_none() {
                                        choice.delta.content =
                                            Some(ChatCompletionMessageContent::Text(merged));
                                    }
                                }
                                if let Some(reasoning) = reasoning {
                                    choice.delta.reasoning_content = Some(
                                        choice.delta.reasoning_content.take().unwrap_or_default()
                                            + &reasoning,
                                    );
                                }
                            }
                        }
                        Ok(data)
                    })
                };

                // Retain a spare envelope only when an EOF flush may follow, so
                // the common reasoning path avoids a full per-token clone. Skip
                // chunks with no choices (the trailing usage-only chunk): they
                // carry no delta slot, so using one as the flush envelope would
                // drop the very bytes the flush exists to preserve.
                if state.defer_reasoning_for_nonempty_content
                    && processed_response
                        .data
                        .as_ref()
                        .is_some_and(|data| !data.inner.choices.is_empty())
                {
                    state.last_response = Some(processed_response.clone());
                }
                Some((processed_response, state))
            } else if !state.defer_reasoning_for_nonempty_content || state.saw_terminal_error {
                // After a backend error the buffered bytes are dropped rather
                // than surfaced: the request failed, so there is no answer to
                // complete. See `saw_terminal_error`.
                None
            } else {
                // Upstream ended with no answer for the choices still holding a
                // pending buffer. Normally the terminal chunk already drained
                // them, so this is the fallback for a stream that ends without
                // any `finish_reason` — an aborted or truncated generation.
                // The synthetic chunk it builds is the only case where recovered
                // bytes arrive after the last upstream chunk, which is
                // unavoidable when there was no terminal chunk to attach them
                // to. Only the force_nonempty_content path reaches this branch;
                // every other parser took the `None` branch above and keeps its
                // original no-flush EOF behavior. Taking the envelope below
                // rather than cloning it makes this branch one-shot: once it is
                // gone the next poll ends the stream.
                // Sorted so the emitted choice order is deterministic rather
                // than following HashMap iteration order.
                let mut indices: Vec<u32> = state.choices.keys().copied().collect();
                indices.sort_unstable();
                #[allow(clippy::type_complexity)]
                let flushed: Vec<(u32, Option<String>, Option<String>)> = indices
                    .into_iter()
                    .filter_map(|index| {
                        let choice_state = state.choices.get_mut(&index)?;
                        if choice_state.guided_json_bypass_decision != Some(false) {
                            return None;
                        }
                        let (content, reasoning) = drain_deferred_reasoning(choice_state);
                        (content.is_some() || reasoning.is_some())
                            .then_some((index, content, reasoning))
                    })
                    .collect();
                if flushed.is_empty() {
                    return None;
                }
                let mut response = state.last_response.take()?;
                // See `scrub_synthetic_chunk_metadata`: this chunk produced no
                // tokens, so every per-chunk field from the envelope it was
                // cloned from has to be dropped rather than reported twice.
                scrub_synthetic_chunk_metadata(&mut response);
                let data = response.data.as_mut()?;
                // Rebuild the choice list from the flushed indices rather than
                // reusing the envelope's own choices: with `n > 1` the last
                // content-bearing chunk carries only the choices that happened
                // to be interleaved into it, which need not be the set that has
                // buffered bytes.
                let template = data.inner.choices.first()?.clone();
                data.inner.choices = flushed
                    .into_iter()
                    .map(|(index, content, reasoning)| {
                        let mut choice = template.clone();
                        choice.index = index;
                        choice.delta.role = None;
                        choice.delta.tool_calls = None;
                        choice.delta.function_call = None;
                        choice.delta.refusal = None;
                        choice.finish_reason = None;
                        choice.logprobs = None;
                        choice.delta.content = content.map(ChatCompletionMessageContent::Text);
                        choice.delta.reasoning_content = reasoning;
                        choice
                    })
                    .collect();
                Some((response, state))
            }
        })
        .fuse()
    }

    /// Apply the request-level non-empty-content contract after a unified parser has
    /// already split reasoning, content, and tool calls.
    fn defer_unified_reasoning_for_nonempty_content<S>(
        stream_in: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        async_stream::stream! {
            let mut states: HashMap<u32, DeferredUnifiedChoice> = HashMap::new();
            let mut last_response: Option<Annotated<NvCreateChatCompletionStreamResponse>> = None;
            tokio::pin!(stream_in);

            while let Some(mut response) = stream_in.next().await {
                if response.is_error() {
                    yield response;
                    return;
                }
                let Some(data) = response.data.as_mut() else {
                    yield response;
                    continue;
                };
                let mut prefix_choices = Vec::new();

                for choice in &mut data.inner.choices {
                    let state = states.entry(choice.index).or_default();
                    if choice.delta.content.is_some()
                        || choice.delta.reasoning_content.is_some()
                        || choice.delta.tool_calls.is_some()
                    {
                        state.drained = false;
                    }

                    if !state.saw_visible_output
                        && let Some(reasoning) = choice.delta.reasoning_content.take()
                    {
                        state.pending_reasoning.push_str(&reasoning);
                    }

                    let carries_parts = matches!(
                        choice.delta.content,
                        Some(ChatCompletionMessageContent::Parts(_))
                    );
                    match choice.delta.content.take() {
                        Some(ChatCompletionMessageContent::Text(text)) => {
                            if !state.saw_visible_output && text.trim().is_empty() {
                                state.pending_content.push_str(&text);
                            } else {
                                if !text.trim().is_empty() {
                                    state.saw_visible_output = true;
                                }
                                let mut content = std::mem::take(&mut state.pending_content);
                                content.push_str(&text);
                                choice.delta.content =
                                    Some(ChatCompletionMessageContent::Text(content));
                            }
                        }
                        Some(parts @ ChatCompletionMessageContent::Parts(_)) => {
                            choice.delta.content = Some(parts);
                        }
                        None => {}
                    }

                    let has_tool_calls = choice
                        .delta
                        .tool_calls
                        .as_ref()
                        .is_some_and(|calls| !calls.is_empty());
                    if carries_parts || has_tool_calls {
                        state.saw_visible_output = true;
                    }
                    if carries_parts {
                        state.pending_content.clear();
                    }

                    if state.saw_visible_output {
                        let (content, reasoning) = state.release_split();
                        if let Some(reasoning) = reasoning {
                            let mut prefix = choice.clone();
                            prefix.delta.role = None;
                            prefix.delta.content = None;
                            prefix.delta.tool_calls = None;
                            prefix.delta.function_call = None;
                            prefix.delta.refusal = None;
                            prefix.delta.reasoning_content = Some(reasoning);
                            prefix.finish_reason = None;
                            prefix.logprobs = None;
                            prefix_choices.push(prefix);
                        }
                        if let Some(content) = content {
                            match choice.delta.content.as_mut() {
                                Some(ChatCompletionMessageContent::Text(existing)) => {
                                    existing.insert_str(0, &content);
                                }
                                Some(ChatCompletionMessageContent::Parts(_)) | None => {
                                    let mut prefix = choice.clone();
                                    prefix.delta.role = None;
                                    prefix.delta.content =
                                        Some(ChatCompletionMessageContent::Text(content));
                                    prefix.delta.tool_calls = None;
                                    prefix.delta.function_call = None;
                                    prefix.delta.refusal = None;
                                    prefix.delta.reasoning_content = None;
                                    prefix.finish_reason = None;
                                    prefix.logprobs = None;
                                    prefix_choices.push(prefix);
                                }
                            }
                        }
                    }

                    if choice.finish_reason.is_some() {
                        let (content, reasoning) = state.drain();
                        if let Some(content) = content {
                            match choice.delta.content.as_mut() {
                                Some(ChatCompletionMessageContent::Text(existing)) => {
                                    existing.push_str(&content);
                                }
                                Some(ChatCompletionMessageContent::Parts(_)) => {}
                                None => {
                                    choice.delta.content =
                                        Some(ChatCompletionMessageContent::Text(content));
                                }
                            }
                        }
                        if let Some(reasoning) = reasoning {
                            choice
                                .delta
                                .reasoning_content
                                .get_or_insert_default()
                                .push_str(&reasoning);
                        }
                    }
                }

                if !data.inner.choices.is_empty() {
                    last_response = Some(response.clone());
                }
                for prefix_choice in prefix_choices {
                    let mut prefix_response = response.clone();
                    if let Some(prefix_data) = prefix_response.data.as_mut() {
                        prefix_data.inner.choices = vec![prefix_choice];
                        prefix_data.inner.usage = None;
                        prefix_data.nvext = None;
                        prefix_data.llm_metrics = None;
                    }
                    prefix_response.id = None;
                    prefix_response.event = None;
                    prefix_response.comment = None;
                    prefix_response.error = None;
                    yield prefix_response;
                }
                yield response;
            }

            let mut indices: Vec<_> = states.keys().copied().collect();
            indices.sort_unstable();
            let flushed: Vec<_> = indices
                .into_iter()
                .filter_map(|index| {
                    let (content, reasoning) = states.get_mut(&index)?.drain();
                    (content.is_some() || reasoning.is_some())
                        .then_some((index, content, reasoning))
                })
                .collect();
            if !flushed.is_empty()
                && let Some(mut response) = last_response
                && scrub_synthetic_chunk_metadata(&mut response).is_some()
                && let Some(data) = response.data.as_mut()
                && let Some(template) = data.inner.choices.first().cloned()
            {
                data.inner.choices = flushed
                    .into_iter()
                    .map(|(index, content, reasoning)| {
                        let mut choice = template.clone();
                        choice.index = index;
                        choice.delta.role = None;
                        choice.delta.content = content.map(ChatCompletionMessageContent::Text);
                        choice.delta.tool_calls = None;
                        choice.delta.function_call = None;
                        choice.delta.refusal = None;
                        choice.delta.reasoning_content = reasoning;
                        choice.finish_reason = None;
                        choice.logprobs = None;
                        choice
                    })
                    .collect();
                yield response;
            }
        }
    }

    /// Hold the trailing usage-only chunk until every parser recovery chunk has
    /// been emitted. A truncated upstream stream can end without
    /// `finish_reason`, so reasoning recovery happens at EOF; forwarding usage
    /// immediately would put that recovered content after the chunk clients
    /// treat as the stream trailer. A transport error discards the pending
    /// trailer because the response did not complete successfully.
    fn hold_usage_until_stream_end<S>(
        stream: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        async_stream::stream! {
            tokio::pin!(stream);
            let mut pending_usage = None;
            let mut transport_failed = false;
            while let Some(response) = stream.next().await {
                if response.error.is_some() {
                    transport_failed = true;
                    pending_usage = None;
                    yield response;
                    continue;
                }
                let is_usage_only = response.data.as_ref().is_some_and(|data| {
                    data.inner.choices.is_empty() && data.inner.usage.is_some()
                });
                if is_usage_only {
                    if let Some(previous) = pending_usage.replace(response) {
                        yield previous;
                    }
                } else {
                    yield response;
                }
            }
            if !transport_failed && let Some(usage) = pending_usage {
                yield usage;
            }
        }
    }

    // Motivation: when Nemotron reasoning is disabled by request flags, the
    // backend may still emit a leading <think>. Buffer the initial stream
    // bytes so split chunks like "<thi" + "nk>answer" are stripped cleanly.
    fn strip_leading_reasoning_start_from_stream<S>(
        stream: S,
        think_start_token: &'static str,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        struct StripReasoningStartState {
            stream:
                Pin<Box<dyn Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send>>,
            think_start_token: &'static str,
            choices: HashMap<u32, StripChoiceState>,
            last_response: Option<Annotated<NvCreateChatCompletionStreamResponse>>,
            eof_flushed: bool,
        }

        #[derive(Default)]
        struct StripChoiceState {
            buffer: String,
            decided: bool,
        }

        fn take_undecided_buffer(choice_state: &mut StripChoiceState) -> Option<String> {
            if choice_state.decided || choice_state.buffer.is_empty() {
                return None;
            }

            choice_state.decided = true;
            Some(std::mem::take(&mut choice_state.buffer))
        }

        fn drain_undecided_buffers(
            choices: &mut HashMap<u32, StripChoiceState>,
        ) -> HashMap<u32, String> {
            choices
                .iter_mut()
                .filter_map(|(index, choice_state)| {
                    take_undecided_buffer(choice_state).map(|buffer| (*index, buffer))
                })
                .collect()
        }

        let state = StripReasoningStartState {
            stream: Box::pin(stream),
            think_start_token,
            choices: HashMap::new(),
            last_response: None,
            eof_flushed: false,
        };

        stream::unfold(state, |mut state| async move {
            if let Some(mut response) = state.stream.next().await {
                let Some(mut data) = response.data.take() else {
                    return Some((response, state));
                };

                for choice in data.inner.choices.iter_mut() {
                    let choice_state = state.choices.entry(choice.index).or_default();
                    let text = match choice.delta.content.take() {
                        Some(ChatCompletionMessageContent::Text(text)) => text,
                        other => {
                            if let Some(buffer) = take_undecided_buffer(choice_state) {
                                choice.delta.content =
                                    Some(ChatCompletionMessageContent::Text(buffer));
                            } else {
                                choice.delta.content = other;
                            }
                            continue;
                        }
                    };

                    let output = if choice_state.decided {
                        text
                    } else {
                        choice_state.buffer.push_str(&text);
                        let trimmed = choice_state.buffer.trim_start();
                        if trimmed.is_empty()
                            || (state.think_start_token.starts_with(trimmed)
                                && trimmed.len() < state.think_start_token.len())
                        {
                            choice.delta.content = None;
                            continue;
                        }

                        choice_state.decided = true;
                        if let Some(remainder) = trimmed.strip_prefix(state.think_start_token) {
                            remainder.to_string()
                        } else {
                            choice_state.buffer.clone()
                        }
                    };

                    choice_state.buffer.clear();
                    choice.delta.content = if output.is_empty() {
                        None
                    } else {
                        Some(ChatCompletionMessageContent::Text(output))
                    };
                }

                response.data = Some(data);
                if response
                    .data
                    .as_ref()
                    .is_some_and(|data| !data.inner.choices.is_empty())
                {
                    state.last_response = Some(response.clone());
                }

                Some((response, state))
            } else if state.eof_flushed {
                None
            } else {
                state.eof_flushed = true;
                let flushed = drain_undecided_buffers(&mut state.choices);
                if flushed.is_empty() {
                    None
                } else {
                    let mut response = state.last_response.clone()?;
                    // Same envelope problem as the reasoning-stream flush: this
                    // is a clone of an already-counted chunk, so it goes through
                    // the shared scrub rather than repeating a partial copy of
                    // it here.
                    scrub_synthetic_chunk_metadata(&mut response);
                    let data = response.data.as_mut()?;
                    let mut template = data.inner.choices.first()?.clone();
                    template.delta.role = None;
                    template.delta.tool_calls = None;
                    template.delta.function_call = None;
                    template.delta.refusal = None;
                    template.delta.reasoning_content = None;
                    template.finish_reason = None;
                    template.logprobs = None;
                    let mut flushed: Vec<_> = flushed.into_iter().collect();
                    flushed.sort_unstable_by_key(|(index, _)| *index);
                    data.inner.choices = flushed
                        .into_iter()
                        .map(|(index, buffer)| {
                            let mut choice = template.clone();
                            choice.index = index;
                            choice.delta.content = Some(ChatCompletionMessageContent::Text(buffer));
                            choice
                        })
                        .collect();

                    if data.inner.choices.is_empty() {
                        None
                    } else {
                        Some((response, state))
                    }
                }
            }
        })
        .fuse()
    }
}

// for pals, we do not want to add the generation prompt to the formatted prompt
// we also need to know if the template support this add_generation_prompt bool
// any prompt template that does not support this should return an error
// oob - we should update any prompt template that does not support this to support it

#[async_trait]
impl
    Operator<
        SingleIn<NvCreateChatCompletionRequest>,
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
        SingleIn<PreprocessedRequest>,
        ManyOut<Annotated<BackendOutput>>,
    > for OpenAIPreprocessor
{
    async fn generate(
        &self,
        request: SingleIn<NvCreateChatCompletionRequest>,
        next: Arc<
            dyn AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<BackendOutput>>, Error>,
        >,
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
        // unpack the request
        let (mut request, context) = request.into_parts();

        // Preserve original inbound streaming flag before any internal overrides
        let request_id = context.id().to_string();
        let original_stream_flag = request.inner.stream.unwrap_or(false);

        // Build request payload handle (None if request trace is disabled / not eligible).
        // The handle snapshots the pristine request and its arrival time here;
        // the single payload record is published once at stream completion
        // (or with an empty response on cancel/timeout), off the request path.
        let payload_http_headers = if crate::request_trace::payload::http_header_capture_active() {
            context
                .get_optional::<std::collections::BTreeMap<String, String>>(
                    crate::request_trace::payload::HTTP_HEADERS_CONTEXT_KEY,
                )
                .ok()
                .flatten()
        } else {
            None
        };
        let payload_handle = crate::request_trace::payload::create_handle(
            &request,
            &request_id,
            payload_http_headers,
        );

        // For non-streaming requests (stream=false), enable usage by default
        // This ensures compliance with OpenAI API spec where non-streaming responses
        // always include usage statistics
        request.enable_usage_for_nonstreaming(original_stream_flag);

        // Set stream=true for internal processing (after request payload capture)
        request.inner.stream = Some(true);
        // Apply the deployment default before parser-specific normalization so
        // it can override an implicit model default (for example Kimi K2.5),
        // while explicit request controls still take precedence.
        let thinking_control_from_client = Self::request_has_client_thinking_control(&request);
        self.apply_default_thinking_mode(&mut request);
        Self::normalize_thinking_arg_with_source(
            &mut request,
            self.runtime_config.reasoning_parser.as_deref(),
            self.tool_call_parser.as_deref(),
            thinking_control_from_client,
        );
        Self::normalize_kimi_k3_named_tool_choice(&mut request, self.tool_call_parser.as_deref());

        // create a response generator
        let response_generator = request.response_generator(context.id().to_string());
        let tracker = Some(response_generator.tracker());
        let preprocess_options = PreprocessRequestOptions {
            preserve_omitted_max_tokens: context
                .get::<bool>(PRESERVE_OMITTED_MAX_TOKENS_CONTEXT_KEY)
                .ok()
                .is_some_and(|flag| *flag),
        };

        // convert the chat completion request to a common completion request
        let (mut common_request, annotations, prompt_injected_reasoning, image_tokens) = self
            .preprocess_request_with_options(
                &request,
                tracker.as_deref(),
                preprocess_options,
                context
                    .get_optional::<String>(LORA_NAME_CONTEXT_KEY)
                    .ok()
                    .flatten()
                    .map(|name| name.as_ref().clone()),
            )
            .await?;
        attach_agent_context_from_context(&mut common_request, &context);

        let guided_tool_constraint = self.apply_tool_choice_guided_decoding(
            &request,
            &mut common_request,
            prompt_injected_reasoning,
        )?;
        let tool_processing_route =
            self.tool_processing_route(&request, &guided_tool_constraint)?;
        validate_legacy_jail_nvext_choice_count(
            request.inner.n.unwrap_or(1),
            request
                .nvext
                .as_ref()
                .and_then(|nvext| nvext.extra_fields.as_deref()),
            tool_processing_route.uses_legacy_jail(),
        )?;

        tracing::trace!(request = ?common_request, prompt_injected_reasoning, "Pre-processed request");
        let trace_state = crate::request_trace::build_request_end_trace_state(
            &common_request,
            &tracker,
            &context,
            self.kv_cache_block_size,
        );
        let trace_tokens_enabled = trace_state.is_some();
        let trace_finish_reason_metadata =
            crate::request_trace::finish_reason_metadata_handle(&trace_state);

        // Attach the timing tracker to the request so downstream components can record metrics
        common_request.tracker = tracker;

        // Capture media counts before `common_request` is moved into the context.
        let mm_counts = MultimodalCounts::from_preprocessed(&common_request);

        let mut response_generator = Box::new(response_generator);

        // Update ISL only for text prompts (embeddings get sequence length from tensor shape)
        if common_request.prompt_embeds.is_none() {
            let isl = common_request.token_ids.len() as u32;
            response_generator.update_isl(isl);
        }

        // repack the common completion request
        let common_request = context.map(|_| common_request);

        // create a stream of annotations this will be prepend to the response stream
        let annotations: Vec<Annotated<NvCreateChatCompletionStreamResponse>> = annotations
            .into_iter()
            .flat_map(|(k, v)| Annotated::from_annotation(k, &v))
            .collect();
        let annotations_stream = stream::iter(annotations);

        // forward the common completion request to the next operator
        let response_stream = next.generate(common_request).await?;
        // Extract context once
        let context = response_stream.context();

        // transform the postprocessor stream (no boxing yet) - detokenize
        let stream = Self::transform_postprocessor_stream_with_image_tokens(
            response_stream,
            response_generator,
            context.clone(),
            payload_handle.is_some(),
            trace_tokens_enabled,
            trace_finish_reason_metadata,
            mm_counts,
            image_tokens,
        );

        let transformed_stream = self.postprocessor_parsing_stream_with_constraint(
            stream,
            &request,
            prompt_injected_reasoning,
            guided_tool_constraint,
            tool_processing_route,
        )?;
        let transformed_stream = Self::normalize_chat_stream_roles(transformed_stream);

        // Apply request payload aggregation strategy.
        // The payload branch already returns Pin<Box<...>> from scan/fold_aggregate_with_future,
        // while the non-payload branch boxes the impl Stream from postprocessor_parsing_stream.
        let final_stream = if let Some(payload) = payload_handle {
            let (stream, agg_fut) = if payload.streaming() {
                // Streaming: apply scan (pass-through + parallel aggregation)
                crate::request_trace::payload_stream::scan_aggregate_with_future(transformed_stream)
            } else {
                // Non-streaming: apply fold (collect all, then emit single chunk)
                crate::request_trace::payload_stream::fold_aggregate_with_future(transformed_stream)
            };

            // Spawn the payload emit off the request path. `agg_fut` resolves to
            // None on client cancel / gateway timeout / aggregation failure; we
            // still emit the payload record with an empty response so those
            // cases remain inspectable. The record carries the request snapshot
            // and arrival time captured at handle creation.
            tokio::spawn(async move {
                match agg_fut.await {
                    Some(final_resp) => payload.emit(Some(Arc::new(final_resp))),
                    None => {
                        tracing::debug!(
                            request_id = %payload.request_id(),
                            "request payload: response aggregation incomplete (client cancel / timeout); emitting request-only record"
                        );
                        payload.emit(None);
                    }
                }
            });

            stream
        } else {
            Box::pin(transformed_stream)
        };

        // Step 5: Speculative next-turn prefill
        let final_stream = speculative_prefill::maybe_wrap_stream(
            final_stream,
            &request,
            &next,
            &self.formatter,
            &self.tokenizer,
        );

        let final_stream = crate::request_trace::wrap_chat_request_end_stream(
            final_stream,
            trace_state,
            request_id,
        );

        // prepend the annotations to the response stream
        let stream = annotations_stream.chain(final_stream);

        // return the response stream - single boxing at the end
        Ok(ResponseStream::new(Box::pin(stream), context))
    }
}

#[async_trait]
impl
    Operator<
        SingleIn<NvCreateCompletionRequest>,
        ManyOut<Annotated<NvCreateCompletionResponse>>,
        SingleIn<PreprocessedRequest>,
        ManyOut<Annotated<BackendOutput>>,
    > for OpenAIPreprocessor
{
    async fn generate(
        &self,
        request: SingleIn<NvCreateCompletionRequest>,
        next: Arc<
            dyn AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<BackendOutput>>, Error>,
        >,
    ) -> Result<ManyOut<Annotated<NvCreateCompletionResponse>>, Error> {
        let _stage_guard = StageGuard::new(STAGE_PREPROCESS, "");

        // unpack the request
        let (mut request, context) = request.into_parts();
        let request_id = context.id().to_string();

        // Preserve original streaming flag
        let original_stream_flag = request.inner.stream.unwrap_or(false);

        // For non-streaming requests (stream=false), enable usage by default
        // This ensures compliance with OpenAI API spec where non-streaming responses
        // always include usage statistics
        request.enable_usage_for_nonstreaming(original_stream_flag);

        request.inner.stream = Some(true);

        // create a response generator
        let response_generator = request.response_generator(request_id.clone());
        let mut response_generator = Box::new(response_generator);
        let tracker = Some(response_generator.tracker());
        // convert the chat completion request to a common completion request
        let mut builder = self.builder_with_lora(
            &request,
            context
                .get_optional::<String>(LORA_NAME_CONTEXT_KEY)
                .ok()
                .flatten()
                .map(|name| name.as_ref().clone()),
        )?;

        // Check if embeddings are provided - skip tokenization path
        let annotations = if let Some(ref prompt_embeds) = request.inner.prompt_embeds {
            // Skip tokenization for embeddings
            builder.token_ids(vec![]); // Empty token IDs
            builder.prompt_embeds(Some(prompt_embeds.clone()));
            // No token annotations
            HashMap::new()
        } else {
            // Normal path: tokenize the prompt; embeddings don't need MM routing,
            // so install tokens on the builder right away.
            let (token_ids, ann) = self
                .gather_tokens(&request, None, tracker.as_deref())
                .await?;
            builder.token_ids(token_ids);
            ann
        };

        // Gather multimodal data (works with both embeddings and text prompts)
        // Returned MM entries are unused on the embeddings path; routing info is
        // not built here.
        let _ = self
            .gather_multi_modal_data(&request, &mut builder, None, &[])
            .await?;

        let mut common_request = builder.build()?;
        Self::validate_preprocessed_token_budget(&common_request, self.token_budget.as_ref())?;
        attach_agent_context_from_context(&mut common_request, &context);

        let trace_state = crate::request_trace::build_request_end_trace_state(
            &common_request,
            &tracker,
            &context,
            self.kv_cache_block_size,
        );
        let trace_tokens_enabled = trace_state.is_some();
        let trace_finish_reason_metadata =
            crate::request_trace::finish_reason_metadata_handle(&trace_state);

        // Attach the timing tracker to the request so downstream components can record metrics
        common_request.tracker = tracker;

        // Update ISL only for text prompts (embeddings get sequence length from tensor shape)
        if common_request.prompt_embeds.is_none() {
            let isl = common_request.token_ids.len() as u32;
            response_generator.update_isl(isl);
        }

        // repack the common completion request
        let common_request = context.map(|_| common_request);

        // create a stream of annotations this will be prepend to the response stream
        let annotations: Vec<Annotated<NvCreateCompletionResponse>> = annotations
            .into_iter()
            .flat_map(|(k, v)| Annotated::from_annotation(k, &v))
            .collect();
        let annotations_stream = stream::iter(annotations);

        // End preprocess stage before handing off to downstream (route/dispatch).
        drop(_stage_guard);

        // forward the common completion request to the next operator
        let response_stream = next.generate(common_request).await?;

        // Extract context once
        let context = response_stream.context();

        // transform the postprocessor stream. Legacy `/v1/completions` is
        // text-only, so multimodal counts are always zero here.
        let stream = Self::transform_postprocessor_stream(
            response_stream,
            response_generator,
            context.clone(),
            false,
            trace_tokens_enabled,
            trace_finish_reason_metadata,
            MultimodalCounts::default(),
        );

        let stream = crate::request_trace::wrap_completion_request_end_stream(
            Box::pin(stream),
            trace_state,
            request_id,
        );

        // prepend the annotations to the response stream
        let stream = annotations_stream.chain(stream);

        // return the response stream
        Ok(ResponseStream::new(Box::pin(stream), context))
    }
}

#[async_trait]
impl
    Operator<
        SingleIn<NvCreateEmbeddingRequest>,
        ManyOut<Annotated<NvCreateEmbeddingResponse>>,
        SingleIn<PreprocessedEmbeddingRequest>,
        ManyOut<Annotated<EmbeddingsEngineOutput>>,
    > for OpenAIPreprocessor
{
    async fn generate(
        &self,
        request: SingleIn<NvCreateEmbeddingRequest>,
        next: Arc<
            dyn AsyncEngine<
                    SingleIn<PreprocessedEmbeddingRequest>,
                    ManyOut<Annotated<EmbeddingsEngineOutput>>,
                    Error,
                >,
        >,
    ) -> Result<ManyOut<Annotated<NvCreateEmbeddingResponse>>, Error> {
        // Unpack request
        let (request, context) = request.into_parts();

        // Preprocess the embedding request
        let (preprocessed_request, annotations) =
            self.preprocess_embedding_request(&request).await?;

        // Forward to next stage
        let preprocessed_request = context.map(|_| preprocessed_request);
        let response_stream = next.generate(preprocessed_request).await?;

        // Extract context once
        let context = response_stream.context();

        // Transform response stream back to OpenAI format
        let stream = Self::transform_embedding_postprocessor_stream(response_stream, request);

        // Prepend annotations
        let annotations_stream = stream::iter(
            annotations
                .into_iter()
                .flat_map(|(k, v)| Annotated::from_annotation(k, &v))
                .collect::<Vec<_>>(),
        );

        let combined_stream = annotations_stream.chain(stream);
        Ok(ResponseStream::new(Box::pin(combined_stream), context))
    }
}

// Note: tests for jailing and parser detection live in `lib/llm/tests/test_jail.rs`

#[cfg(test)]
mod strip_tests {
    use super::OpenAIPreprocessor;

    #[test]
    fn test_strip_inline_data_urls_replaces_data_urls() {
        let mut messages = serde_json::json!([{
            "role": "user",
            "content": [
                {"type": "text", "text": "What is this?"},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBOR...longdata..."}},
                {"type": "image_url", "image_url": {"url": "https://example.com/img.png"}}
            ]
        }]);
        OpenAIPreprocessor::strip_inline_data_urls(&mut messages);
        let parts = messages[0]["content"].as_array().unwrap();
        assert_eq!(parts[0]["text"], "What is this?");
        assert_eq!(parts[1]["image_url"]["url"], "");
        assert_eq!(parts[2]["image_url"]["url"], "https://example.com/img.png");
    }

    #[test]
    fn test_strip_inline_data_urls_handles_video_audio() {
        let mut messages = serde_json::json!([{
            "role": "user",
            "content": [
                {"type": "video_url", "video_url": {"url": "data:video/mp4;base64,AAAA..."}},
                {"type": "audio_url", "audio_url": {"url": "https://example.com/audio.wav"}}
            ]
        }]);
        OpenAIPreprocessor::strip_inline_data_urls(&mut messages);
        let parts = messages[0]["content"].as_array().unwrap();
        assert_eq!(parts[0]["video_url"]["url"], "");
        assert_eq!(
            parts[1]["audio_url"]["url"],
            "https://example.com/audio.wav"
        );
    }

    #[test]
    fn test_strip_inline_data_urls_preserves_text_only() {
        let mut messages = serde_json::json!([{
            "role": "user",
            "content": "plain text message"
        }]);
        let original = messages.clone();
        OpenAIPreprocessor::strip_inline_data_urls(&mut messages);
        assert_eq!(messages, original);
    }

    #[test]
    fn test_strip_inline_data_urls_empty_messages() {
        let mut messages = serde_json::json!([]);
        OpenAIPreprocessor::strip_inline_data_urls(&mut messages);
        assert_eq!(messages, serde_json::json!([]));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocols::common::extensions::{
        AGENT_CONTEXT_CONTEXT_KEY, AgentCompaction, AgentContext,
    };
    use crate::protocols::common::preprocessor::MultimodalData;
    use crate::protocols::common::{OutputOptions, SamplingOptions, StopConditions};
    use dynamo_protocols::types::{
        ChatChoiceStream, ChatCompletionStreamResponseDelta, CreateChatCompletionStreamResponse,
        FinishReason, Role,
    };

    #[test]
    fn guided_tool_streaming_release_only_when_guided_json_and_not_rolled_back() {
        assert!(
            OpenAIPreprocessor::guided_tool_streaming_release(true, false),
            "a forced tool_choice with an installed grammar releases incrementally by default"
        );
        assert!(
            !OpenAIPreprocessor::guided_tool_streaming_release(true, true),
            "DYN_ENABLE_GUIDED_TOOL_STREAMING=false must fall back to buffer-to-completion \
             even when guided JSON is installed"
        );
        assert!(
            !OpenAIPreprocessor::guided_tool_streaming_release(false, false),
            "no installed grammar means nothing to release incrementally, rollback or not"
        );
        assert!(
            !OpenAIPreprocessor::guided_tool_streaming_release(false, true),
            "no installed grammar means nothing to release incrementally, rollback or not"
        );
    }

    #[test]
    fn legacy_jail_rejects_multiple_choices_for_choice_specific_nvext() {
        let engine_data = vec!["engine_data".to_string()];
        let request_level = vec!["timing".to_string(), "worker_id".to_string()];

        assert!(validate_legacy_jail_nvext_choice_count(2, Some(&engine_data), true).is_err());
        assert!(validate_legacy_jail_nvext_choice_count(1, Some(&engine_data), true).is_ok());
        assert!(validate_legacy_jail_nvext_choice_count(2, Some(&request_level), true).is_ok());

        for route in [
            ToolProcessingRoute::MuseUnified("muse_glimmer".to_string()),
            ToolProcessingRoute::QwenUnified("qwen3"),
            ToolProcessingRoute::ParserV2("qwen3_coder".to_string()),
            ToolProcessingRoute::PassThrough,
        ] {
            assert!(
                validate_legacy_jail_nvext_choice_count(
                    2,
                    Some(&engine_data),
                    route.uses_legacy_jail(),
                )
                .is_ok()
            );
        }
    }

    fn chat_stream_chunk(
        index: u32,
        role: Option<Role>,
    ) -> Annotated<NvCreateChatCompletionStreamResponse> {
        #[allow(deprecated)]
        let choice = ChatChoiceStream {
            index,
            delta: ChatCompletionStreamResponseDelta {
                role,
                content: Some(ChatCompletionMessageContent::Text("content".to_string())),
                tool_calls: None,
                function_call: None,
                refusal: None,
                reasoning_content: None,
            },
            finish_reason: None,
            logprobs: None,
        };
        Annotated::from_data(NvCreateChatCompletionStreamResponse {
            inner: CreateChatCompletionStreamResponse {
                id: "test".to_string(),
                choices: vec![choice],
                created: 0,
                model: "test".to_string(),
                system_fingerprint: None,
                object: "chat.completion.chunk".to_string(),
                usage: None,
                service_tier: None,
            },
            nvext: None,
            llm_metrics: None,
        })
    }

    fn reasoning_usage_chunk(
        reasoning: Option<&str>,
        content: Option<&str>,
        chunk_tokens: usize,
    ) -> Annotated<NvCreateChatCompletionStreamResponse> {
        let mut chunk = chat_stream_chunk(0, None);
        let data = chunk.data.as_mut().unwrap();
        data.inner.choices[0].delta.reasoning_content = reasoning.map(str::to_string);
        data.inner.choices[0].delta.content = content
            .map(str::to_string)
            .map(ChatCompletionMessageContent::Text);
        data.llm_metrics = Some(LLMMetricAnnotation {
            chunk_tokens,
            ..Default::default()
        });
        chunk
    }

    fn reasoning_usage_trailer(
        completion_tokens: u32,
        backend_reasoning_tokens: Option<u32>,
    ) -> Annotated<NvCreateChatCompletionStreamResponse> {
        let mut chunk = chat_stream_chunk(0, None);
        let data = chunk.data.as_mut().unwrap();
        data.inner.choices.clear();
        let mut usage = dynamo_protocols::types::CompletionUsage {
            prompt_tokens: 5,
            completion_tokens,
            total_tokens: 5 + completion_tokens,
            prompt_tokens_details: None,
            completion_tokens_details: None,
        };
        if let Some(reasoning_tokens) = backend_reasoning_tokens {
            usage
                .completion_tokens_details
                .get_or_insert_default()
                .reasoning_tokens = Some(reasoning_tokens);
        }
        data.inner.usage = Some(usage);
        data.llm_metrics = Some(LLMMetricAnnotation {
            output_tokens: completion_tokens as usize,
            ..Default::default()
        });
        chunk
    }

    #[tokio::test]
    async fn reasoning_usage_estimator_stamps_shared_chat_usage() {
        let output = annotate_reasoning_usage(stream::iter(vec![
            reasoning_usage_chunk(Some("think"), None, 1),
            reasoning_usage_chunk(Some(" more"), None, 1),
            reasoning_usage_chunk(None, None, 1),
            reasoning_usage_chunk(None, Some("answer"), 1),
            reasoning_usage_trailer(4, None),
        ]))
        .collect::<Vec<_>>()
        .await;

        let usage = output
            .last()
            .and_then(|response| response.data.as_ref())
            .and_then(|chunk| chunk.inner.usage.as_ref())
            .unwrap();
        assert_eq!(
            usage
                .completion_tokens_details
                .as_ref()
                .and_then(|details| details.reasoning_tokens),
            Some(3)
        );
    }

    #[tokio::test]
    async fn reasoning_usage_estimator_documents_mixed_chunk_overcount() {
        let output = annotate_reasoning_usage(stream::iter(vec![
            reasoning_usage_chunk(Some("think"), Some("answer"), 4),
            reasoning_usage_trailer(4, None),
        ]))
        .collect::<Vec<_>>()
        .await;

        let usage = output
            .last()
            .and_then(|response| response.data.as_ref())
            .and_then(|chunk| chunk.inner.usage.as_ref())
            .unwrap();
        assert_eq!(
            usage
                .completion_tokens_details
                .as_ref()
                .and_then(|details| details.reasoning_tokens),
            Some(4),
            "the chunk-granular estimate intentionally attributes the mixed chunk to reasoning"
        );
    }

    #[tokio::test]
    async fn reasoning_usage_estimator_preserves_positive_backend_count() {
        let output = annotate_reasoning_usage(stream::iter(vec![
            reasoning_usage_chunk(Some("two estimated tokens"), None, 2),
            reasoning_usage_trailer(2, Some(1)),
        ]))
        .collect::<Vec<_>>()
        .await;

        let usage = output
            .last()
            .and_then(|response| response.data.as_ref())
            .and_then(|chunk| chunk.inner.usage.as_ref())
            .unwrap();
        assert_eq!(
            usage
                .completion_tokens_details
                .as_ref()
                .and_then(|details| details.reasoning_tokens),
            Some(1)
        );
    }

    #[tokio::test]
    async fn force_nonempty_deferral_preserves_reasoning_usage() {
        let reasoning = reasoning_usage_chunk(Some("deferred thought"), None, 3);
        let mut terminal = chat_stream_chunk(0, None);
        let terminal_choice = &mut terminal.data.as_mut().unwrap().inner.choices[0];
        terminal_choice.delta.content = None;
        terminal_choice.finish_reason = Some(FinishReason::Stop);

        let output = OpenAIPreprocessor::apply_unified_response_policies(
            stream::iter(vec![reasoning, terminal, reasoning_usage_trailer(3, None)]),
            true,
            true,
        )
        .collect::<Vec<_>>()
        .await;
        let usage = output
            .last()
            .and_then(|response| response.data.as_ref())
            .and_then(|chunk| chunk.inner.usage.as_ref())
            .expect("held usage trailer");

        assert_eq!(
            usage
                .completion_tokens_details
                .as_ref()
                .and_then(|details| details.reasoning_tokens),
            Some(3),
            "deferral must not erase the parser's reasoning classification"
        );
        assert_eq!(
            output
                .iter()
                .filter_map(|response| response.data.as_ref())
                .filter(|chunk| chunk.llm_metrics.is_some())
                .count(),
            2,
            "one source metric and one usage-trailer metric must survive"
        );
    }

    #[tokio::test]
    async fn test_normalize_chat_stream_roles_recovers_missing_first_role_per_choice() {
        let input = stream::iter(vec![
            // Mirrors a parser releasing buffered content without the role that
            // arrived on the original, swallowed chunk.
            chat_stream_chunk(0, None),
            chat_stream_chunk(1, None),
            chat_stream_chunk(0, Some(Role::Assistant)),
            chat_stream_chunk(1, Some(Role::Assistant)),
        ]);

        let output: Vec<_> = OpenAIPreprocessor::normalize_chat_stream_roles(input)
            .collect()
            .await;
        let roles: Vec<_> = output
            .iter()
            .map(|response| response.data.as_ref().unwrap().inner.choices[0].delta.role)
            .collect();

        assert_eq!(
            roles,
            vec![Some(Role::Assistant), Some(Role::Assistant), None, None,]
        );
    }

    fn kimi_k3_reasoning_chunk(reasoning: &str) -> Annotated<NvCreateChatCompletionStreamResponse> {
        let mut chunk = chat_stream_chunk(0, Some(Role::Assistant));
        let choice = &mut chunk.data.as_mut().unwrap().inner.choices[0];
        choice.delta.content = None;
        choice.delta.reasoning_content = Some(reasoning.to_string());
        chunk
    }

    fn terminal_chat_stream_chunk() -> Annotated<NvCreateChatCompletionStreamResponse> {
        let mut chunk = chat_stream_chunk(0, None);
        let choice = &mut chunk.data.as_mut().unwrap().inner.choices[0];
        choice.delta.content = None;
        choice.finish_reason = Some(FinishReason::Stop);
        chunk
    }

    async fn apply_kimi_k3_no_tools(
        leaked_reasoning: &str,
    ) -> Vec<Annotated<NvCreateChatCompletionStreamResponse>> {
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "moonshotai/Kimi-K3",
            "messages": [{"role": "user", "content": "test"}]
        }))
        .unwrap();
        let tool_call_parsing_enabled = OpenAIPreprocessor::tool_call_parsing_enabled(&request);
        assert!(!tool_call_parsing_enabled, "request has no tools");

        let jailed = OpenAIPreprocessor::apply_tool_calling_jail(
            Some("kimi_k3".to_string()),
            request.inner.tool_choice.clone(),
            None,
            false,
            // No tools and no forced choice, so no JSON grammar was installed.
            false,
            stream::iter(vec![
                kimi_k3_reasoning_chunk(leaked_reasoning),
                terminal_chat_stream_chunk(),
            ]),
        );

        OpenAIPreprocessor::apply_tool_call_response_policy(jailed, tool_call_parsing_enabled)
            .collect()
            .await
    }

    #[tokio::test]
    async fn test_kimi_k3_no_tools_preserves_decoded_content_and_reasoning() {
        let responses = apply_kimi_k3_no_tools(concat!(
            "The user requested an exact integer.",
            "<|open|>response<|sep|>",
            "323",
            "<|close|>response<|sep|>",
            "<|close|>message<|sep|>",
            "<|end_of_msg|>"
        ))
        .await;

        let choices: Vec<_> = responses
            .iter()
            .flat_map(|response| response.data.iter())
            .flat_map(|data| data.inner.choices.iter())
            .collect();
        let content: String = choices
            .iter()
            .filter_map(|choice| match &choice.delta.content {
                Some(ChatCompletionMessageContent::Text(text)) => Some(text.as_str()),
                _ => None,
            })
            .collect();
        let reasoning: String = choices
            .iter()
            .filter_map(|choice| choice.delta.reasoning_content.as_deref())
            .collect();

        assert_eq!(content, "323");
        assert_eq!(reasoning, "The user requested an exact integer.");
        assert!(!content.contains("<|"));
        assert!(!reasoning.contains("<|"));
    }

    #[tokio::test]
    async fn test_kimi_k3_no_tools_suppresses_structured_calls_for_stream_and_batch() {
        let responses = apply_kimi_k3_no_tools(concat!(
            "Use the calculator.",
            "<|open|>tools<|sep|>",
            "<|open|>call tool=\"calc\" index=\"1\"<|sep|>",
            "<|open|>argument key=\"x\" type=\"number\"<|sep|>323",
            "<|close|>argument<|sep|>",
            "<|close|>call<|sep|>",
            "<|close|>tools<|sep|>",
            "<|close|>message<|sep|>",
            "<|end_of_msg|>"
        ))
        .await;

        let choices: Vec<_> = responses
            .iter()
            .flat_map(|response| response.data.iter())
            .flat_map(|data| data.inner.choices.iter())
            .collect();
        assert!(
            choices
                .iter()
                .all(|choice| choice.delta.tool_calls.is_none()),
            "streaming output must not expose parser-produced tool calls"
        );
        assert!(
            choices
                .iter()
                .all(|choice| choice.finish_reason != Some(FinishReason::ToolCalls))
        );
        assert!(
            choices
                .iter()
                .any(|choice| choice.finish_reason == Some(FinishReason::Stop))
        );
        let content = choices
            .iter()
            .filter_map(|choice| match &choice.delta.content {
                Some(ChatCompletionMessageContent::Text(text)) => Some(text.as_str()),
                _ => None,
            })
            .collect::<String>();
        assert!(
            content.is_empty(),
            "a suppressed tool-only turn deliberately fails closed instead of exposing raw XTML"
        );
        assert_eq!(
            choices
                .iter()
                .filter_map(|choice| choice.delta.reasoning_content.as_deref())
                .collect::<String>(),
            "Use the calculator."
        );

        let response =
            crate::protocols::openai::chat_completions::aggregator::DeltaAggregator::apply(
                stream::iter(responses),
                crate::protocols::openai::ParsingOptions::new(None, None),
            )
            .await
            .unwrap();
        let choice = &response.inner.choices[0];
        assert!(
            choice.message.content.as_ref().is_none_or(|content| {
                matches!(content, ChatCompletionMessageContent::Text(text) if text.is_empty())
            }),
            "batch output must not reconstruct the suppressed call as assistant content"
        );
        assert!(choice.message.tool_calls.is_none());
        assert_eq!(choice.finish_reason, Some(FinishReason::Stop));
        assert_eq!(
            choice.message.reasoning_content.as_deref(),
            Some("Use the calculator.")
        );
    }

    #[test]
    fn prompt_invalid_request_maps_to_invalid_argument() {
        let error = PromptRenderError::invalid_request("unsupported model parameter").into();
        let mapped = OpenAIPreprocessor::map_prompt_render_error(error);
        let mapped = mapped
            .downcast_ref::<DynamoError>()
            .expect("prompt validation should map to a DynamoError");

        assert!(matches!(mapped.error_type(), ErrorType::InvalidArgument));
        assert_eq!(mapped.message(), "unsupported model parameter");
    }

    #[test]
    fn ordinary_prompt_error_maps_to_invalid_argument() {
        let mapped = OpenAIPreprocessor::map_prompt_render_error(anyhow::anyhow!(
            "template configuration failed"
        ));
        let mapped = mapped
            .downcast_ref::<DynamoError>()
            .expect("any prompt render failure should map to a DynamoError");

        assert!(matches!(mapped.error_type(), ErrorType::InvalidArgument));
        assert_eq!(mapped.message(), "template configuration failed");
    }

    fn url_entry(u: &str) -> MultimodalData {
        MultimodalData::Url(url::Url::parse(u).unwrap())
    }

    fn preprocessed_with_media(media: Option<MultimodalDataMap>) -> PreprocessedRequest {
        let mut b = PreprocessedRequest::builder();
        b.model("m".to_string())
            .token_ids(vec![1, 2, 3])
            .stop_conditions(StopConditions::default())
            .sampling_options(SamplingOptions::default())
            .output_options(OutputOptions::default());
        if let Some(m) = media {
            b.multi_modal_data(Some(m));
        }
        b.build().unwrap()
    }

    #[test]
    fn test_multimodal_counts_from_preprocessed_mixed() {
        // 2 images, 1 video, 0 audio -> counts reflect vec lengths per modality.
        let mut map: MultimodalDataMap = HashMap::new();
        map.insert(
            "image_url".to_string(),
            vec![url_entry("http://x/a.png"), url_entry("http://x/b.png")],
        );
        map.insert("video_url".to_string(), vec![url_entry("http://x/c.mp4")]);

        let req = preprocessed_with_media(Some(map));
        let counts = MultimodalCounts::from_preprocessed(&req);
        assert_eq!(counts.image, 2);
        assert_eq!(counts.video, 1);
        assert_eq!(counts.audio, 0);
    }

    #[test]
    fn test_multimodal_counts_from_preprocessed_text_only() {
        // No multi_modal_data -> all zero.
        let req = preprocessed_with_media(None);
        let counts = MultimodalCounts::from_preprocessed(&req);
        assert_eq!(counts.image, 0);
        assert_eq!(counts.video, 0);
        assert_eq!(counts.audio, 0);
    }

    #[test]
    fn tool_message_exposes_multimodal_content_parts() {
        let message: ChatCompletionRequestMessage = serde_json::from_value(serde_json::json!({
            "role": "tool",
            "tool_call_id": "call_media",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "data:image/png;base64,aGVsbG8="
                    }
                },
                {
                    "type": "video_url",
                    "video_url": {
                        "url": "https://example.com/clip.mp4"
                    }
                },
                {
                    "type": "audio_url",
                    "audio_url": {
                        "url": "https://example.com/audio.wav"
                    }
                }
            ]
        }))
        .unwrap();

        let parts: Vec<_> = multimodal_content_parts(&message).unwrap().collect();
        assert!(matches!(
            parts[0].as_user().as_ref(),
            ChatCompletionRequestUserMessageContentPart::ImageUrl(_)
        ));
        assert!(matches!(
            parts[1].as_user().as_ref(),
            ChatCompletionRequestUserMessageContentPart::VideoUrl(_)
        ));
        assert!(matches!(
            parts[2].as_user().as_ref(),
            ChatCompletionRequestUserMessageContentPart::AudioUrl(_)
        ));
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn image_token_aggregate_requires_complete_trustworthy_counts() {
        assert_eq!(aggregate_image_tokens(Some(300), 2, 2, false), Some(300));
        assert_eq!(aggregate_image_tokens(Some(300), 2, 3, false), None);
        assert_eq!(aggregate_image_tokens(Some(300), 2, 2, true), None);
        assert_eq!(aggregate_image_tokens(None, 2, 2, false), None);
        assert_eq!(aggregate_image_tokens(Some(0), 0, 0, false), None);
        assert_eq!(
            checked_add_image_tokens(Some(usize::MAX), 1),
            None,
            "overflow must omit the aggregate rather than wrap"
        );
    }

    #[cfg(feature = "mm-routing")]
    struct RoutingTestTokenizer {
        atomic_controls: bool,
        fail_plain_text: bool,
    }

    #[cfg(feature = "mm-routing")]
    impl crate::tokenizers::traits::Encoder for RoutingTestTokenizer {
        fn encode(&self, input: &str) -> anyhow::Result<Encoding> {
            Ok(Encoding::Sp(
                input.bytes().map(|byte| 1000 + u32::from(byte)).collect(),
            ))
        }

        fn encode_batch(&self, inputs: &[&str]) -> anyhow::Result<Vec<Encoding>> {
            inputs.iter().map(|input| self.encode(input)).collect()
        }

        fn encode_segments(
            &self,
            segments: &[crate::tokenizers::EncodeSegment<'_>],
        ) -> anyhow::Result<Encoding> {
            let mut ids = Vec::new();
            for segment in segments {
                if segment.allow_special {
                    if !self.atomic_controls {
                        ids.extend([9000, 9001]);
                        continue;
                    }
                    ids.push(match segment.text {
                        "<|media_begin|>" => 163602,
                        "<|media_content|>" => 163603,
                        "<|media_end|>" => 163604,
                        other => anyhow::bail!("unexpected control segment {other:?}"),
                    });
                } else {
                    if self.fail_plain_text {
                        anyhow::bail!("injected plain-text routing encode failure");
                    }
                    ids.extend(segment.text.bytes().map(|byte| 1000 + u32::from(byte)));
                }
            }
            Ok(Encoding::Sp(ids))
        }
    }

    #[cfg(feature = "mm-routing")]
    impl crate::tokenizers::traits::Decoder for RoutingTestTokenizer {
        fn decode(
            &self,
            _token_ids: &[TokenIdType],
            _skip_special_tokens: bool,
        ) -> anyhow::Result<crate::tokenizers::traits::DecodeResult> {
            Ok(crate::tokenizers::traits::DecodeResult::Complete(
                String::new(),
            ))
        }
    }

    #[cfg(feature = "mm-routing")]
    impl Tokenizer for RoutingTestTokenizer {}

    #[cfg(feature = "mm-routing")]
    struct ReferenceK3Tokenizer;

    #[cfg(feature = "mm-routing")]
    impl llm_tokenizer::traits::Encoder for ReferenceK3Tokenizer {
        fn encode(
            &self,
            input: &str,
            _add_special_tokens: bool,
        ) -> anyhow::Result<llm_tokenizer::Encoding> {
            Ok(llm_tokenizer::Encoding::Plain(
                input.bytes().map(|byte| 1000 + u32::from(byte)).collect(),
            ))
        }

        fn encode_batch(
            &self,
            inputs: &[&str],
            add_special_tokens: bool,
        ) -> anyhow::Result<Vec<llm_tokenizer::Encoding>> {
            inputs
                .iter()
                .map(|input| self.encode(input, add_special_tokens))
                .collect()
        }
    }

    #[cfg(feature = "mm-routing")]
    impl llm_tokenizer::traits::Decoder for ReferenceK3Tokenizer {
        fn decode(&self, _token_ids: &[u32], _skip_special_tokens: bool) -> anyhow::Result<String> {
            Ok(String::new())
        }
    }

    #[cfg(feature = "mm-routing")]
    impl llm_tokenizer::traits::Tokenizer for ReferenceK3Tokenizer {
        fn vocab_size(&self) -> usize {
            0
        }

        fn get_special_tokens(&self) -> &llm_tokenizer::SpecialTokens {
            static EMPTY: std::sync::LazyLock<llm_tokenizer::SpecialTokens> =
                std::sync::LazyLock::new(llm_tokenizer::SpecialTokens::default);
            &EMPTY
        }

        fn token_to_id(&self, token: &str) -> Option<u32> {
            match token {
                "<|media_begin|>" => Some(163602),
                "<|media_content|>" => Some(163603),
                "<|media_end|>" => Some(163604),
                "<|media_pad|>" => Some(163605),
                _ => None,
            }
        }

        fn id_to_token(&self, _id: u32) -> Option<String> {
            None
        }

        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k3_routing_replacement_includes_dimensions_and_structural_tokens() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: false,
        };
        let layout =
            resolve_routing_image_prompt_layout(&tokenizer, lightseek_mm::ImagePromptKind::KimiK3)
                .unwrap();
        let image = MmImageEntry {
            mm_hash: 0x1234,
            width: 320,
            height: 240,
        };
        let fill = dynamo_kv_router::protocols::pad_value_for_mm_hash(image.mm_hash);
        let dimension_ids: Vec<TokenIdType> = "image 320x240"
            .bytes()
            .map(|byte| 1000 + u32::from(byte))
            .collect();
        let mut expanded = vec![7];

        append_mm_routing_replacement(&mut expanded, &tokenizer, layout, image, 3).unwrap();

        let mut expected = vec![7, 163602];
        expected.extend(dimension_ids);
        expected.push(163603);
        expected.extend([fill; 3]);
        expected.push(163604);
        assert_eq!(expanded, expected);
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k2_routing_replacement_remains_repeated_pad_only() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: false,
        };
        let image = MmImageEntry {
            mm_hash: 0x5678,
            width: 320,
            height: 240,
        };
        let fill = dynamo_kv_router::protocols::pad_value_for_mm_hash(image.mm_hash);
        let mut expanded = vec![7];

        append_mm_routing_replacement(
            &mut expanded,
            &tokenizer,
            RoutingImagePromptLayout::RepeatedPad,
            image,
            3,
        )
        .unwrap();

        assert_eq!(expanded, vec![7, fill, fill, fill]);
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k3_layout_resolution_rejects_non_atomic_control_tokens() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: false,
            fail_plain_text: false,
        };

        let error =
            resolve_routing_image_prompt_layout(&tokenizer, lightseek_mm::ImagePromptKind::KimiK3)
                .unwrap_err();

        assert!(error.to_string().contains("expected exactly one"));
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k3_expansion_reports_reference_exact_prompt_length() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: false,
        };
        let layout =
            resolve_routing_image_prompt_layout(&tokenizer, lightseek_mm::ImagePromptKind::KimiK3)
                .unwrap();
        let image = MmImageEntry {
            mm_hash: 0x1234,
            width: 320,
            height: 240,
        };
        let dimension_token_count = "image 320x240".len();
        let image_token_count = 3;

        let (expanded, expanded_prompt_len) = expand_mm_routing_tokens(
            &tokenizer,
            layout,
            None,
            163605,
            &[image],
            &[image_token_count],
            &[7, 163605, 8],
        )
        .unwrap();

        // vLLM's K3 prompt update replaces one placeholder with:
        // begin + dimension text + content + image tokens + end.
        let reference_len = 2 + 3 + dimension_token_count + image_token_count;
        assert_eq!(expanded_prompt_len, reference_len);
        assert_eq!(expanded.len(), reference_len);
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k3_exact_prompt_length_matches_upstream_processor_replacement() {
        use llm_multimodal::vision::{PreProcessorConfig, VisionProcessorRegistry};

        let config = serde_json::json!({
            "model_type": "kimi_k3",
            "media_placeholder_token_id": 163605
        });
        let reference_tokenizer = ReferenceK3Tokenizer;
        let metadata = llm_multimodal::ModelMetadata {
            model_id: "moonshotai/Kimi-K3",
            tokenizer: &reference_tokenizer,
            config: &config,
        };
        let registry = llm_multimodal::ModelRegistry::new();
        let spec = registry.lookup(&metadata).unwrap();
        let vision_registry = VisionProcessorRegistry::with_defaults();
        let processor = vision_registry
            .find("moonshotai/Kimi-K3", Some("kimi_k3"))
            .unwrap();
        let image = image::DynamicImage::new_rgb8(320, 240);
        let processed = processor
            .preprocess(&[image], &PreProcessorConfig::default())
            .unwrap();
        let reference_replacements = spec.prompt_replacements(&metadata, &processed).unwrap();
        let reference_replacement = &reference_replacements[0];

        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: false,
        };
        let layout =
            resolve_routing_image_prompt_layout(&tokenizer, lightseek_mm::ImagePromptKind::KimiK3)
                .unwrap();
        let image_entry = MmImageEntry {
            mm_hash: 0x1234,
            width: 320,
            height: 240,
        };
        let (expanded, expanded_prompt_len) = expand_mm_routing_tokens(
            &tokenizer,
            layout,
            None,
            163605,
            &[image_entry],
            &processed.feature_token_counts,
            &[7, 163605, 8],
        )
        .unwrap();

        let reference_prompt_len = 2 + reference_replacement.tokens.len();
        assert_eq!(expanded_prompt_len, reference_prompt_len);
        assert_eq!(expanded.len(), reference_prompt_len);
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn kimi_k3_plain_text_encode_failure_is_routing_only() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: true,
        };
        let layout =
            resolve_routing_image_prompt_layout(&tokenizer, lightseek_mm::ImagePromptKind::KimiK3)
                .unwrap();
        let image = MmImageEntry {
            mm_hash: 0x1234,
            width: 320,
            height: 240,
        };

        let result = try_expand_mm_routing_tokens(
            &tokenizer,
            layout,
            None,
            163605,
            &[image],
            &[3],
            &[7, 163605, 8],
            "moonshotai/Kimi-K3",
        );

        assert!(result.is_none());
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn image_expansion_applies_placeholders_in_request_order() {
        let tokenizer = RoutingTestTokenizer {
            atomic_controls: true,
            fail_plain_text: false,
        };
        let images = [
            MmImageEntry {
                mm_hash: 0x1234,
                width: 320,
                height: 240,
            },
            MmImageEntry {
                mm_hash: 0x5678,
                width: 640,
                height: 480,
            },
        ];
        let first_fill = dynamo_kv_router::protocols::pad_value_for_mm_hash(images[0].mm_hash);
        let second_fill = dynamo_kv_router::protocols::pad_value_for_mm_hash(images[1].mm_hash);

        let (expanded, prompt_len) = expand_mm_routing_tokens(
            &tokenizer,
            RoutingImagePromptLayout::RepeatedPad,
            Some(1),
            10,
            &images,
            &[2, 3],
            &[7, 10, 8, 10, 9],
        )
        .unwrap();

        assert_eq!(
            expanded,
            [
                1,
                7,
                first_fill,
                first_fill,
                8,
                second_fill,
                second_fill,
                second_fill,
                9,
            ]
        );
        assert_eq!(prompt_len, expanded.len());
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn exact_routing_rejects_image_placeholder_count_mismatch() {
        let model_dir = tempfile::tempdir().unwrap();
        std::fs::write(model_dir.path().join("preprocessor_config.json"), "{}").unwrap();
        let counter = lightseek_mm::LightseekMmCounter::try_new(
            "Qwen/Qwen3-VL-2B-Instruct",
            Some("qwen3_vl"),
            model_dir.path(),
        )
        .unwrap();
        let mdc = ModelDeploymentCard::load_from_disk(
            "tests/data/sample-models/mock-llama-3.1-8b-instruct",
            None,
        )
        .unwrap();
        let mut preprocessor = match Arc::try_unwrap(OpenAIPreprocessor::new(mdc).unwrap()) {
            Ok(preprocessor) => preprocessor,
            Err(_) => panic!("test preprocessor unexpectedly shared"),
        };
        preprocessor.image_token_counter = Some(counter);
        preprocessor.routing_image_token_id = Some(10);
        preprocessor.routing_image_prompt_layout = Some(RoutingImagePromptLayout::RepeatedPad);
        preprocessor.kv_cache_block_size = 16;
        let image = [MmRoutingEntry::Image {
            mm_hash: 0x1234,
            width: 320,
            height: 240,
        }];

        assert!(
            preprocessor
                .build_mm_exact_routing_info(&image, &[7, 8])
                .is_none(),
            "missing placeholder must fail closed at the production boundary"
        );
        assert!(
            preprocessor
                .build_mm_exact_routing_info(&image, &[7, 10, 10, 8])
                .is_none(),
            "extra placeholder must fail closed at the production boundary"
        );
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn mm_processor_override_is_conservative() {
        assert!(!has_mm_processor_override(None));
        assert!(!has_mm_processor_override(Some(&serde_json::Value::Null)));
        assert!(!has_mm_processor_override(Some(&serde_json::json!({}))));
        assert!(has_mm_processor_override(Some(&serde_json::json!([]))));
        assert!(has_mm_processor_override(Some(
            &serde_json::json!({"min_pixels": 64})
        )));
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn processor_kwargs_disable_exact_mm_routing() {
        assert!(exact_mm_routing_preconditions_met(false, 1, 1, false));
        assert!(!exact_mm_routing_preconditions_met(false, 1, 1, true));
        assert!(!exact_mm_routing_preconditions_met(true, 1, 1, false));
        assert!(!exact_mm_routing_preconditions_met(false, 0, 1, false));
    }

    #[cfg(all(feature = "mm-routing", feature = "media-ffmpeg"))]
    #[test]
    fn decoded_video_hash_requires_exact_routing_eligibility() {
        assert!(should_hash_decoded_video(true, false, false, true));
        assert!(!should_hash_decoded_video(false, false, false, true));
        assert!(!should_hash_decoded_video(true, true, false, true));
        assert!(!should_hash_decoded_video(true, false, true, true));
        assert!(!should_hash_decoded_video(true, false, false, false));
    }

    #[test]
    fn replace_reserved_media_slot_preserves_alignment_and_returns_errors() {
        let mut map = HashMap::from([(
            "image_url".to_string(),
            vec![
                url_entry("http://x/a.png"),
                MultimodalData::UuidOnly("cached-b".to_string()),
                url_entry("http://x/c.png"),
            ],
        )]);

        OpenAIPreprocessor::replace_reserved_media_slot(
            &mut map,
            "image_url",
            2,
            MultimodalData::RawUrl("decoded-c".to_string()),
        )
        .unwrap();

        let images = &map["image_url"];
        assert!(matches!(images[0], MultimodalData::Url(_)));
        assert!(matches!(
            &images[1],
            MultimodalData::UuidOnly(uuid) if uuid == "cached-b"
        ));
        assert!(matches!(
            &images[2],
            MultimodalData::RawUrl(value) if value == "decoded-c"
        ));

        let error = OpenAIPreprocessor::replace_reserved_media_slot(
            &mut map,
            "image_url",
            3,
            MultimodalData::RawUrl("out-of-range".to_string()),
        )
        .expect_err("an out-of-range reserved slot must return an error");
        assert!(error.to_string().contains("image_url[3]"));
    }

    #[test]
    fn routing_priorities_keep_strict_tier_independent() {
        let hints = crate::protocols::common::extensions::AgentHints {
            priority: Some(-3),
            strict_priority: Some(7),
            ..Default::default()
        };

        assert_eq!(
            routing_priorities(Some(&hints)),
            (Some(0.0), Some(7), Some(-3))
        );
        assert_eq!(routing_priorities(None), (None, None, None));
    }

    fn test_llm_metrics_annotation() -> LLMMetricAnnotation {
        LLMMetricAnnotation {
            input_tokens: 10,
            output_tokens: 20,
            chunk_tokens: 3,
            cached_tokens: Some(4),
            image_tokens: Some(512),
            prefill_worker_id: Some(1),
            prefill_dp_rank: Some(2),
            prefill_worker_type: Some("prefill".to_string()),
            decode_worker_id: Some(3),
            decode_dp_rank: Some(4),
            decode_worker_type: Some("decode".to_string()),
            tokenize_latency: Some(std::time::Duration::from_millis(5)),
            detokenize_total_latency: Some(std::time::Duration::from_micros(50)),
            detokenize_count: Some(6),
            ..Default::default()
        }
    }

    #[test]
    fn llm_metrics_from_annotation_recognizes_both_metric_event_tags() {
        // Both the per-chunk `llm_metrics` event and the payload-only `payload_usage`
        // event carry the serialized LLMMetricAnnotation as their comment and must
        // be observed by the metrics collector.
        let base = test_llm_metrics_annotation()
            .to_annotation::<()>()
            .expect("metrics annotation serializes");
        for tag in [ANNOTATION_LLM_METRICS, ANNOTATION_PAYLOAD_USAGE] {
            let tagged = Annotated::<()> {
                id: None,
                data: None,
                event: Some(tag.to_string()),
                comment: base.comment.clone(),
                error: None,
            };
            let metrics = LLMMetricAnnotation::from_annotation(&tagged)
                .expect("metrics annotation parses")
                .unwrap_or_else(|| panic!("metrics recognized for tag {tag}"));
            assert_eq!(metrics.input_tokens, 10);
            assert_eq!(metrics.output_tokens, 20);
            assert_eq!(metrics.image_tokens, Some(512));
            assert_eq!(metrics.detokenize_count, Some(6));
        }
    }

    #[test]
    fn llm_metrics_from_annotation_ignores_untagged_and_other_events() {
        // No event → not metrics (per-chunk metrics are event-tagged again).
        let untagged = Annotated::<()> {
            id: None,
            data: None,
            event: None,
            comment: Some(vec!["{\"input_tokens\":1}".to_string()]),
            error: None,
        };
        assert!(
            LLMMetricAnnotation::from_annotation(&untagged)
                .expect("untagged chunk is not an error")
                .is_none()
        );

        // A different event tag → not metrics.
        let other = Annotated::<()> {
            id: None,
            data: None,
            event: Some(ANNOTATION_TOKEN_IDS.to_string()),
            comment: None,
            error: None,
        };
        assert!(
            LLMMetricAnnotation::from_annotation(&other)
                .expect("other event is not an error")
                .is_none()
        );
    }

    /// PRE.1 — `skip_special_tokens` default. See `lib/llm/PREPROCESSOR_CASES.md`.
    #[test]
    fn test_parser_requires_special_tokens() {
        let cases: &[(Option<&str>, Option<&str>, bool, &str)] = &[
            (
                Some("gemma4"),
                None,
                true,
                "gemma4 tool-call only → required",
            ),
            (
                None,
                Some("gemma4"),
                true,
                "gemma4 reasoning only → required",
            ),
            (
                Some("gemma-4"),
                None,
                true,
                "gemma-4 hyphen alias (tool) → required",
            ),
            (
                None,
                Some("gemma-4"),
                true,
                "gemma-4 hyphen alias (reasoning) → required",
            ),
            (
                Some("gemma4"),
                Some("gemma4"),
                true,
                "gemma4 paired → required",
            ),
            (Some("hermes"), None, false, "hermes → not required"),
            (
                Some("harmony"),
                None,
                true,
                "harmony tool-call only → required",
            ),
            (
                None,
                Some("gpt_oss"),
                true,
                "gpt_oss reasoning only → required",
            ),
            (
                Some("harmony"),
                Some("gpt_oss"),
                true,
                "harmony + gpt_oss paired → required",
            ),
            (
                Some("kimi_k2"),
                Some("kimi_k25"),
                true,
                "kimi_k2 + kimi_k25 paired → required \
                 (tool-call markers `<|tool_calls_section_*|>` and reasoning \
                  marker `</think>` are special tokens that get stripped under \
                  the default skip_special_tokens=true)",
            ),
            (
                None,
                Some("kimi_k25"),
                true,
                "kimi_k25 reasoning only → required (`</think>` is special token id 163607)",
            ),
            (
                Some("kimi_k3"),
                Some("kimi_k3"),
                true,
                "kimi_k3 paired XTML parsers → required",
            ),
            (
                Some("kimi-k3"),
                Some("kimi-k3"),
                true,
                "kimi-k3 aliases → required",
            ),
            (
                None,
                Some("mistral"),
                true,
                "mistral reasoning only → required (`[THINK]` / `[/THINK]` are special tokens)",
            ),
            (
                Some("kimi_k2"),
                None,
                true,
                "kimi_k2 tool-call only → required \
                 (`<|tool_calls_section_begin|>` / `<|tool_calls_section_end|>` are special)",
            ),
            (
                Some("minimax_m3"),
                Some("minimax_m3"),
                true,
                "minimax_m3 paired → required",
            ),
            (
                Some("minimax-m3-nom"),
                Some("minimax-m3"),
                true,
                "MiniMax M3 SGLang aliases → required",
            ),
            (
                Some("muse_glimmer"),
                None,
                true,
                "muse_glimmer tool-call only → required \
                 (`<|start|>` / `<|message|>` / `<|eom|>` / `<|eot|>` are special)",
            ),
            (
                None,
                Some("muse_glimmer"),
                true,
                "muse_glimmer reasoning-name only → required",
            ),
            (
                Some("muse"),
                None,
                true,
                "muse (SGLang's registered name, tool) → required",
            ),
            (None, None, false, "no parsers → not required"),
        ];
        for (tool, reasoning, expected, desc) in cases {
            assert_eq!(
                OpenAIPreprocessor::parser_requires_special_tokens(*tool, *reasoning),
                *expected,
                "FAILED: {desc}",
            );
        }
    }

    /// Guard: a caller forcing `skip_special_tokens=true` while a
    /// special-token-dependent parser is active strips the markers before
    /// parsing → silent empty tool_calls / leaked markup. Only that exact
    /// combination should trip the warning condition.
    #[test]
    fn test_special_tokens_will_be_stripped() {
        let f = OpenAIPreprocessor::special_tokens_will_be_stripped;
        // forced-true + marker-dependent parser → will be stripped (warn)
        assert!(f(Some(true), Some("harmony"), Some("gpt_oss")));
        assert!(f(Some(true), Some("harmony"), None));
        assert!(f(Some(true), None, Some("gpt_oss")));
        assert!(f(Some(true), Some("kimi_k2"), None));
        assert!(f(Some(true), Some("kimi_k3"), Some("kimi_k3")));
        assert!(f(Some(true), None, Some("mistral")));
        // false / unset → never (default path keeps the markers)
        assert!(!f(Some(false), Some("harmony"), None));
        assert!(!f(None, Some("harmony"), None));
        // forced-true but parser doesn't need special tokens → fine
        assert!(!f(Some(true), Some("hermes"), None));
        assert!(!f(Some(true), None, None));
    }

    #[test]
    fn test_kimi_k3_jail_always_unwraps_xtml_response_channels() {
        let parser = "kimi_k3".to_string();
        assert!(OpenAIPreprocessor::should_apply_tool_jail(Some(&parser), None, false).unwrap());

        let alias = "kimi-k3".to_string();
        assert!(
            OpenAIPreprocessor::should_apply_tool_jail(
                Some(&alias),
                Some(&ChatCompletionToolChoiceOption::None),
                true,
            )
            .unwrap()
        );
    }

    /// Verifies which force-reasoning parsers use guided-output shape detection.
    #[test]
    fn test_reasoning_before_guided_json_parser_allowlist() {
        for parser in [
            "deepseek_r1",
            "deepseek_v3",
            "deepseek_v3_1",
            "deepseek_v3_2",
            "step3",
            "kimi_k25",
            "mistral",
            "minimax_m2",
            "nemotron_nano",
            "nemotron3",
            "nemotron_v3",
        ] {
            assert!(
                OpenAIPreprocessor::supports_reasoning_before_guided_json(Some(parser)),
                "{parser} should inspect guided output shape"
            );
        }

        assert!(
            !OpenAIPreprocessor::supports_reasoning_before_guided_json(Some(
                "minimax_append_think"
            )),
            "minimax_append_think must retain the guided-JSON bypass"
        );
    }

    /// Verifies parser-specific openers that can be confused with guided JSON.
    #[test]
    fn test_guided_json_reasoning_start_tokens() {
        assert_eq!(
            OpenAIPreprocessor::guided_json_reasoning_start_token(Some("mistral")),
            Some("[THINK]")
        );
        assert_eq!(
            OpenAIPreprocessor::guided_json_reasoning_start_token(Some("nemotron_v3")),
            None
        );
    }

    #[test]
    fn test_prompt_injected_reasoning_start_by_parser() {
        let cases = [
            (
                Some("minimax_m3"),
                Some("...<mm:think>\n"),
                true,
                "MiniMax M3 starts from <mm:think>",
            ),
            (
                Some("minimax-m3"),
                Some("...</mm:think>\n"),
                false,
                "MiniMax M3 prefilled end marker means not in reasoning",
            ),
            (
                Some("minimax_m3"),
                Some("...<think>\n"),
                false,
                "MiniMax M3 must not use generic <think>",
            ),
            (
                Some("qwen3"),
                Some("...<think>\n"),
                true,
                "Qwen-style templated <think> behavior remains",
            ),
            (
                Some("kimi_k3"),
                Some("...<|open|>think<|sep|>\n"),
                true,
                "Kimi K3 starts inside its XTML think channel",
            ),
            (
                Some("kimi-k3"),
                Some("...<think>\n"),
                false,
                "Kimi K3 must not use the generic think marker",
            ),
            (
                Some("deepseek_v4"),
                Some("...<think>\n"),
                true,
                "existing <think> parser behavior remains",
            ),
            (
                None,
                Some("...<think>\n"),
                true,
                "legacy no-parser detection",
            ),
            (Some("minimax_m3"), None, false, "no prompt"),
        ];

        for (parser, prompt, expected, desc) in cases {
            assert_eq!(
                OpenAIPreprocessor::prompt_injected_reasoning_start(parser, prompt),
                expected,
                "FAILED: {desc}",
            );
        }
    }

    #[test]
    fn test_prompt_injected_reasoning_ended_backend_arg_by_parser() {
        let cases = [
            (
                Some("minimax_m2"),
                Some("...<think>\n"),
                Some(false),
                "MiniMax M2 needs native backend reasoning state aligned with the prompt",
            ),
            (
                Some("minimax_m3"),
                Some("...<mm:think>\n"),
                Some(false),
                "MiniMax M3 needs native backend reasoning state aligned with the prompt",
            ),
            (
                Some("kimi_k3"),
                Some("...<|open|>think<|sep|>\n"),
                Some(false),
                "Kimi K3 guided decoding must start after its prompt-opened think channel",
            ),
            (
                Some("deepseek_v4"),
                Some("...<think>\n"),
                None,
                "DeepSeek V4 native guided JSON must not be forced into reasoning mode",
            ),
            (
                Some("deepseek-v4"),
                Some("...<think>\n"),
                None,
                "DeepSeek V4 alias must not receive reasoning_ended=false",
            ),
            (
                Some("qwen3"),
                Some("...<think>\n"),
                None,
                "Qwen-style prompt injection is handled by Dynamo postprocessing only",
            ),
            (
                Some("minimax_m2"),
                Some("plain prompt"),
                None,
                "no injected reasoning opener means no backend state override",
            ),
        ];

        for (parser, prompt, expected, desc) in cases {
            assert_eq!(
                OpenAIPreprocessor::prompt_injected_reasoning_ended_arg(parser, prompt),
                expected,
                "FAILED: {desc}",
            );
        }
    }

    #[test]
    fn test_backend_extra_args_preserves_nvext_and_sampling_extensions() {
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}],
            "detokenize": false,
            "allowed_token_ids": [10, 11],
            "bad_words_token_ids": [[12, 13]],
            "logprob_token_ids": [14, 15],
            "nvext": {
                "cache_salt": "step_7",
                "extra_fields": ["completion_token_ids"],
                "metadata_upload": {
                    "url": "s3://bucket/root/rollouts"
                }
            }
        }))
        .unwrap();

        let extra_args = OpenAIPreprocessor::backend_extra_args(&request, false, None).unwrap();

        assert_eq!(extra_args["nvext"]["cache_salt"], "step_7");
        assert_eq!(
            extra_args["nvext"]["extra_fields"],
            serde_json::json!(["completion_token_ids"])
        );
        assert_eq!(
            extra_args["nvext"]["metadata_upload"],
            serde_json::json!({
                "url": "s3://bucket/root/rollouts"
            })
        );
        assert_eq!(extra_args["sampling_options"]["detokenize"], false);
        assert_eq!(
            extra_args["sampling_options"]["allowed_token_ids"],
            serde_json::json!([10, 11])
        );
        assert_eq!(
            extra_args["sampling_options"]["bad_words_token_ids"],
            serde_json::json!([[12, 13]])
        );
        assert_eq!(
            extra_args["sampling_options"]["logprob_token_ids"],
            serde_json::json!([14, 15])
        );
    }

    #[test]
    fn capture_prompt_token_ids_is_exact_and_opt_in() {
        let requested: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}],
            "nvext": {"extra_fields": ["prompt_token_ids"]}
        }))
        .unwrap();
        let tracker = RequestTracker::new();

        OpenAIPreprocessor::capture_prompt_token_ids(&requested, Some(&tracker), &[101, 102, 103]);
        assert_eq!(tracker.prompt_token_ids(), Some(&[101u32, 102, 103][..]));

        let ordinary: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}]
        }))
        .unwrap();
        let ordinary_tracker = RequestTracker::new();
        OpenAIPreprocessor::capture_prompt_token_ids(
            &ordinary,
            Some(&ordinary_tracker),
            &[201, 202],
        );
        assert!(ordinary_tracker.prompt_token_ids().is_none());
    }

    fn chat_request_with_args(
        chat_template_args: Option<HashMap<String, serde_json::Value>>,
    ) -> NvCreateChatCompletionRequest {
        let mut request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [{"role": "user", "content": "hi"}]
            }))
            .unwrap();
        request.chat_template_args = chat_template_args;
        request
    }

    fn runtime_config_with_default_thinking_mode(
        mode: &str,
    ) -> crate::local_model::runtime_config::ModelRuntimeConfig {
        let mut runtime_config = crate::local_model::runtime_config::ModelRuntimeConfig::new();
        runtime_config
            .set_engine_specific(DEFAULT_THINKING_MODE_RUNTIME_KEY, mode)
            .unwrap();
        runtime_config
    }

    #[test]
    fn test_default_thinking_mode_disabled_adds_template_args() {
        let runtime_config = runtime_config_with_default_thinking_mode("disabled");
        let mut request = chat_request_with_args(None);

        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );

        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
    }

    #[test]
    fn test_default_thinking_mode_enabled_adds_template_args() {
        let runtime_config = runtime_config_with_default_thinking_mode("enabled");
        let mut request = chat_request_with_args(None);

        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );

        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(true)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(true)));
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("enabled"))
        );
    }

    #[test]
    fn test_gemma4_default_thinking_mode_controls_reasoning_parser() {
        for (mode, expected_disabled) in [("enabled", false), ("disabled", true)] {
            let runtime_config = runtime_config_with_default_thinking_mode(mode);
            let mut request = chat_request_with_args(None);

            OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
                &runtime_config,
                &mut request,
            );

            for parser in ["gemma4", "gemma-4"] {
                assert_eq!(
                    OpenAIPreprocessor::is_reasoning_disabled_by_request(
                        Some(parser),
                        request.chat_template_args.as_ref(),
                    ),
                    expected_disabled,
                    "parser={parser}, default_thinking_mode={mode}",
                );
            }
        }
    }

    #[test]
    fn test_default_thinking_mode_does_not_override_request() {
        let runtime_config = runtime_config_with_default_thinking_mode("disabled");
        let mut request = chat_request_with_args(Some(HashMap::from([(
            "thinking_mode".to_string(),
            serde_json::json!("enabled"),
        )])));

        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );

        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("enabled"))
        );
        assert!(!args.contains_key("thinking"));
        assert!(!args.contains_key("enable_thinking"));
    }

    #[test]
    fn test_default_thinking_mode_precedes_parser_implicit_default() {
        let runtime_config = runtime_config_with_default_thinking_mode("disabled");
        let mut request = chat_request_with_args(None);

        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("kimi_k25"), None);

        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
    }

    #[test]
    fn test_default_thinking_mode_does_not_override_reasoning_effort() {
        let runtime_config = runtime_config_with_default_thinking_mode("disabled");
        let mut request = chat_request_with_args(Some(HashMap::from([(
            "reasoning_effort".to_string(),
            serde_json::json!("high"),
        )])));

        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );

        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("reasoning_effort"),
            Some(&serde_json::json!("high"))
        );
        assert!(!args.contains_key("thinking"));
        assert!(!args.contains_key("enable_thinking"));
        assert!(!args.contains_key("thinking_mode"));
    }

    /// Verifies template reasoning controls are forwarded to a configured parser.
    #[test]
    fn test_backend_extra_args_forwards_reasoning_template_args() {
        for enable_thinking in [true, false] {
            let request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "model": "test-model",
                    "messages": [{"role": "user", "content": "hi"}],
                    "chat_template_kwargs": {
                        "enable_thinking": enable_thinking,
                        "reasoning_effort": "high"
                    }
                }))
                .unwrap();

            let extra_args =
                OpenAIPreprocessor::backend_extra_args(&request, true, Some(false)).unwrap();

            assert_eq!(
                extra_args["reasoning_parser_kwargs"]["chat_template_kwargs"],
                serde_json::json!({
                    "enable_thinking": enable_thinking,
                    "reasoning_effort": "high"
                })
            );
            assert_eq!(extra_args["reasoning_ended"], false);
        }
    }

    /// Verifies parser metadata is omitted when no reasoning parser is configured.
    #[test]
    fn test_backend_extra_args_omits_reasoning_metadata_without_configured_parser() {
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}],
            "detokenize": false,
            "chat_template_kwargs": {
                "enable_thinking": true
            }
        }))
        .unwrap();

        let extra_args =
            OpenAIPreprocessor::backend_extra_args(&request, false, Some(false)).unwrap();

        assert_eq!(extra_args["sampling_options"]["detokenize"], false);
        assert!(extra_args.get("reasoning_parser_kwargs").is_none());
        assert!(extra_args.get("reasoning_ended").is_none());
    }

    /// Verifies no parser metadata is added when template arguments are absent.
    #[test]
    fn test_backend_extra_args_omits_reasoning_metadata_without_template_args() {
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}]
        }))
        .unwrap();

        assert!(OpenAIPreprocessor::backend_extra_args(&request, true, None).is_none());
    }

    /// Verifies the SGLang reasoning gate covers forced tool JSON and
    /// structured assistant output while honoring per-request thinking controls.
    #[test]
    fn test_guided_output_requires_reasoning() {
        let request = |tool_choice: serde_json::Value, enable_thinking: Option<bool>| {
            let mut value = serde_json::json!({
                "model": "test-model",
                "messages": [{"role": "user", "content": "use the tool"}],
                "tools": [{
                    "type": "function",
                    "function": {
                        "name": "lookup",
                        "parameters": {"type": "object", "properties": {}}
                    }
                }],
                "tool_choice": tool_choice
            });
            if let Some(enabled) = enable_thinking {
                value["chat_template_kwargs"] = serde_json::json!({
                    "enable_thinking": enabled
                });
            }
            serde_json::from_value::<NvCreateChatCompletionRequest>(value).unwrap()
        };

        let required = request(serde_json::json!("required"), Some(true));
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &required,
            Some("nemotron_v3")
        ));

        let named = request(
            serde_json::json!({
                "type": "function",
                "function": {"name": "lookup"}
            }),
            None,
        );
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &named,
            Some("nemotron_v3")
        ));

        let disabled = request(serde_json::json!("required"), Some(false));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &disabled,
            Some("nemotron_v3")
        ));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &required, None
        ));

        let automatic = request(serde_json::json!("auto"), Some(true));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &automatic,
            Some("nemotron_v3")
        ));

        let gemma_without_opt_in = request(serde_json::json!("required"), None);
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &gemma_without_opt_in,
            Some("gemma4")
        ));
        let gemma_with_opt_in = request(serde_json::json!("required"), Some(true));
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &gemma_with_opt_in,
            Some("gemma4")
        ));

        let deepseek_default = request(serde_json::json!("required"), None);
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &deepseek_default,
            Some("deepseek_v4")
        ));
        let deepseek_disabled = request(serde_json::json!("required"), Some(false));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &deepseek_disabled,
            Some("deepseek_v4")
        ));

        let structured_request = |enable_thinking: bool| {
            serde_json::from_value::<NvCreateChatCompletionRequest>(serde_json::json!({
                "model": "test-model",
                "messages": [{"role": "user", "content": "return json"}],
                "chat_template_kwargs": {"enable_thinking": enable_thinking},
                "response_format": {
                    "type": "json_schema",
                    "json_schema": {
                        "name": "result",
                        "schema": {"type": "object"}
                    }
                }
            }))
            .unwrap()
        };
        let json_object_request = |enable_thinking: bool| {
            serde_json::from_value::<NvCreateChatCompletionRequest>(serde_json::json!({
                "model": "test-model",
                "messages": [{"role": "user", "content": "return json"}],
                "chat_template_kwargs": {"enable_thinking": enable_thinking},
                "response_format": {"type": "json_object"}
            }))
            .unwrap()
        };
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &structured_request(true),
            Some("qwen3")
        ));
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &json_object_request(true),
            Some("qwen3")
        ));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &structured_request(false),
            Some("qwen3")
        ));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &structured_request(true),
            Some("gpt_oss")
        ));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &json_object_request(true),
            Some("gpt_oss")
        ));
        assert!(!OpenAIPreprocessor::guided_output_requires_reasoning(
            &structured_request(false),
            Some("gpt_oss")
        ));
        assert!(OpenAIPreprocessor::guided_output_requires_reasoning(
            &request(serde_json::json!("required"), None),
            Some("gpt_oss")
        ));
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn exact_mm_routing_rejects_backend_owned_modalities() {
        assert!(exact_mm_routing_supports_modality("image_url", false));
        assert!(exact_mm_routing_supports_modality("video_url", true));
        assert!(!exact_mm_routing_supports_modality("video_url", false));
        assert!(!exact_mm_routing_supports_modality("audio_url", true));
    }

    /// Verifies SGLang's effective reasoning mode for each parser family.
    #[test]
    fn test_sglang_effective_reasoning_enabled() {
        let cases = [
            ("qwen3", serde_json::json!({}), true),
            (
                "qwen3",
                serde_json::json!({"enable_thinking": false}),
                false,
            ),
            ("nemotron_v3", serde_json::json!({}), true),
            ("gemma4", serde_json::json!({}), false),
            ("gemma4", serde_json::json!({"enable_thinking": true}), true),
            ("deepseek_v4", serde_json::json!({}), true),
            ("deepseek_v4", serde_json::json!({"thinking": true}), true),
            (
                "deepseek_v4",
                serde_json::json!({"enable_thinking": true}),
                true,
            ),
            (
                "deepseek_v4",
                serde_json::json!({"thinking_mode": "thinking"}),
                true,
            ),
            (
                "deepseek_v4",
                serde_json::json!({"enable_thinking": false}),
                false,
            ),
            (
                "deepseek_v4",
                serde_json::json!({"thinking_mode": "chat"}),
                false,
            ),
            (
                "deepseek_v4",
                serde_json::json!({"thinking": false, "thinking_mode": "thinking"}),
                false,
            ),
            ("deepseek_v3_2", serde_json::json!({}), true),
            ("deepseek_v3_1", serde_json::json!({}), false),
            (
                "deepseek_v3_1",
                serde_json::json!({"enable_thinking": true}),
                true,
            ),
            ("kimi_k25", serde_json::json!({"thinking": false}), false),
            ("kimi_k3", serde_json::json!({}), true),
            ("kimi-k3", serde_json::json!({"thinking": false}), false),
            ("minimax_m2", serde_json::json!({}), true),
            ("minimax_m2", serde_json::json!({"thinking": false}), false),
            ("mistral", serde_json::json!({}), false),
            (
                "mistral",
                serde_json::json!({"reasoning_effort": "none"}),
                false,
            ),
            (
                "mistral",
                serde_json::json!({"reasoning_effort": "high"}),
                true,
            ),
            ("minimax_m3", serde_json::json!({}), true),
            (
                "minimax_m3",
                serde_json::json!({"thinking_mode": "disabled"}),
                false,
            ),
            ("gpt_oss", serde_json::json!({}), true),
            (
                "gpt_oss",
                serde_json::json!({"enable_thinking": true}),
                true,
            ),
            (
                "gpt_oss",
                serde_json::json!({"enable_thinking": false}),
                true,
            ),
            ("deepseek_r1", serde_json::json!({}), true),
            ("minimax_append_think", serde_json::json!({}), false),
            ("basic", serde_json::json!({}), false),
        ];

        for (parser, request_args, expected) in cases {
            let request_args = serde_json::from_value(request_args).unwrap();
            assert_eq!(
                OpenAIPreprocessor::sglang_effective_reasoning_enabled(
                    Some(parser),
                    Some(&request_args),
                ),
                expected,
                "parser={parser}, args={request_args:?}",
            );
        }
        assert!(!OpenAIPreprocessor::sglang_effective_reasoning_enabled(
            None, None
        ));
    }

    #[test]
    fn test_internal_preserve_omitted_max_tokens_option() {
        assert_eq!(
            OpenAIPreprocessor::omitted_max_tokens_default(
                10,
                Some(100),
                PreprocessRequestOptions::default()
            ),
            Some(90)
        );
        assert_eq!(
            OpenAIPreprocessor::omitted_max_tokens_default(
                10,
                Some(100),
                PreprocessRequestOptions {
                    preserve_omitted_max_tokens: true,
                },
            ),
            None
        );
        assert_eq!(
            OpenAIPreprocessor::omitted_max_tokens_default(
                10,
                None,
                PreprocessRequestOptions::default()
            ),
            None
        );
        assert_eq!(
            OpenAIPreprocessor::omitted_max_tokens_default(
                10,
                Some(0),
                PreprocessRequestOptions::default()
            ),
            Some(0)
        );
    }

    #[test]
    fn test_exact_prompt_len() {
        let images = MultimodalDataMap::from([(
            "image_url".to_string(),
            vec![MultimodalData::Url(
                url::Url::parse("https://example.com/image.png").unwrap(),
            )],
        )]);
        let videos = MultimodalDataMap::from([(
            "video_url".to_string(),
            vec![MultimodalData::Url(
                url::Url::parse("https://example.com/video.mp4").unwrap(),
            )],
        )]);
        let mixed = MultimodalDataMap::from([
            (
                "image_url".to_string(),
                vec![MultimodalData::Url(
                    url::Url::parse("https://example.com/image.png").unwrap(),
                )],
            ),
            (
                "audio_url".to_string(),
                vec![MultimodalData::Url(
                    url::Url::parse("https://example.com/audio.wav").unwrap(),
                )],
            ),
        ]);

        // Image-expanded length present: use it instead of placeholder tokens.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(Some(500), Some(&images), 12),
            Some(500)
        );
        // Expanded length 0 (serde-default / absent) with images: defer to backend.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(Some(0), Some(&images), 12),
            None
        );
        // No routing info but images present: defer to backend.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(None, Some(&images), 12),
            None
        );
        // Video/audio expansion is backend-owned, including mixed requests
        // whose routing metadata expands only the image portion.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(None, Some(&videos), 12),
            None
        );
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(Some(500), Some(&mixed), 12),
            None
        );
        // Text-only: use the token count.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(None, None, 12),
            Some(12)
        );
        // Expanded length 0 without media: fall back to the token count.
        assert_eq!(
            OpenAIPreprocessor::exact_prompt_len(Some(0), None, 12),
            Some(12)
        );
    }

    fn token_budget(
        combined_limit: u32,
        reject_prompt_overflow: bool,
        reject_total_overflow: bool,
    ) -> TokenBudget {
        TokenBudget {
            combined_limit,
            reject_prompt_overflow,
            reject_total_overflow,
        }
    }

    #[test]
    fn test_requested_token_budget_policy_matrix() {
        let cases = [
            // Exact combined limit is accepted.
            (3, Some(7), true, true, false),
            // One token beyond the combined limit is rejected.
            (3, Some(8), true, true, true),
            // A full prompt leaves no room for generation.
            (10, None, true, true, true),
            // Each rejection dimension can be delegated independently.
            (3, Some(8), true, false, false),
            (10, Some(8), false, true, false),
        ];

        for (
            prompt_len,
            max_tokens,
            reject_prompt_overflow,
            reject_total_overflow,
            should_reject,
        ) in cases
        {
            let budget = token_budget(10, reject_prompt_overflow, reject_total_overflow);
            assert_eq!(
                OpenAIPreprocessor::validate_requested_token_budget(
                    prompt_len,
                    max_tokens,
                    Some(&budget),
                )
                .is_err(),
                should_reject,
            );
        }
    }

    fn preprocessed_budget_request(max_tokens: Option<u32>) -> PreprocessedRequest {
        let stop_conditions = crate::protocols::common::StopConditions {
            max_tokens,
            ..Default::default()
        };

        PreprocessedRequest::builder()
            .model("test-model".to_string())
            .token_ids(vec![1, 2, 3])
            .stop_conditions(stop_conditions)
            .sampling_options(crate::protocols::common::SamplingOptions::default())
            .output_options(crate::protocols::common::OutputOptions::default())
            .build()
            .unwrap()
    }

    #[test]
    fn attach_agent_context_forwards_compaction() {
        let agent_context = AgentContext {
            session_id: "codex-thread".to_string(),
            parent_session_id: None,
            session_final: None,
            compaction: Some(AgentCompaction {
                trigger: Some("manual".to_string()),
                ..Default::default()
            }),
            kv_hints: None,
            input_trigger: None,
        };
        let mut context = PipelineContext::new(());
        context.insert(AGENT_CONTEXT_CONTEXT_KEY, agent_context.clone());
        let mut request = preprocessed_budget_request(None);

        attach_agent_context_from_context(&mut request, &context);

        assert_eq!(request.agent_context.as_ref(), Some(&agent_context));
        let wire = serde_json::to_value(&request).unwrap();
        assert_eq!(
            wire["agent_context"]["compaction"]["trigger"],
            serde_json::json!("manual")
        );
    }

    #[test]
    fn test_preprocessed_completion_budget_validation_and_deferral() {
        let text_request = preprocessed_budget_request(Some(8));
        let reject = token_budget(10, true, true);
        assert!(
            OpenAIPreprocessor::validate_preprocessed_token_budget(&text_request, Some(&reject))
                .is_err()
        );

        let defer_total = token_budget(10, true, false);
        assert_eq!(
            OpenAIPreprocessor::validate_preprocessed_token_budget(
                &text_request,
                Some(&defer_total),
            )
            .unwrap(),
            Some(3)
        );

        // Prompt embeddings do not expose their sequence length as token_ids.
        let mut embeddings_request = text_request.clone();
        embeddings_request.prompt_embeds = Some("opaque-tensor".to_string());
        assert_eq!(
            OpenAIPreprocessor::validate_preprocessed_token_budget(
                &embeddings_request,
                Some(&reject),
            )
            .unwrap(),
            None
        );
    }

    struct UnreachableBackend;

    #[async_trait]
    impl AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<BackendOutput>>, Error>
        for UnreachableBackend
    {
        async fn generate(
            &self,
            _request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<BackendOutput>>, Error> {
            panic!("request must be rejected before backend dispatch")
        }
    }

    #[tokio::test]
    async fn test_completion_operator_rejects_token_budget_overflow() {
        let mut mdc = ModelDeploymentCard::load_from_disk(
            "tests/data/sample-models/mock-llama-3.1-8b-instruct",
            None,
        )
        .unwrap();
        mdc.runtime_config.context_length = Some(100);
        mdc.runtime_config
            .set_engine_specific(TOKEN_BUDGET_RUNTIME_KEY, token_budget(10, true, true))
            .unwrap();
        let preprocessor = OpenAIPreprocessor::new(mdc).unwrap();

        let request = NvCreateCompletionRequest {
            inner: dynamo_protocols::types::CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: dynamo_protocols::types::Prompt::IntegerArray(vec![1, 2, 3]),
                max_tokens: Some(8),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
            metadata: None,
            return_tokens_as_token_ids: None,
            unsupported_fields: Default::default(),
        };
        let next: Arc<
            dyn AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<BackendOutput>>, Error>,
        > = Arc::new(UnreachableBackend);

        let result =
            Operator::generate(preprocessor.as_ref(), PipelineContext::new(request), next).await;
        let Err(err) = result else {
            panic!("over-budget completion should fail admission");
        };
        let dynamo_err = err
            .downcast_ref::<DynamoError>()
            .expect("error should preserve the DynamoError type");
        assert_eq!(dynamo_err.error_type(), ErrorType::InvalidArgument);
    }

    #[tokio::test]
    async fn chat_operator_rejects_invalid_legacy_jail_request_before_dispatch() {
        let mut mdc = ModelDeploymentCard::load_from_disk(
            "tests/data/sample-models/mock-llama-3.1-8b-instruct",
            None,
        )
        .unwrap();
        mdc.runtime_config.tool_call_parser = Some("hermes".to_string());
        let preprocessor = OpenAIPreprocessor::new(mdc).unwrap();
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "What is the weather?"}],
            "n": 2,
            "max_tokens": 4,
            "tools": [{
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get the weather",
                    "parameters": {"type": "object", "properties": {}}
                }
            }],
            "tool_choice": "auto",
            "nvext": {"extra_fields": ["engine_data"]}
        }))
        .unwrap();
        let next: Arc<
            dyn AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<BackendOutput>>, Error>,
        > = Arc::new(UnreachableBackend);

        let result =
            Operator::generate(preprocessor.as_ref(), PipelineContext::new(request), next).await;
        let Err(err) = result else {
            panic!("invalid legacy-jail request should fail admission");
        };
        let dynamo_err = err
            .downcast_ref::<DynamoError>()
            .expect("error should preserve the DynamoError type");
        assert_eq!(dynamo_err.error_type(), ErrorType::InvalidArgument);
        assert!(dynamo_err.to_string().contains("legacy tool-call parsing"));
    }

    fn test_prompt_formatter(template: &str) -> Arc<dyn OAIPromptFormatter> {
        let template: dynamo_renderer::ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": template
        }))
        .unwrap();
        match dynamo_renderer::PromptFormatter::from_parts(
            template,
            dynamo_renderer::ContextMixins::default(),
            false,
        )
        .unwrap()
        {
            dynamo_renderer::PromptFormatter::OAI(formatter) => formatter,
        }
    }

    fn assistant_only_request() -> NvCreateChatCompletionRequest {
        serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "assistant", "content": "prefill"}]
        }))
        .unwrap()
    }

    const REQUIRES_USER_TEMPLATE: &str = "\
        {% set ns = namespace(has_user=false) %}\
        {% for message in messages %}\
            {% if message['role'] == 'user' %}{% set ns.has_user = true %}{% endif %}\
        {% endfor %}\
        {% if not ns.has_user %}{{ raise_exception('No user query found in messages.') }}{% endif %}\
        {{ messages[0]['content'] }}";

    fn render_through_preprocessor(
        formatter: &dyn OAIPromptFormatter,
        request: &dyn OAIChatLikeRequest,
    ) -> Result<RenderedPrompt> {
        formatter
            .render_prompt(request)
            .map_err(OpenAIPreprocessor::map_prompt_render_error)
    }

    #[test]
    fn test_assistant_only_request_accepted_when_template_accepts_it() {
        let formatter = test_prompt_formatter(
            "{% for message in messages %}{{ message['role'] }}:{{ message['content'] }}{% endfor %}",
        );

        let rendered =
            render_through_preprocessor(formatter.as_ref(), &assistant_only_request()).unwrap();

        assert_eq!(rendered.as_str(), "assistant:prefill");
    }

    #[test]
    fn test_assistant_only_template_error_is_invalid_argument() {
        let formatter = test_prompt_formatter(REQUIRES_USER_TEMPLATE);

        let error = render_through_preprocessor(formatter.as_ref(), &assistant_only_request())
            .context("Failed to apply prompt template")
            .unwrap_err();
        let dynamo_error = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<DynamoError>())
            .expect("template render error should be classified as a DynamoError");

        assert_eq!(dynamo_error.error_type(), ErrorType::InvalidArgument);
        assert!(
            dynamo_error
                .message()
                .contains("No user query found in messages.")
        );
    }

    #[test]
    fn test_restrictive_template_accepts_request_with_user_message() {
        let formatter = test_prompt_formatter(REQUIRES_USER_TEMPLATE);
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hello"}]
        }))
        .unwrap();

        let rendered = render_through_preprocessor(formatter.as_ref(), &request).unwrap();

        assert_eq!(rendered.as_str(), "hello");
    }

    #[test]
    fn continue_final_message_leaves_last_assistant_open_on_llama_template() {
        let mut mdc = ModelDeploymentCard::load_from_disk(
            "tests/data/sample-models/mock-llama-3.1-8b-instruct",
            None,
        )
        .unwrap();
        mdc.set_name("test-model");
        let preprocessor = OpenAIPreprocessor::new(mdc).unwrap();

        let default_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [
                    {"role": "user", "content": "Continue this sentence"},
                    {"role": "assistant", "content": "LLM-Native Interaction"}
                ]
            }))
            .unwrap();
        let continue_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [
                    {"role": "user", "content": "Continue this sentence"},
                    {"role": "assistant", "content": "LLM-Native Interaction"}
                ],
                "add_generation_prompt": false,
                "continue_final_message": true
            }))
            .unwrap();

        let default_prompt = preprocessor
            .apply_template(&default_request)
            .unwrap()
            .unwrap();
        let continue_prompt = preprocessor
            .apply_template(&continue_request)
            .unwrap()
            .unwrap();

        assert!(
            default_prompt
                .as_str()
                .ends_with("<|start_header_id|>assistant<|end_header_id|>\n\n"),
            "default render should start a new assistant turn, got {:?}",
            default_prompt.as_str()
        );
        assert!(
            continue_prompt.as_str().ends_with("LLM-Native Interaction"),
            "continue_final_message should leave the last assistant open, got {:?}",
            continue_prompt.as_str()
        );
        assert!(
            !continue_prompt.as_str().contains(
                "LLM-Native Interaction<|eot_id|><|start_header_id|>assistant<|end_header_id|>"
            ),
            "continue_final_message must not close the last assistant and start a new turn, got {:?}",
            continue_prompt.as_str()
        );
    }

    #[test]
    fn should_add_generation_prompt_defaults_true_and_continue_forces_false() {
        use dynamo_renderer::OAIChatLikeRequest;

        let unset: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{"role": "user", "content": "hi"}]
        }))
        .unwrap();
        assert!(unset.should_add_generation_prompt());

        let explicit_false: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [{"role": "user", "content": "hi"}],
                "add_generation_prompt": false
            }))
            .unwrap();
        assert!(!explicit_false.should_add_generation_prompt());

        let continue_with_false: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [
                    {"role": "user", "content": "hi"},
                    {"role": "assistant", "content": "partial"}
                ],
                "add_generation_prompt": false,
                "continue_final_message": true
            }))
            .unwrap();
        assert!(!continue_with_false.should_add_generation_prompt());
    }

    /// Qwen-style templates close every turn, including the last assistant. Truncate
    /// after render is what actually leaves the prefix open; Llama's mock template
    /// already omits the last eot when `add_generation_prompt` is false.
    const QWEN_STYLE_TEMPLATE: &str = "\
{%- for message in messages -%}\
{%- if message.role == 'user' -%}{{ '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}\
{%- elif message.role == 'assistant' -%}{{ '<|im_start|>assistant\n' + message.content + '<|im_end|>\n' }}\
{%- endif -%}\
{%- endfor -%}\
{%- if add_generation_prompt -%}{{ '<|im_start|>assistant\n' }}{%- endif -%}";

    fn continue_request() -> NvCreateChatCompletionRequest {
        serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "Continue this sentence"},
                {"role": "assistant", "content": "LLM-Native Interaction"}
            ],
            "add_generation_prompt": false,
            "continue_final_message": true
        }))
        .unwrap()
    }

    fn render_with_continue_final_message(
        formatter: &dyn OAIPromptFormatter,
        request: &NvCreateChatCompletionRequest,
    ) -> RenderedPrompt {
        use crate::protocols::openai::common_ext::CommonExtProvider;

        let continue_final = request.get_continue_final_message() == Some(true);
        let rendered = if continue_final {
            formatter
                .render_prompt(&NormalizedArgsRequest {
                    inner: request,
                    normalize_tool_call_args: false,
                    continue_final_message: true,
                })
                .unwrap()
        } else {
            formatter.render_prompt(request).unwrap()
        };
        if continue_final {
            apply_continue_final_message(rendered).unwrap()
        } else {
            rendered
        }
    }

    #[test]
    fn continue_final_message_strips_qwen_style_closing_tokens() {
        let formatter = test_prompt_formatter(QWEN_STYLE_TEMPLATE);
        let default_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [
                    {"role": "user", "content": "Continue this sentence"},
                    {"role": "assistant", "content": "LLM-Native Interaction"}
                ]
            }))
            .unwrap();
        let closed_only: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test-model",
                "messages": [
                    {"role": "user", "content": "Continue this sentence"},
                    {"role": "assistant", "content": "LLM-Native Interaction"}
                ],
                "add_generation_prompt": false
            }))
            .unwrap();

        let default_prompt =
            render_with_continue_final_message(formatter.as_ref(), &default_request);
        let closed_prompt = render_with_continue_final_message(formatter.as_ref(), &closed_only);
        let continue_prompt =
            render_with_continue_final_message(formatter.as_ref(), &continue_request());

        assert!(
            default_prompt.as_str().ends_with("<|im_start|>assistant\n"),
            "default Qwen render should start a new assistant turn, got {:?}",
            default_prompt.as_str()
        );
        assert!(
            closed_prompt
                .as_str()
                .ends_with("LLM-Native Interaction<|im_end|>\n"),
            "add_generation_prompt=false alone must still close the last assistant, got {:?}",
            closed_prompt.as_str()
        );
        assert_eq!(
            continue_prompt.as_str(),
            "<|im_start|>user\nContinue this sentence<|im_end|>\n<|im_start|>assistant\nLLM-Native Interaction"
        );
    }

    /// Raw turns `same / previous / same`; the template uppercases the last
    /// turn to `SAME`. Searching rendered text for `same` would cut at the
    /// first copy. The HuggingFace marker must keep the full conversation.
    #[test]
    fn continue_final_message_marker_survives_rewritten_final_turn() {
        const TEMPLATE: &str = "\
{%- for message in messages -%}\
{%- if loop.last -%}{{ message.content | upper }}|{%- else -%}{{ message.content }}|{%- endif -%}\
{%- endfor -%}closed";
        let formatter = test_prompt_formatter(TEMPLATE);
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "same"},
                {"role": "user", "content": "previous"},
                {"role": "assistant", "content": "same"}
            ],
            "add_generation_prompt": false,
            "continue_final_message": true
        }))
        .unwrap();

        let prompt = render_with_continue_final_message(formatter.as_ref(), &request);
        assert_eq!(prompt.as_str(), "same|previous|SAME");
        assert!(
            !prompt.as_str().contains("CONTINUE_FINAL_MESSAGE_TAG"),
            "marker must be stripped from the prompt sent to the model, got {:?}",
            prompt.as_str()
        );
    }

    #[test]
    fn test_kimi_thinking_normalization_keeps_template_and_gates_in_sync() {
        let template: dynamo_renderer::ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": "{% if thinking == true and enable_thinking == true %}<think>{% elif thinking == false and enable_thinking == false %}<chat>{% else %}<mismatch>{% endif %}"
        }))
        .unwrap();
        let formatter = dynamo_renderer::PromptFormatter::from_parts(
            template,
            dynamo_renderer::ContextMixins::default(),
            false,
        )
        .unwrap();
        let cases = [
            (serde_json::json!(true), true, "true"),
            (serde_json::json!("true"), true, "string true"),
            (serde_json::json!("TRUE"), true, "uppercase true"),
            (serde_json::json!("1"), true, "string one"),
            (serde_json::json!("yes"), true, "yes"),
            (serde_json::json!("on"), true, "on"),
            (serde_json::json!(1), true, "one"),
            (serde_json::json!(false), false, "false"),
            (serde_json::json!("false"), false, "string false"),
            (serde_json::json!("no"), false, "no"),
            (serde_json::json!("off"), false, "off"),
            (serde_json::json!(0), false, "zero"),
        ];

        let assert_case =
            |key: Option<&str>, value: Option<&serde_json::Value>, expected, description| {
                let mut request: NvCreateChatCompletionRequest =
                    serde_json::from_value(serde_json::json!({
                        "messages": [{"role": "user", "content": "hello"}],
                        "model": "moonshotai/Kimi-K2.5-Instruct"
                    }))
                    .unwrap();
                if let (Some(key), Some(value)) = (key, value) {
                    request.chat_template_args = Some(std::collections::HashMap::from([(
                        key.to_string(),
                        value.clone(),
                    )]));
                }

                OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("kimi_k25"), None);
                let args = request.chat_template_args.as_ref();
                assert_eq!(
                    dynamo_renderer::thinking_bool_from_args(args),
                    Some(expected),
                    "renderer helper mismatch for {description}"
                );
                assert_eq!(
                    OpenAIPreprocessor::sglang_effective_reasoning_enabled(Some("kimi_k25"), args),
                    expected,
                    "SGLang gate mismatch for {description}"
                );
                assert_eq!(
                    !OpenAIPreprocessor::is_reasoning_disabled_by_request(Some("kimi_k25"), args,),
                    expected,
                    "postprocessor gate mismatch for {description}"
                );

                let rendered = match &formatter {
                    dynamo_renderer::PromptFormatter::OAI(formatter) => {
                        formatter.render(&request).unwrap()
                    }
                };
                assert_eq!(
                    rendered,
                    if expected { "<think>" } else { "<chat>" },
                    "rendered prompt mismatch for {description}"
                );
            };

        for key in ["thinking", "enable_thinking"] {
            for (value, expected, description) in &cases {
                assert_case(Some(key), Some(value), *expected, *description);
            }
        }
        assert_case(None, None, true, "omitted Kimi default");

        for parser in ["kimi_k3", "kimi-k3"] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "messages": [{"role": "user", "content": "hello"}],
                    "model": "moonshotai/Kimi-K3"
                }))
                .unwrap();
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some(parser), None);
            assert_eq!(
                dynamo_renderer::thinking_bool_from_args(request.chat_template_args.as_ref()),
                Some(true),
                "{parser} should default to thinking mode",
            );
        }

        let mut conflicting_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "messages": [{"role": "user", "content": "hello"}],
                "model": "moonshotai/Kimi-K2.5-Instruct",
                "chat_template_kwargs": {
                    "thinking": "true",
                    "enable_thinking": false
                }
            }))
            .unwrap();
        OpenAIPreprocessor::normalize_thinking_arg(
            &mut conflicting_request,
            Some("kimi_k25"),
            None,
        );
        let args = conflicting_request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::Value::Bool(true)));
        assert_eq!(
            args.get("enable_thinking"),
            Some(&serde_json::Value::Bool(true))
        );
        let rendered = match &formatter {
            dynamo_renderer::PromptFormatter::OAI(formatter) => {
                formatter.render(&conflicting_request).unwrap()
            }
        };
        assert_eq!(rendered, "<think>");
    }

    #[test]
    fn test_named_kimi_k3_normalizes_every_reasoning_consumer_to_disabled() {
        for parser in ["kimi_k3", "kimi-k3"] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "messages": [{"role": "user", "content": "Weather in Berlin?"}],
                    "model": "moonshotai/Kimi-K3",
                    "tools": [{
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "parameters": {
                                "type": "object",
                                "properties": {"city": {"type": "string"}}
                            }
                        }
                    }],
                    "tool_choice": {
                        "type": "function",
                        "function": {"name": "get_weather"}
                    },
                    "reasoning_effort": "high",
                    "chat_template_args": {
                        "thinking": true,
                        "enable_thinking": true
                    }
                }))
                .unwrap();

            request.normalize_reasoning_template_args().unwrap();
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some(parser), None);
            OpenAIPreprocessor::normalize_kimi_k3_named_tool_choice(&mut request, Some(parser));

            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(args.get("thinking"), Some(&serde_json::Value::Bool(false)));
            assert_eq!(
                args.get("enable_thinking"),
                Some(&serde_json::Value::Bool(false))
            );
            assert_eq!(
                args.get("reasoning_effort"),
                Some(&serde_json::Value::String("high".to_string())),
                "the public effort value is preserved while the named-call exception disables thinking"
            );
            assert!(OpenAIPreprocessor::is_reasoning_disabled_by_request(
                Some(parser),
                Some(args)
            ));
        }
    }

    #[test]
    fn test_named_kimi_k3_override_is_scoped_to_k3_tool_parser() {
        let request_json = serde_json::json!({
            "messages": [{"role": "user", "content": "Weather?"}],
            "model": "test",
            "tools": [{
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "parameters": {"type": "object"}
                }
            }],
            "tool_choice": {
                "type": "function",
                "function": {"name": "get_weather"}
            },
            "chat_template_args": {"thinking": true}
        });

        for parser in [None, Some("hermes"), Some("kimi_k2")] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(request_json.clone()).unwrap();
            OpenAIPreprocessor::normalize_kimi_k3_named_tool_choice(&mut request, parser);
            assert_eq!(
                dynamo_renderer::thinking_bool_from_args(request.chat_template_args.as_ref()),
                Some(true),
                "parser {parser:?} must retain its existing policy"
            );
        }
    }

    fn minimax_m3_request(body: serde_json::Value) -> NvCreateChatCompletionRequest {
        let mut base = serde_json::json!({
            "model": "MiniMaxAI/MiniMax-M3",
            "messages": [{"role": "user", "content": "hi"}],
        });
        let base_obj = base.as_object_mut().unwrap();
        for (k, v) in body.as_object().unwrap() {
            base_obj.insert(k.clone(), v.clone());
        }
        serde_json::from_value(base).unwrap()
    }

    #[test]
    fn test_normalize_thinking_arg_m3_defaults_disabled_for_json_schema() {
        for parser in ["minimax_m3", "minimax-m3"] {
            let mut request = minimax_m3_request(serde_json::json!({
                "response_format": {
                    "type": "json_schema",
                    "json_schema": {"name": "s", "schema": {"type": "object"}}
                }
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some(parser), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("disabled"))
            );
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
        }
    }

    #[test]
    fn test_normalize_thinking_arg_m3_defaults_disabled_for_tool_choice_required() {
        let mut request = minimax_m3_request(serde_json::json!({
            "tools": [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}],
            "tool_choice": "required"
        }));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
    }

    #[test]
    fn test_normalize_thinking_arg_m3_defaults_disabled_for_named_tool_choice() {
        let mut request = minimax_m3_request(serde_json::json!({
            "tools": [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}],
            "tool_choice": {"type": "function", "function": {"name": "f"}}
        }));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
    }

    #[test]
    fn test_normalize_thinking_arg_m3_tool_call_only_deployment_gets_default() {
        // Tool-call-only M3 deployments still render the M3 template.
        // Guided-output requests therefore still need "adaptive" overridden.
        for tool_call_parser in [
            "minimax_m3",
            "minimax-m3",
            "minimax_m3_nom",
            "minimax-m3-nom",
        ] {
            let mut request = minimax_m3_request(serde_json::json!({
                "tools": [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}],
                "tool_choice": "required"
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, None, Some(tool_call_parser));
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("disabled")),
                "tool_call_parser={tool_call_parser:?} + tool_choice=required with no reasoning parser must still default thinking_mode=disabled"
            );
        }
    }

    #[test]
    fn test_normalize_thinking_arg_m3_preserves_client_adaptive() {
        let mut request = minimax_m3_request(serde_json::json!({
            "response_format": {
                "type": "json_schema",
                "json_schema": {"name": "s", "schema": {"type": "object"}}
            },
            "chat_template_kwargs": {"thinking_mode": "adaptive"}
        }));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("adaptive"))
        );
        assert!(!args.contains_key("thinking"));
        assert!(!args.contains_key("enable_thinking"));
    }

    #[test]
    fn test_normalize_thinking_arg_m3_bridges_thinking_bool_to_mode() {
        let mut request = minimax_m3_request(serde_json::json!({
            "chat_template_kwargs": {"thinking": true}
        }));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(true)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(true)));
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("enabled"))
        );
    }

    #[test]
    fn test_normalize_thinking_arg_m3_bridges_enable_thinking_to_mode() {
        let mut request = minimax_m3_request(serde_json::json!({
            "chat_template_kwargs": {"enable_thinking": false}
        }));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
    }

    #[test]
    fn test_normalize_thinking_arg_thinking_mode_enabled_is_thinking_on() {
        // `thinking_mode` strings must bypass `is_truthy`, which would map
        // "enabled" to false. M3 inputs are canonicalized to exact values.
        for value in ["enabled", "ENABLED", "Enabled"] {
            let mut request = minimax_m3_request(serde_json::json!({
                "chat_template_kwargs": {"thinking_mode": value}
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking"),
                Some(&serde_json::json!(true)),
                "thinking_mode={value:?} must map to thinking=true"
            );
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(true)));
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("enabled"))
            );
        }
    }

    #[test]
    fn test_normalize_thinking_arg_thinking_mode_disabled_is_thinking_off() {
        for value in ["disabled", "DISABLED"] {
            let mut request = minimax_m3_request(serde_json::json!({
                "chat_template_kwargs": {"thinking_mode": value}
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("disabled"))
            );
        }
    }

    #[test]
    fn test_normalize_thinking_arg_m3_canonicalizes_non_canonical_thinking_mode() {
        // M3 only treats exact "disabled" as off.
        // Canonicalize falsy aliases so `thinking=false` and the template gate agree.
        for value in [
            serde_json::json!(false),
            serde_json::json!(0),
            serde_json::json!("false"),
            serde_json::json!("no"),
            serde_json::json!("off"),
        ] {
            let mut request = minimax_m3_request(serde_json::json!({
                "chat_template_kwargs": {"thinking_mode": value.clone()}
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("disabled")),
                "input={value} must canonicalize to \"disabled\""
            );
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
        }

        // Truthy non-canonical values must canonicalize to "enabled".
        for value in [
            serde_json::json!(true),
            serde_json::json!(1),
            serde_json::json!("true"),
            serde_json::json!("yes"),
            serde_json::json!("on"),
        ] {
            let mut request = minimax_m3_request(serde_json::json!({
                "chat_template_kwargs": {"thinking_mode": value.clone()}
            }));
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!("enabled")),
                "input={value} must canonicalize to \"enabled\""
            );
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(true)));
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(true)));
        }
    }

    #[test]
    fn test_normalize_thinking_arg_deepseek_thinking_mode_words_preserved() {
        // DeepSeek V3.1 uses `thinking_mode` values "chat" and "thinking".
        // Preserve them verbatim without writing boolean aliases.
        for value in ["thinking", "chat"] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "model": "deepseek/DeepSeek-V3.1",
                    "messages": [{"role": "user", "content": "hi"}],
                    "chat_template_kwargs": {"thinking_mode": value}
                }))
                .unwrap();
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("deepseek_v3_1"), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode").and_then(|v| v.as_str()),
                Some(value),
                "DeepSeek {value:?} must survive verbatim"
            );
            assert!(
                !args.contains_key("thinking"),
                "no boolean coercion for DeepSeek {value:?}"
            );
            assert!(!args.contains_key("enable_thinking"));
        }
    }

    #[test]
    fn test_normalize_thinking_arg_thinking_mode_not_written_for_non_m3_parsers() {
        // Only M3-family templates use the "enabled"/"disabled" vocabulary.
        // Other parsers may treat an injected value as out-of-vocabulary.
        for parser in [
            "deepseek_v3_1",
            "deepseek_v3_2",
            "minimax_m2",
            "qwen3",
            "kimi_k25",
            "kimi_k3",
        ] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "model": "test",
                    "messages": [{"role": "user", "content": "hi"}],
                    "chat_template_kwargs": {"thinking": true}
                }))
                .unwrap();
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some(parser), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(true)));
            assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(true)));
            assert!(
                !args.contains_key("thinking_mode"),
                "parser {parser:?} must not receive an injected thinking_mode value"
            );
        }
    }

    #[test]
    fn test_normalize_thinking_arg_kimi_or_else_does_not_write_thinking_mode() {
        // Kimi parsers synthesize `Some(true)` with no client input.
        // Write boolean aliases only; Kimi does not read `thinking_mode`.
        for parser in ["kimi_k25", "kimi_k3", "kimi-k3"] {
            let mut request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "model": "test",
                    "messages": [{"role": "user", "content": "hi"}]
                }))
                .unwrap();
            OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some(parser), None);
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(args.get("thinking"), Some(&serde_json::json!(true)));
            assert!(!args.contains_key("thinking_mode"));
        }
    }

    #[test]
    fn test_normalize_thinking_arg_m3_leaves_plain_chat_untouched() {
        let mut request = minimax_m3_request(serde_json::json!({}));
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("minimax_m3"), None);
        assert!(request.chat_template_args.is_none());
    }

    #[test]
    fn test_normalize_thinking_arg_non_m3_adaptive_is_no_op() {
        // Preserve non-M3 `thinking_mode: "adaptive"` verbatim by leaving
        // normalization as `None`.
        let mut request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "test",
                "messages": [{"role": "user", "content": "hi"}],
                "chat_template_kwargs": {"thinking_mode": "adaptive"}
            }))
            .unwrap();
        OpenAIPreprocessor::normalize_thinking_arg(&mut request, Some("qwen3"), None);
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("adaptive"))
        );
        assert!(!args.contains_key("thinking"));
        assert!(!args.contains_key("enable_thinking"));
    }

    #[test]
    fn test_normalize_thinking_arg_operator_default_forces_m3_constrained_disabled() {
        // Runtime defaults are operator policy, not client intent. When the
        // client sends no thinking control, constrained M3 requests force
        // "disabled" even if the operator default is "enabled" — otherwise
        // the deployment default silently propagates a mode M3 cannot honor
        // with a constrained decoder attached.
        let runtime_config = runtime_config_with_default_thinking_mode("enabled");
        let mut request = minimax_m3_request(serde_json::json!({
            "response_format": {
                "type": "json_schema",
                "json_schema": {"name": "s", "schema": {"type": "object"}}
            }
        }));
        let thinking_control_from_client =
            OpenAIPreprocessor::request_has_client_thinking_control(&request);
        assert!(
            !thinking_control_from_client,
            "no chat_template_kwargs → not client intent"
        );
        OpenAIPreprocessor::apply_default_thinking_mode_from_runtime_config(
            &runtime_config,
            &mut request,
        );
        OpenAIPreprocessor::normalize_thinking_arg_with_source(
            &mut request,
            Some("minimax_m3"),
            None,
            thinking_control_from_client,
        );
        let args = request.chat_template_args.as_ref().unwrap();
        assert_eq!(
            args.get("thinking_mode"),
            Some(&serde_json::json!("disabled"))
        );
        assert_eq!(args.get("thinking"), Some(&serde_json::json!(false)));
        assert_eq!(args.get("enable_thinking"), Some(&serde_json::json!(false)));
    }

    #[test]
    fn test_normalize_thinking_arg_m3_preserves_explicit_thinking_for_constrained() {
        // Explicit client thinking intent is respected for constrained M3
        // requests. The runtime attempts the combination even though the
        // template's adaptive/enabled path is known to conflict with the
        // constrained decoder — this is the client's opt-in, and returning
        // possibly-degraded content is preferred to a hard reject at the
        // API boundary (which would break provider-compatibility probes
        // that expect the request to be attempted).
        for (body, expected_mode, desc) in [
            (
                serde_json::json!({
                    "response_format": {
                        "type": "json_schema",
                        "json_schema": {"name": "s", "schema": {"type": "object"}}
                    },
                    "chat_template_kwargs": {"thinking_mode": "enabled"}
                }),
                "enabled",
                "json_schema + explicit thinking_mode=enabled",
            ),
            (
                serde_json::json!({
                    "tools": [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}],
                    "tool_choice": "required",
                    "chat_template_kwargs": {"thinking_mode": "adaptive"}
                }),
                "adaptive",
                "required tool + explicit thinking_mode=adaptive",
            ),
            (
                serde_json::json!({
                    "tools": [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}],
                    "tool_choice": {"type": "function", "function": {"name": "f"}},
                    "chat_template_kwargs": {"thinking": true}
                }),
                "enabled",
                "named tool + explicit thinking=true",
            ),
        ] {
            let mut request = minimax_m3_request(body);
            let thinking_control_from_client =
                OpenAIPreprocessor::request_has_client_thinking_control(&request);
            assert!(
                thinking_control_from_client,
                "{desc} must be classified as client thinking intent"
            );
            OpenAIPreprocessor::normalize_thinking_arg_with_source(
                &mut request,
                Some("minimax_m3"),
                None,
                thinking_control_from_client,
            );
            let args = request.chat_template_args.as_ref().unwrap();
            assert_eq!(
                args.get("thinking_mode"),
                Some(&serde_json::json!(expected_mode)),
                "{desc} must preserve explicit client thinking"
            );
        }
    }

    /// PRE.2 — Per-request reasoning gate. See `lib/llm/PREPROCESSOR_CASES.md`.
    #[test]
    fn test_is_reasoning_disabled_by_request() {
        let thinking_true = {
            let mut m = std::collections::HashMap::new();
            m.insert("thinking".to_string(), serde_json::Value::Bool(true));
            m
        };
        let thinking_false = {
            let mut m = std::collections::HashMap::new();
            m.insert("thinking".to_string(), serde_json::Value::Bool(false));
            m
        };
        let enable_thinking_true = {
            let mut m = std::collections::HashMap::new();
            m.insert("enable_thinking".to_string(), serde_json::Value::Bool(true));
            m
        };
        let enable_thinking_false = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "enable_thinking".to_string(),
                serde_json::Value::Bool(false),
            );
            m
        };
        let force_nonempty_content_true = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "force_nonempty_content".to_string(),
                serde_json::Value::Bool(true),
            );
            m
        };
        let thinking_mode_chat = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "thinking_mode".to_string(),
                serde_json::Value::String("chat".to_string()),
            );
            m
        };
        let thinking_mode_thinking = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "thinking_mode".to_string(),
                serde_json::Value::String("thinking".to_string()),
            );
            m
        };
        let thinking_mode_disabled = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "thinking_mode".to_string(),
                serde_json::Value::String("disabled".to_string()),
            );
            m
        };
        let reasoning_effort_none = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "reasoning_effort".to_string(),
                serde_json::Value::String("none".to_string()),
            );
            m
        };
        let reasoning_effort_high = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                "reasoning_effort".to_string(),
                serde_json::Value::String("high".to_string()),
            );
            m
        };
        let empty_args = std::collections::HashMap::new();

        // (parser, args, expected_disabled, description)
        let cases = [
            (
                Some("kimi_k25"),
                Some(&thinking_false),
                true,
                "kimi_k25 + thinking=false → disabled",
            ),
            (
                Some("kimi_k25"),
                Some(&thinking_true),
                false,
                "kimi_k25 + thinking=true → enabled",
            ),
            (
                Some("kimi_k25"),
                None,
                false,
                "kimi_k25 + no args → enabled",
            ),
            (
                Some("kimi_k25"),
                Some(&empty_args),
                false,
                "kimi_k25 + empty args → enabled",
            ),
            (
                Some("kimi_k3"),
                Some(&thinking_false),
                true,
                "kimi_k3 + thinking=false → disabled",
            ),
            (
                Some("kimi-k3"),
                Some(&thinking_true),
                false,
                "kimi-k3 + thinking=true → enabled",
            ),
            // deepseek_r1 uses "thinking" bool or "thinking_mode" string
            (
                Some("deepseek_r1"),
                Some(&thinking_false),
                true,
                "deepseek_r1 + thinking=false → disabled",
            ),
            (
                Some("deepseek_r1"),
                Some(&thinking_true),
                false,
                "deepseek_r1 + thinking=true → enabled",
            ),
            (
                Some("deepseek_r1"),
                Some(&thinking_mode_chat),
                true,
                "deepseek_r1 + thinking_mode=chat → disabled",
            ),
            (
                Some("deepseek_r1"),
                Some(&thinking_mode_thinking),
                false,
                "deepseek_r1 + thinking_mode=thinking → enabled",
            ),
            (
                Some("deepseek_r1"),
                None,
                false,
                "deepseek_r1 + no args → enabled",
            ),
            (
                Some("deepseek_r1"),
                Some(&empty_args),
                false,
                "deepseek_r1 + empty args → enabled",
            ),
            (
                Some("deepseek_v3"),
                None,
                true,
                "deepseek_v3 + no args → disabled",
            ),
            (
                Some("deepseek_v3"),
                Some(&thinking_true),
                false,
                "deepseek_v3 + thinking=true → enabled",
            ),
            (
                Some("deepseek_v3_1"),
                Some(&enable_thinking_true),
                false,
                "deepseek_v3_1 + enable_thinking=true → enabled",
            ),
            (
                Some("deepseek_v3_2"),
                None,
                false,
                "deepseek_v3_2 + no args → enabled",
            ),
            (
                Some("deepseek_v3_2"),
                Some(&thinking_false),
                true,
                "deepseek_v3_2 + thinking=false → disabled",
            ),
            (
                Some("minimax_m2"),
                Some(&thinking_false),
                true,
                "minimax_m2 + thinking=false → disabled",
            ),
            (
                Some("minimax_m2"),
                Some(&thinking_true),
                false,
                "minimax_m2 + thinking=true → enabled",
            ),
            (
                Some("minimax_m2"),
                None,
                false,
                "minimax_m2 + no args → enabled",
            ),
            (
                Some("basic"),
                Some(&thinking_false),
                false,
                "basic → never disabled",
            ),
            (
                None,
                Some(&thinking_false),
                false,
                "no parser → never disabled",
            ),
            // nemotron_nano uses "enable_thinking" key
            (
                Some("nemotron_nano"),
                Some(&enable_thinking_false),
                true,
                "nemotron_nano + enable_thinking=false → disabled",
            ),
            (
                Some("nemotron_nano"),
                Some(&enable_thinking_true),
                false,
                "nemotron_nano + enable_thinking=true → enabled",
            ),
            (
                Some("nemotron_nano"),
                None,
                false,
                "nemotron_nano + no args → enabled",
            ),
            (
                Some("nemotron_nano"),
                Some(&empty_args),
                false,
                "nemotron_nano + empty args → enabled",
            ),
            (
                Some("nemotron3"),
                Some(&force_nonempty_content_true),
                false,
                "nemotron3 + force_nonempty_content=true → NOT disabled (parser stays on)",
            ),
            (
                Some("nemotron_v3"),
                Some(&enable_thinking_false),
                true,
                "nemotron_v3 + enable_thinking=false → disabled",
            ),
            (
                Some("nemotron_v3"),
                Some(&force_nonempty_content_true),
                false,
                "nemotron_v3 + force_nonempty_content=true → NOT disabled (parser stays on)",
            ),
            // deepseek_v4 — same convention as deepseek_r1; verify all three aliases
            // (deepseek_v4 / deepseek-v4 / deepseekv4) plus both signal keys.
            (
                Some("deepseek_v4"),
                Some(&thinking_false),
                true,
                "deepseek_v4 + thinking=false → disabled",
            ),
            (
                Some("deepseek_v4"),
                Some(&thinking_true),
                false,
                "deepseek_v4 + thinking=true → enabled",
            ),
            (
                Some("deepseek_v4"),
                Some(&thinking_mode_chat),
                true,
                "deepseek_v4 + thinking_mode=chat → disabled",
            ),
            (
                Some("deepseek_v4"),
                Some(&thinking_mode_thinking),
                false,
                "deepseek_v4 + thinking_mode=thinking → enabled",
            ),
            (
                Some("deepseek_v4"),
                None,
                false,
                "deepseek_v4 + no args → enabled",
            ),
            (
                Some("deepseek-v4"),
                Some(&thinking_false),
                true,
                "deepseek-v4 (hyphen alias) + thinking=false → disabled",
            ),
            (
                Some("deepseekv4"),
                Some(&thinking_mode_chat),
                true,
                "deepseekv4 (joined alias) + thinking_mode=chat → disabled",
            ),
            (
                Some("deepseek_v4"),
                Some(&enable_thinking_false),
                true,
                "deepseek_v4 + enable_thinking=false → disabled (vLLM alias)",
            ),
            (
                Some("deepseek_v4"),
                Some(&enable_thinking_true),
                false,
                "deepseek_v4 + enable_thinking=true → enabled (vLLM alias)",
            ),
            (
                Some("gemma4"),
                Some(&enable_thinking_false),
                true,
                "gemma4 + enable_thinking=false → disabled",
            ),
            (
                Some("gemma4"),
                Some(&enable_thinking_true),
                false,
                "gemma4 + enable_thinking=true → enabled",
            ),
            (
                Some("gemma4"),
                None,
                true,
                "gemma4 + no args → disabled (reasoning is opt-in)",
            ),
            (
                Some("gemma-4"),
                Some(&enable_thinking_false),
                true,
                "gemma-4 (hyphen alias) + enable_thinking=false → disabled",
            ),
            (
                Some("gemma-4"),
                None,
                true,
                "gemma-4 (hyphen alias) + no args → disabled (reasoning is opt-in)",
            ),
            (Some("mistral"), None, true, "mistral + no args → disabled"),
            (
                Some("mistral"),
                Some(&reasoning_effort_none),
                true,
                "mistral + reasoning_effort=none → disabled",
            ),
            (
                Some("mistral"),
                Some(&reasoning_effort_high),
                false,
                "mistral + reasoning_effort=high → enabled",
            ),
            (
                Some("minimax_m3"),
                Some(&thinking_mode_disabled),
                true,
                "minimax_m3 + thinking_mode=disabled → disabled",
            ),
            (
                Some("minimax-m3"),
                Some(&thinking_mode_disabled),
                true,
                "minimax-m3 + thinking_mode=disabled → disabled",
            ),
            (
                Some("minimax_m3"),
                Some(&thinking_mode_thinking),
                false,
                "minimax_m3 + thinking_mode=thinking → enabled",
            ),
            (
                Some("minimax_m3"),
                None,
                false,
                "minimax_m3 + no args → enabled",
            ),
        ];

        // The disable decision no longer depends on streaming — `enable_thinking`
        // and the per-family signals decide it identically for both paths.
        for (parser, args, expected, desc) in cases {
            assert_eq!(
                OpenAIPreprocessor::is_reasoning_disabled_by_request(parser, args),
                expected,
                "FAILED: {desc}",
            );
        }

        // force_nonempty_content=true does NOT disable reasoning parsing for
        // either path: the parser stays on so reasoning is split from the answer
        // (no leak). Non-streaming additionally moves reasoning into content when
        // no content was generated (the aggregator); streaming skips that move.
        assert!(
            !OpenAIPreprocessor::is_reasoning_disabled_by_request(
                Some("nemotron3"),
                Some(&force_nonempty_content_true),
            ),
            "nemotron3 + force_nonempty_content=true → NOT disabled",
        );
        assert!(
            !OpenAIPreprocessor::is_reasoning_disabled_by_request(
                Some("nemotron_v3"),
                Some(&force_nonempty_content_true),
            ),
            "nemotron_v3 + force_nonempty_content=true → NOT disabled",
        );
        // enable_thinking=false disables entirely (user turned thinking off).
        assert!(
            OpenAIPreprocessor::is_reasoning_disabled_by_request(
                Some("nemotron3"),
                Some(&enable_thinking_false),
            ),
            "nemotron3 + enable_thinking=false → disabled",
        );

        // The force_nonempty_content=true → NOT disabled behavior is what lets a
        // reasoning-only non-streaming turn surface reasoning as content; verify
        // the aggregator half in test_move_reasoning_to_content_when_empty.
    }

    #[test]
    fn muse_force_nonempty_stream_reports_that_it_can_defer_all_output() {
        let mut args = std::collections::HashMap::new();
        args.insert(
            "force_nonempty_content".to_string(),
            serde_json::Value::Bool(true),
        );

        assert!(OpenAIPreprocessor::stream_can_defer_all_output(
            None,
            Some("muse_glimmer"),
            Some(&args),
        ));
    }

    /// Different query strings must produce different hashes. `?v=1` and
    /// `?v=2` may look like cache-busters, but they could equally be a
    /// content selector ("version 2 of the image"). The URL alone doesn't
    /// tell us which, so we keep the hash URL-identical and let the URL be
    /// the identity. For signed-URL workloads where rotation actually
    /// hides a stable object, `--frontend-decoding` hashes the decoded
    /// bytes instead.
    #[cfg(feature = "mm-routing")]
    #[test]
    fn hash_image_url_distinguishes_query_strings() {
        let base = "https://cdn.example.com/img.jpg";
        let v1 = OpenAIPreprocessor::hash_image_url(&format!("{base}?v=1"));
        let v2 = OpenAIPreprocessor::hash_image_url(&format!("{base}?v=2"));
        let no_q = OpenAIPreprocessor::hash_image_url(base);
        assert_ne!(v1, v2, "different query values must hash differently");
        assert_ne!(v1, no_q, "presence of a query string must change the hash");
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn image_dim_cache_preserves_terminal_policy_classification() {
        let terminal = ImageDimFetchFailure::from_error(invalid_argument_error(
            "media destination rejected by SSRF policy",
        ));
        let terminal = terminal.to_error();
        assert!(MediaFetcher::is_policy_rejection(&terminal));

        let recoverable =
            ImageDimFetchFailure::from_error(anyhow::anyhow!("image header was truncated"));
        let recoverable = recoverable.to_error();
        assert!(!MediaFetcher::is_policy_rejection(&recoverable));
    }

    /// A blocked destination on the URL-passthrough path must fail the whole
    /// request. The IP literal is refused before DNS, so no socket is opened.
    #[cfg(feature = "mm-routing")]
    #[tokio::test]
    async fn url_passthrough_policy_rejection_is_terminal() {
        // The probe's fetcher is built from the environment. The opt-in allows
        // this destination, so there would be nothing to assert.
        if std::env::var("DYN_MM_ALLOW_INTERNAL").as_deref() == Ok("1") {
            return;
        }

        let mdc = ModelDeploymentCard::load_from_disk(
            "tests/data/sample-models/mock-llama-3.1-8b-instruct",
            None,
        )
        .unwrap();
        let preprocessor = OpenAIPreprocessor::new(mdc).unwrap();
        assert!(preprocessor.media_loader.is_none());

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [{
                "role": "user",
                "content": [{
                    "type": "image_url",
                    "image_url": {
                        "url": "https://169.254.169.254/latest/meta-data/private-image.png"
                    }
                }]
            }]
        }))
        .unwrap();
        let mut builder = PreprocessedRequest::builder();

        let error = preprocessor
            .gather_multi_modal_data(&request, &mut builder, None, &[])
            .await
            .expect_err("URL-passthrough must stop at the policy rejection");

        assert!(MediaFetcher::is_policy_rejection(&error));
    }

    /// Object-store and file URLs are backend-owned passthrough schemes, so a
    /// failed dimension probe must remain recoverable rather than become 4xx.
    #[cfg(feature = "mm-routing")]
    #[tokio::test]
    async fn dim_fetch_declines_passthrough_schemes_without_rejecting_them() {
        for url in [
            "s3://bucket/private-image.png",
            "gs://bucket/private-image.png",
            "file:///tmp/private-image.png",
        ] {
            let error = OpenAIPreprocessor::fetch_image_dims_uncached(
                url,
                RoutingImageDimensionPolicy::Encoded,
            )
            .await
            .expect_err("a non-fetchable scheme cannot yield dimensions");
            assert!(
                !MediaFetcher::is_policy_rejection(&error),
                "{url} must be a skippable dim-fetch failure, not a terminal 4xx: {error:#}"
            );
        }
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn exif_dimension_policy_is_limited_to_kimi_k3_vllm_url_passthrough() {
        use crate::local_model::runtime_config::{
            ModelRuntimeConfig, SGLANG_GENERATE_CAPABILITY, VLLM_INFERENCE_V1_GENERATE_CAPABILITY,
        };

        let kimi_k3 = Some(RoutingImagePromptLayout::KimiK3 {
            media_begin: 1,
            media_content: 2,
            media_end: 3,
        });
        let mut runtime_config = ModelRuntimeConfig::default();
        assert_eq!(
            routing_image_dimension_policy(&runtime_config, false, kimi_k3),
            RoutingImageDimensionPolicy::Encoded
        );

        let mut sglang_config = ModelRuntimeConfig::default();
        sglang_config
            .set_engine_specific(SGLANG_GENERATE_CAPABILITY, true)
            .unwrap();
        assert_eq!(
            routing_image_dimension_policy(&sglang_config, false, kimi_k3),
            RoutingImageDimensionPolicy::Encoded
        );

        runtime_config
            .set_engine_specific(VLLM_INFERENCE_V1_GENERATE_CAPABILITY, true)
            .unwrap();
        assert_eq!(
            routing_image_dimension_policy(&runtime_config, false, kimi_k3),
            RoutingImageDimensionPolicy::ExifTransposed
        );
        assert_eq!(
            routing_image_dimension_policy(&runtime_config, true, kimi_k3),
            RoutingImageDimensionPolicy::Encoded
        );
        assert_eq!(
            routing_image_dimension_policy(
                &runtime_config,
                false,
                Some(RoutingImagePromptLayout::RepeatedPad),
            ),
            RoutingImageDimensionPolicy::Encoded
        );
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn exif_transposed_dimensions_match_vllm_image_loading() {
        use image::{ExtendedColorType, ImageEncoder, codecs::jpeg::JpegEncoder};

        // Little-endian TIFF with one orientation entry set to 6 (rotate 90°).
        let exif = vec![
            b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0,
            0,
        ];
        let mut jpeg = Vec::new();
        let mut encoder = JpegEncoder::new(&mut jpeg);
        encoder.set_exif_metadata(exif).unwrap();
        encoder
            .encode(&[255, 0, 0, 0, 255, 0], 2, 1, ExtendedColorType::Rgb8)
            .unwrap();

        assert_eq!(
            OpenAIPreprocessor::dimensions_from_image_bytes(
                &jpeg,
                RoutingImageDimensionPolicy::Encoded,
            )
            .unwrap(),
            (2, 1)
        );
        assert_eq!(
            OpenAIPreprocessor::dimensions_from_image_bytes(
                &jpeg,
                RoutingImageDimensionPolicy::ExifTransposed,
            )
            .unwrap(),
            (1, 2)
        );
    }

    /// Rotating S3 / GCS / Azure SAS signatures change the URL and
    /// therefore the hash. This is a known limitation of URL-passthrough
    /// routing for signed-URL workloads — `--frontend-decoding` is the
    /// recommended mode there because it hashes the decoded image bytes
    /// regardless of how the URL was signed.
    #[cfg(feature = "mm-routing")]
    #[test]
    fn hash_image_url_distinguishes_rotating_signatures() {
        let base = "https://bucket.s3.amazonaws.com/img.jpg";
        let a = OpenAIPreprocessor::hash_image_url(&format!(
            "{base}?X-Amz-Signature=AAA&X-Amz-Date=20260101T000000Z&X-Amz-Expires=600"
        ));
        let b = OpenAIPreprocessor::hash_image_url(&format!(
            "{base}?X-Amz-Signature=BBB&X-Amz-Date=20260101T010000Z&X-Amz-Expires=900"
        ));
        assert_ne!(
            a, b,
            "rotating presign params produce a different URL and must hash differently"
        );
    }

    /// Identical URLs must hash to the same value (the basic identity
    /// guarantee that makes URL-passthrough routing useful at all).
    #[cfg(feature = "mm-routing")]
    #[test]
    fn hash_image_url_is_deterministic_for_identical_urls() {
        let url = "https://cdn.example.com/img.jpg?width=256";
        assert_eq!(
            OpenAIPreprocessor::hash_image_url(url),
            OpenAIPreprocessor::hash_image_url(url),
        );
    }

    /// data: URIs hash the entire URI string. Same payload → same hash;
    /// different payload → different hash.
    #[cfg(feature = "mm-routing")]
    #[test]
    fn hash_image_url_data_uri_content_addressed() {
        let same = "data:image/png;base64,AAAA";
        let other = "data:image/png;base64,BBBB";
        assert_eq!(
            OpenAIPreprocessor::hash_image_url(same),
            OpenAIPreprocessor::hash_image_url(same)
        );
        assert_ne!(
            OpenAIPreprocessor::hash_image_url(same),
            OpenAIPreprocessor::hash_image_url(other),
            "different data URI payloads must hash differently"
        );
    }

    /// Non-HTTP / non-data schemes (s3://, gs://, file://) hash as-is.
    #[cfg(feature = "mm-routing")]
    #[test]
    fn hash_image_url_other_schemes_passthrough() {
        let s3a = OpenAIPreprocessor::hash_image_url("s3://bucket/key?v=1");
        let s3b = OpenAIPreprocessor::hash_image_url("s3://bucket/key?v=2");
        assert_ne!(
            s3a, s3b,
            "s3:// query params identify objects and must not collide"
        );
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn tracked_video_boundary_uses_native_metadata_only_when_needed() {
        use dynamo_kv_router::protocols::pad_value_for_mm_hash;

        let video_token_id = 100;
        let mm_hash = 41;
        let video_pad = pad_value_for_mm_hash(mm_hash);
        let replacement = TrackedMmRoutingReplacement {
            mm_hash,
            target_tokens: vec![9],
            worker_tokens: vec![3, 4, 5, 6, video_token_id, video_token_id],
            routing_tokens: vec![3, 4, 5, 6, video_pad, video_pad],
        };

        let (tokens, prompt_len, infos) = apply_tracked_mm_replacements(
            None,
            &[replacement],
            &[1, 9, 2],
            4,
            Some(99),
            Some(video_token_id),
        )
        .unwrap();

        assert_eq!(prompt_len, 8);
        assert_eq!(&tokens[..4], &[1, 3, 4, 5]);
        assert_eq!(&tokens[4..], &[6, video_pad, video_pad, 2]);
        assert_eq!(infos[0].as_ref().unwrap().mm_objects[0].mm_hash, mm_hash);
        assert!(infos[1].is_none());
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn tracked_mixed_boundary_preserves_worker_hash_fallback() {
        use dynamo_kv_router::protocols::pad_value_for_mm_hash;

        let image_token_id = 99;
        let video_token_id = 100;
        let image_hash = 41;
        let video_hash = 42;
        let replacements = [
            TrackedMmRoutingReplacement {
                mm_hash: image_hash,
                target_tokens: vec![image_token_id],
                worker_tokens: vec![image_token_id, image_token_id, 7],
                routing_tokens: vec![
                    pad_value_for_mm_hash(image_hash),
                    pad_value_for_mm_hash(image_hash),
                    7,
                ],
            },
            TrackedMmRoutingReplacement {
                mm_hash: video_hash,
                target_tokens: vec![video_token_id],
                worker_tokens: vec![8, video_token_id, video_token_id, 9],
                routing_tokens: vec![
                    8,
                    pad_value_for_mm_hash(video_hash),
                    pad_value_for_mm_hash(video_hash),
                    9,
                ],
            },
        ];

        let (tokens, prompt_len, infos) = apply_tracked_mm_replacements(
            None,
            &replacements,
            &[image_token_id, video_token_id],
            4,
            Some(image_token_id),
            Some(video_token_id),
        )
        .unwrap();

        assert_eq!(prompt_len, 7);
        assert_eq!(&tokens[..4], &[image_token_id, image_token_id, 7, 8]);
        assert_eq!(
            &tokens[4..],
            &[
                pad_value_for_mm_hash(video_hash),
                pad_value_for_mm_hash(video_hash),
                9,
                0
            ]
        );
        assert_eq!(
            infos[0]
                .as_ref()
                .unwrap()
                .mm_objects
                .iter()
                .map(|object| object.mm_hash)
                .collect::<Vec<_>>(),
            [image_hash, video_hash]
        );
        assert!(infos[1].is_none());
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn tracked_replacements_preserve_image_video_image_order() {
        use dynamo_kv_router::protocols::pad_value_for_mm_hash;

        let image_token_id = 99;
        let video_token_id = 100;
        let replacement = |mm_hash, target_token| TrackedMmRoutingReplacement {
            mm_hash,
            target_tokens: vec![target_token],
            worker_tokens: vec![target_token, target_token],
            routing_tokens: vec![
                pad_value_for_mm_hash(mm_hash),
                pad_value_for_mm_hash(mm_hash),
            ],
        };
        let replacements = [
            replacement(41, image_token_id),
            replacement(42, video_token_id),
            replacement(43, image_token_id),
        ];

        let (tokens, prompt_len, infos) = apply_tracked_mm_replacements(
            None,
            &replacements,
            &[1, image_token_id, 2, video_token_id, 3, image_token_id, 4],
            16,
            Some(image_token_id),
            Some(video_token_id),
        )
        .unwrap();

        assert_eq!(prompt_len, 10);
        assert_eq!(
            &tokens[..prompt_len],
            &[
                1,
                pad_value_for_mm_hash(41),
                pad_value_for_mm_hash(41),
                2,
                pad_value_for_mm_hash(42),
                pad_value_for_mm_hash(42),
                3,
                pad_value_for_mm_hash(43),
                pad_value_for_mm_hash(43),
                4,
            ]
        );
        assert!(infos[0].is_none());
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn tracked_replacements_reject_misordered_missing_and_extra_targets() {
        let replacement = |mm_hash, target| TrackedMmRoutingReplacement {
            mm_hash,
            target_tokens: vec![target],
            worker_tokens: vec![target],
            routing_tokens: vec![target],
        };
        let replacements = [replacement(41, 10), replacement(42, 20)];

        for token_ids in [&[20, 10][..], &[10][..], &[10, 20, 20][..]] {
            assert!(
                apply_tracked_mm_replacements(
                    None,
                    &replacements,
                    token_ids,
                    4,
                    Some(10),
                    Some(20),
                )
                .is_err(),
                "invalid target sequence {token_ids:?} must fail closed"
            );
        }
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn routing_bos_preserves_image_behavior_and_skips_video_only_requests() {
        assert_eq!(routing_bos_to_prepend(Some(1), true), Some(1));
        assert_eq!(routing_bos_to_prepend(None, true), None);
        assert_eq!(routing_bos_to_prepend(Some(1), false), None);
    }

    #[cfg(feature = "mm-routing")]
    #[test]
    fn consecutive_video_entries_are_not_exactly_routable() {
        let video = |mm_hash| MmRoutingEntry::Video {
            mm_hash,
            placeholder_token_id: 3,
            target_tokens: vec![3],
            replacement_tokens: vec![3],
        };
        let image = MmRoutingEntry::Image {
            mm_hash: 2,
            width: 1,
            height: 1,
        };

        assert!(exact_mm_routing_entries_are_unambiguous(&[video(1)]));
        assert!(!exact_mm_routing_entries_are_unambiguous(&[
            video(1),
            video(2)
        ]));
        assert!(exact_mm_routing_entries_are_unambiguous(&[
            video(1),
            image,
            video(2)
        ]));
    }
}