switchyard-server 0.3.0

Rust HTTP server surface for libsy algorithms
Documentation
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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Integration tests for the libsy Rust server.

use std::collections::{BTreeMap, HashSet};
use std::convert::Infallible;
use std::error::Error;
use std::io::Write;
use std::sync::Arc;

use axum::body::{Body, Bytes};
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{HeaderMap, HeaderValue, Request as HttpRequest, StatusCode, Uri};
use axum::response::sse::{Event, Sse};
use axum::response::{IntoResponse, Response as HttpResponse};
use axum::routing::post;
use axum::{Json, Router};
use http_body_util::BodyExt;
use libsy::{Algorithm, Random};
use serde_json::{Value, json};
use switchyard_llm_client::{
    Backend, ClientRouter, HttpBackendConfig, ModelConfig, TranslatingLlmClient,
};
use switchyard_protocol::RoutedLlmClient;
use switchyard_protocol::{Category, ModelId, WireFormat};
use switchyard_runner::{DecisionTarget, ModelCapabilities, Route, Runner, RuntimeModels};
use switchyard_server::config::load_server_state;
use switchyard_server::{
    DEFAULT_MAX_REQUEST_BODY_BYTES, ServerState, build_llm_router, build_switchyard_router,
};
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
use tower::ServiceExt;

type TestError = Box<dyn Error + Send + Sync>;
type TestResult<T = ()> = Result<T, TestError>;

const ROUTE_MODEL: &str = "switchyard/random";
const VERSION: &str = env!("CARGO_PKG_VERSION");

struct MockUpstream {
    base_url: String,
    calls: Arc<Mutex<Vec<Value>>>,
    task: JoinHandle<()>,
}

impl MockUpstream {
    async fn start() -> TestResult<Self> {
        let calls = Arc::new(Mutex::new(Vec::new()));
        let app = Router::new()
            .route("/v1/chat/completions", post(upstream_chat))
            .route("/buffered/responses", post(upstream_buffered_responses))
            .route(
                "/v1/messages",
                post(upstream_messages_requires_forwarded_oauth),
            )
            .route(
                "/v1/responses",
                post(upstream_responses_requires_forwarded_auth),
            )
            .route("/silo/{silo}/responses", post(upstream_responses_silo))
            .route("/capture", post(upstream_redirect_capture))
            .route("/v1/messages/count_tokens", post(upstream_count_tokens))
            .route(
                "/v1/responses/input_tokens",
                post(upstream_responses_auxiliary),
            )
            .route("/v1/responses/compact", post(upstream_responses_auxiliary))
            .route("/future/provider/endpoint", post(upstream_fallback))
            .layer(DefaultBodyLimit::disable())
            .with_state(Arc::clone(&calls));
        let listener = TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        let task = tokio::spawn(async move {
            if let Err(error) = axum::serve(listener, app).await {
                tracing::error!(error = %error, "mock upstream stopped");
            }
        });
        Ok(Self {
            base_url: format!("http://{addr}/v1"),
            calls,
            task,
        })
    }

    /// The upstream model id of every request this upstream received, in order.
    async fn models(&self) -> Vec<String> {
        self.calls
            .lock()
            .await
            .iter()
            .filter_map(|call| call.get("model")?.as_str().map(str::to_string))
            .collect()
    }
}

impl Drop for MockUpstream {
    fn drop(&mut self) {
        self.task.abort();
    }
}

fn user_prompt(body: &Value) -> &str {
    body["messages"]
        .as_array()
        .and_then(|messages| messages.iter().find(|message| message["role"] == "user"))
        .and_then(|message| message["content"].as_str())
        .unwrap_or_default()
}

fn has_system_prompt(call: &Value, expected: &str) -> bool {
    call["messages"].as_array().is_some_and(|messages| {
        messages.iter().any(|message| {
            message["role"] == "system" && message["content"].as_str() == Some(expected)
        })
    })
}

async fn upstream_chat(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(body.clone());
    let prompt = user_prompt(&body);
    if prompt == "fail" {
        return (
            StatusCode::IM_A_TEAPOT,
            Json(json!({"error": {"message": "upstream rejected request"}})),
        )
            .into_response();
    }
    if prompt == "auth-fail" {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": {"message": "upstream authentication failed"}})),
        )
            .into_response();
    }

    let model = body["model"].as_str().unwrap_or("unknown").to_string();
    if model == "model/classifier" {
        let mut pending = HashSet::new();
        for message in body["messages"].as_array().into_iter().flatten() {
            for call in message["tool_calls"].as_array().into_iter().flatten() {
                if let Some(id) = call["id"].as_str() {
                    pending.insert(id);
                }
            }
            if message["role"] == "tool"
                && !pending.remove(message["tool_call_id"].as_str().unwrap_or_default())
            {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": {
                        "message": "tool result has no preceding assistant tool call"
                    }})),
                )
                    .into_response();
            }
        }
    }
    if prompt == "retry-once"
        && calls
            .lock()
            .await
            .iter()
            .filter(|call| user_prompt(call) == "retry-once")
            .count()
            == 1
    {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            [("retry-after", "0")],
            Json(json!({"error": {"message": "upstream is temporarily unavailable"}})),
        )
            .into_response();
    }
    if (model == "model/weak" && prompt == "unavailable") || prompt == "all-unavailable" {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"error": {"message": "upstream is unavailable"}})),
        )
            .into_response();
    }
    if model == "model/weak" && prompt == "overflow" {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({
                "error": {
                    "code": "context_length_exceeded",
                    "message": "request exceeds this model's context window"
                }
            })),
        )
            .into_response();
    }
    if prompt == "upstream-headers" {
        // Both the buffered and the streamed reply echo the same set, so the two
        // capture paths are compared against one expectation.
        const UPSTREAM_HEADER_ECHO: [(&str, &str); 5] = [
            ("x-upstream-trace", "trace-123"),
            ("x-request-id", "req-42"),
            ("request-id", "req_anthropic_42"),
            ("x-model-router-selected-model", "model/upstream-echo"),
            ("x-switchyard-session-id", "spoofed-by-upstream"),
        ];
        // Streaming captures the headers off the response head, before any body
        // arrives, so the streamed variant exercises a different capture branch.
        let mut response = if body["stream"].as_bool() == Some(true) {
            let events = [
                json!({"id": "chatcmpl-headers", "model": model, "choices": [{"index": 0, "delta": {"role": "assistant"}}]}).to_string(),
                json!({"id": "chatcmpl-headers", "model": model, "choices": [{"index": 0, "delta": {"content": "ok"}}]}).to_string(),
                json!({"id": "chatcmpl-headers", "model": model, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12}}).to_string(),
                "[DONE]".to_string(),
            ];
            let stream = futures_util::stream::iter(
                events
                    .into_iter()
                    .map(|data| Ok::<Event, Infallible>(Event::default().data(data))),
            );
            let mut response = Sse::new(stream).into_response();
            let headers = response.headers_mut();
            for (name, value) in UPSTREAM_HEADER_ECHO {
                headers.append(name, HeaderValue::from_static(value));
            }
            response
        } else {
            (
                UPSTREAM_HEADER_ECHO,
                Json(json!({
                "id": "chatcmpl-test",
                "object": "chat.completion",
                "model": model,
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": "ok"},
                    "finish_reason": "stop"
                }],
                "usage": {"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12}
                })),
            )
                .into_response()
        };
        let headers = response.headers_mut();
        headers.append("x-upstream-trace", HeaderValue::from_static("trace-456"));
        headers.append(
            "link",
            HeaderValue::from_static("<https://example.test/next>; rel=next"),
        );
        headers.append(
            "link",
            HeaderValue::from_static("<https://example.test/prev>; rel=prev"),
        );
        headers.append(
            "set-cookie",
            HeaderValue::from_static("session=upstream; HttpOnly"),
        );
        return response;
    }
    if body["stream"].as_bool() == Some(true) {
        // Streamed tool call, for the namespace-on-every-event assertions. The
        // model calls a tool by the name it was given, so echo that name back.
        if prompt == "mcp-tool-call" {
            let called = body["tool_choice"]["function"]["name"]
                .as_str()
                .or_else(|| body["tools"][0]["function"]["name"].as_str())
                .unwrap_or("search")
                .to_string();
            let events = [
                json!({"id": "chatcmpl-mcp", "model": model, "choices": [{"index": 0, "delta": {"role": "assistant", "tool_calls": [{"index": 0, "id": "call_1", "type": "function", "function": {"name": called, "arguments": ""}}]}}]}).to_string(),
                json!({"id": "chatcmpl-mcp", "model": model, "choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "{\"q\":\"rust\"}"}}]}}]}).to_string(),
                json!({"id": "chatcmpl-mcp", "model": model, "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 4, "completion_tokens": 3, "total_tokens": 7}}).to_string(),
                "[DONE]".to_string(),
            ];
            let stream = futures_util::stream::iter(
                events
                    .into_iter()
                    .map(|data| Ok::<Event, Infallible>(Event::default().data(data))),
            );
            return Sse::new(stream).into_response();
        }
        if prompt == "stream-error" {
            let events = [
                json!({"id": "chatcmpl-stream-error", "model": model, "choices": [{"index": 0, "delta": {"role": "assistant"}}]}).to_string(),
                json!({"id": "chatcmpl-stream-error", "model": model, "choices": [{"index": 0, "delta": {"content": "before"}}]}).to_string(),
                json!({"id": "chatcmpl-stream-error", "model": model, "choices": [{"index": 0, "delta": {"content": "still here"}}], "usage": {"prompt_tokens": 6, "completion_tokens": 2, "total_tokens": 8}}).to_string(),
                json!({"error": {"message": "upstream stream failed", "type": "server_error"}}).to_string(),
            ];
            let stream = futures_util::stream::iter(
                events
                    .into_iter()
                    .map(|data| Ok::<Event, Infallible>(Event::default().data(data))),
            );
            return Sse::new(stream).into_response();
        }
        let events = [
            json!({"id": "chatcmpl-stream", "model": model, "choices": [{"index": 0, "delta": {"role": "assistant"}}]}).to_string(),
            json!({"id": "chatcmpl-stream", "model": model, "choices": [{"index": 0, "delta": {"content": "hello"}}]}).to_string(),
            json!({"id": "chatcmpl-stream", "model": model, "choices": [{"index": 0, "delta": {"content": "-partial"}}], "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6, "prompt_tokens_details": {"cached_tokens": 2, "cache_creation_tokens": 1}}}).to_string(),
            json!({"id": "chatcmpl-stream", "model": model, "choices": [{"index": 0, "delta": {"content": "-final"}}], "usage": {"prompt_tokens": 12, "completion_tokens": 5, "total_tokens": 17, "prompt_tokens_details": {"cached_tokens": 7, "cache_creation_tokens": 2}, "completion_tokens_details": {"reasoning_tokens": 3}}}).to_string(),
            json!({"id": "chatcmpl-stream", "model": model, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}).to_string(),
            "[DONE]".to_string(),
        ];
        let stream = futures_util::stream::iter(
            events
                .into_iter()
                .map(|data| Ok::<Event, Infallible>(Event::default().data(data))),
        );
        return Sse::new(stream).into_response();
    }

    if model == "model/advisor" {
        // The review consult carries the serialized transcript in its user
        // message, so the original prompt text rides inside it: tests script
        // the verdict (or an outage) from the prompt they send.
        let haystack = body["messages"].to_string();
        if haystack.contains("advisor-down") {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(json!({"error": {"message": "advisor is unavailable"}})),
            )
                .into_response();
        }
        let verdict = if haystack.contains("please-redo") {
            "REDO run the tests"
        } else {
            "APPROVE"
        };
        return Json(json!({
            "id": "chatcmpl-advisor",
            "object": "chat.completion",
            "model": model,
            "choices": [{
                "index": 0,
                "message": {"role": "assistant", "content": verdict},
                "finish_reason": "stop"
            }],
            "usage": {"prompt_tokens": 40, "completion_tokens": 4, "total_tokens": 44}
        }))
        .into_response();
    }

    // Buffered tool call, the non-streaming counterpart of the branch above.
    if prompt == "mcp-tool-call" {
        let called = body["tool_choice"]["function"]["name"]
            .as_str()
            .or_else(|| body["tools"][0]["function"]["name"].as_str())
            .unwrap_or("search")
            .to_string();
        return Json(json!({
            "id": "chatcmpl-mcp",
            "object": "chat.completion",
            "model": model,
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": null,
                    "tool_calls": [{
                        "id": "call_1",
                        "type": "function",
                        "function": {"name": called, "arguments": "{\"q\":\"rust\"}"}
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "usage": {"prompt_tokens": 4, "completion_tokens": 3, "total_tokens": 7}
        }))
        .into_response();
    }

    let custom_target_schema = body
        .pointer("/response_format/json_schema/schema/properties/decision/properties/target")
        .is_some();
    let requests_invalid_verdict = body["messages"].as_array().is_some_and(|messages| {
        messages.iter().any(|message| {
            message["content"]
                .as_str()
                .is_some_and(|content| content.contains("invalid verdict"))
        })
    });
    let requests_schema_invalid_verdict = body["messages"].as_array().is_some_and(|messages| {
        messages.iter().any(|message| {
            message["content"]
                .as_str()
                .is_some_and(|content| content.contains("schema-invalid verdict"))
        })
    });
    // A custom-mode task may name the group it wants the judge to pick, so one
    // config can be driven through each of its groups in turn.
    let requested_group = body["messages"].as_array().and_then(|messages| {
        messages.iter().find_map(|message| {
            message["content"]
                .as_str()?
                .split_once("route to ")
                .map(|(_, group)| group.trim().to_string())
        })
    });
    let content = if model == "model/classifier" && custom_target_schema {
        if requests_invalid_verdict {
            r#"{"decision":{"target":"unknown"}}"#.to_string()
        } else {
            let group = requested_group.unwrap_or_else(|| "efficient".to_string());
            format!(r#"{{"decision":{{"target":"{group}"}}}}"#)
        }
    } else if body
        .pointer("/response_format/json_schema/schema/properties/escalate")
        .is_some()
    {
        r#"{"escalate":false,"reason":"making progress"}"#.to_string()
    } else if model == "model/classifier" && requests_schema_invalid_verdict {
        r#"{"crux":"bounded task","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.1,"unexpected":true}"#.to_string()
    } else if model == "model/classifier" {
        r#"{"crux":"bounded task","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.9}"#.to_string()
    } else {
        "ok".to_string()
    };
    Json(json!({
        "id": "chatcmpl-test",
        "object": "chat.completion",
        "model": model,
        "choices": [{
            "index": 0,
            "message": {"role": "assistant", "content": content},
            "finish_reason": "stop"
        }],
        "usage": {
            "prompt_tokens": 10,
            "completion_tokens": 2,
            "total_tokens": 12,
            "prompt_tokens_details": {"cached_tokens": 7}
        }
    }))
    .into_response()
}

async fn upstream_messages_requires_forwarded_oauth(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(body.clone());
    let has_expected_headers = headers
        .get("authorization")
        .and_then(|value| value.to_str().ok())
        == Some("Bearer claude-oauth-token")
        && headers
            .get("anthropic-beta")
            .and_then(|value| value.to_str().ok())
            == Some("oauth-2025-04-20")
        && headers
            .get("anthropic-version")
            .and_then(|value| value.to_str().ok())
            == Some("2023-06-01")
        && headers
            .get("chatgpt-account-id")
            .and_then(|value| value.to_str().ok())
            == Some("account-123")
        && headers
            .get("x-openai-fedramp")
            .and_then(|value| value.to_str().ok())
            == Some("true");
    if !has_expected_headers {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": {"message": "missing forwarded Anthropic OAuth headers"}})),
        )
            .into_response();
    }
    Json(json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "model": body["model"],
        "content": [{"type": "text", "text": "ok"}],
        "stop_reason": "end_turn",
        "stop_sequence": null,
        "usage": {"input_tokens": 1, "output_tokens": 1}
    }))
    .into_response()
}

async fn upstream_responses_requires_forwarded_auth(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(body.clone());
    if headers.contains_key("x-test-redirect") {
        return (StatusCode::TEMPORARY_REDIRECT, [("location", "/capture")]).into_response();
    }
    if headers.contains_key("x-test-echo-auth") {
        let authorization = headers
            .get("authorization")
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default();
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": {"message": authorization}})),
        )
            .into_response();
    }
    let has_expected_headers = headers
        .get("authorization")
        .and_then(|value| value.to_str().ok())
        == Some("Bearer codex-login-token")
        && headers
            .get("chatgpt-account-id")
            .and_then(|value| value.to_str().ok())
            == Some("account-123")
        && headers
            .get("x-openai-fedramp")
            .and_then(|value| value.to_str().ok())
            == Some("true")
        && headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok())
            == Some("provider-api-key")
        && headers
            .get("anthropic-beta")
            .and_then(|value| value.to_str().ok())
            == Some("provider-beta");
    if !has_expected_headers {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": {"message": "missing forwarded OpenAI login"}})),
        )
            .into_response();
    }
    Json(json!({
        "id": "resp_test",
        "object": "response",
        "model": body["model"],
        "status": "completed",
        "output": [{
            "type": "message",
            "role": "assistant",
            "content": [{"type": "output_text", "text": "ok"}]
        }],
        "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
    }))
    .into_response()
}

async fn upstream_buffered_responses(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> Json<Value> {
    calls.lock().await.push(body.clone());
    let model = body["model"].as_str().unwrap_or_default();
    let mut response = json!({
        "id": "resp_buffered", "object": "response", "model": model,
        "status": "failed", "output": [], "usage": null,
        "error": {"code": "server_error", "message": "deterministic upstream failure"}
    });
    match model {
        "model/missing-error" => response = json!({"status": "failed"}),
        "model/invalid-error" => response["error"] = json!("invalid error details"),
        "model/invalid-code" => response["error"]["code"] = json!(42),
        "model/empty-code" => response["error"]["code"] = json!(""),
        "model/fallback" | "model/efficient" => {
            response["status"] = json!("completed");
            response["error"] = Value::Null;
            response["output"] = json!([{
                "type": "message", "role": "assistant",
                "content": [{"type": "output_text", "text": "ok"}]
            }]);
        }
        _ => {}
    }
    if let Some(secret) = headers.get("x-private-token") {
        response["error"]["code"] = json!(secret.to_str().unwrap_or_default());
        response["error"]["message"] = json!(format!(
            "provider rejected {}",
            secret.to_str().unwrap_or_default()
        ));
    }
    Json(response)
}

/// A local Responses provider whose IDs normally contain its name. It returns `state_not_found`
/// for another provider's ID, except `resp_shared_conflict`, which tests duplicate ownership.
/// The judge selects the strong tier when the input contains `ROUTE_B`.
async fn upstream_responses_silo(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    Path(silo): Path<String>,
    Json(body): Json<Value>,
) -> HttpResponse {
    let mut calls = calls.lock().await;
    calls.push(body.clone());
    let model = body["model"].as_str().unwrap_or_default().to_string();
    if model == "model/judge" {
        let strong = body.to_string().contains("ROUTE_B");
        let verdict = if body["text"]["format"]["schema"]["properties"]
            .get("escalate")
            .is_some()
        {
            json!({"escalate": strong, "reason": "state probe"})
        } else {
            json!({
                "crux": "state probe", "primary_rule": if strong { "LIM-1" } else { "SUP-1" },
                "capability_boundary": if strong { "unsupported" } else { "supported" },
                "p_solve": if strong { 0.1 } else { 0.9 },
            })
        };
        return Json(responses_body("resp_judge", &model, &verdict.to_string())).into_response();
    }
    let minted_prefix = format!("resp_{silo}_");
    if silo == "A" && body.to_string().contains("owner-unavailable") {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"error": {"message": "provider A is unavailable"}})),
        )
            .into_response();
    }
    if let Some(previous) = body["previous_response_id"].as_str()
        && !previous.starts_with(&minted_prefix)
        && previous != "resp_shared_conflict"
    {
        return (
            StatusCode::BAD_REQUEST,
            Json(
                json!({"error": {"code": "state_not_found", "message": format!(
                    "previous_response_id {previous} is not present in provider {silo}"
                )}}),
            ),
        )
            .into_response();
    }
    let id = if body.to_string().contains("state-id-conflict") {
        "resp_shared_conflict".to_string()
    } else {
        format!("{minted_prefix}{}", calls.len())
    };
    let text = format!("served-by:{silo}");
    let mut response = responses_body(&id, &model, &text);
    response["store"] = body.get("store").cloned().unwrap_or(json!(true));
    response["conversation"] = body.get("conversation").cloned().unwrap_or(Value::Null);
    if body["stream"] == true {
        let mut created = response.clone();
        created["status"] = json!("in_progress");
        created["output"] = json!([]);
        let events = [
            json!({"type": "response.created", "response": created}),
            json!({"type": "response.output_text.delta", "output_index": 0, "delta": text}),
            json!({"type": "response.completed", "response": response}),
        ];
        let stream = futures_util::stream::iter(events.into_iter().map(|event| {
            Ok::<Event, Infallible>(
                Event::default()
                    .event(event["type"].as_str().unwrap_or_default())
                    .data(event.to_string()),
            )
        }));
        return Sse::new(stream).into_response();
    }
    Json(response).into_response()
}

fn responses_body(id: &str, model: &str, text: &str) -> Value {
    json!({
        "id": id, "object": "response", "created_at": 1, "model": model, "status": "completed",
        "output": [{"id": "msg_1", "type": "message", "status": "completed", "role": "assistant",
                    "content": [{"type": "output_text", "text": text, "annotations": []}]}],
        "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2,
                  "output_tokens_details": {"reasoning_tokens": 0}}
    })
}

async fn upstream_redirect_capture(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    headers: HeaderMap,
) -> HttpResponse {
    calls.lock().await.push(json!({
        "redirected": true,
        "has_authorization": headers.contains_key("authorization")
    }));
    StatusCode::OK.into_response()
}

async fn upstream_count_tokens(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(body.clone());
    Json(json!({"input_tokens": 7})).into_response()
}

async fn upstream_responses_auxiliary(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    uri: Uri,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(json!({
        "path": uri.path(),
        "body": body,
        "configured_header": headers.get("x-configured-client").and_then(|value| value.to_str().ok())
    }));
    if uri.path().ends_with("/input_tokens") {
        Json(json!({"input_tokens": 11})).into_response()
    } else {
        Json(json!({"id": "resp_compacted", "object": "response", "output": []})).into_response()
    }
}

async fn upstream_fallback(
    State(calls): State<Arc<Mutex<Vec<Value>>>>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> HttpResponse {
    calls.lock().await.push(json!({
        "body": body,
        "authorization": headers.get("authorization").and_then(|value| value.to_str().ok()),
        "end_to_end": headers.get("x-end-to-end").and_then(|value| value.to_str().ok()),
        "configured_secret": headers.contains_key("x-configured-secret"),
        "connection": headers.contains_key("connection"),
        "connection_nominated": headers.contains_key("x-remove-me")
    }));
    let mut response = Json(json!({"input_tokens": 7})).into_response();
    response
        .headers_mut()
        .insert("connection", HeaderValue::from_static("x-upstream-hop"));
    response
        .headers_mut()
        .insert("x-upstream-hop", HeaderValue::from_static("remove"));
    response.headers_mut().insert(
        "x-end-to-end-response",
        HeaderValue::from_static("preserve"),
    );
    response
}

fn random_state(base_url: &str, routes: &[(&str, &[&str])]) -> TestResult<ServerState> {
    random_state_with_retries(base_url, routes, 0)
}

fn random_state_with_retries(
    base_url: &str,
    routes: &[(&str, &[&str])],
    max_retries: u32,
) -> TestResult<ServerState> {
    let backend = Backend::OpenAiChat(HttpBackendConfig {
        base_url: base_url.to_string(),
        api_key: Some("test-key".to_string()),
        forward_auth: false,
        extra_headers: BTreeMap::new(),
        extra_body: BTreeMap::new(),
        reasoning_effort: None,
        max_retries,
        timeout: None,
    });
    let target_models = routes
        .iter()
        .flat_map(|(_, targets)| targets.iter().copied())
        .collect::<HashSet<_>>();
    let model_configs = target_models
        .into_iter()
        .map(|model| ModelConfig::new(model, backend.clone(), None))
        .collect::<Vec<_>>();
    let client: Arc<dyn RoutedLlmClient> = Arc::new(TranslatingLlmClient::new(&model_configs)?);
    let entries = routes
        .iter()
        .map(|(route_model, targets)| {
            let algorithm: Arc<dyn Algorithm> = Arc::new(Random::new(None, None)?);
            let decision_targets = targets
                .iter()
                .map(|model| DecisionTarget {
                    target: (*model).to_string(),
                    model: ModelId::from(*model),
                    format: WireFormat::OpenAiChat,
                    base_url: base_url.to_string(),
                    extra_body: BTreeMap::new(),
                })
                .collect();
            Ok((
                ModelId::from(*route_model),
                Route::new(
                    algorithm,
                    ClientRouter::single(Arc::clone(&client)),
                    None,
                    ModelCapabilities::default(),
                    None,
                    None,
                    decision_targets,
                    RuntimeModels::new(
                        [(
                            Category::Any,
                            targets.iter().map(|model| ModelId::from(*model)).collect(),
                        )]
                        .into(),
                    ),
                ),
            ))
        })
        .collect::<TestResult<Vec<_>>>()?;
    ServerState::from_runner(Runner::new(entries)).map_err(Into::into)
}

async fn test_app(routes: &[(&str, &[&str])]) -> TestResult<(MockUpstream, Router)> {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(random_state(&upstream.base_url, routes)?);
    Ok((upstream, app))
}

// Embedders expose only the three primary inference endpoints and own every other route.
#[tokio::test]
async fn llm_router_exposes_only_primary_llm_endpoints() -> TestResult {
    let state = random_state("http://127.0.0.1:1/v1", &[(ROUTE_MODEL, &["model/weak"])])?;
    let app = build_llm_router(state);

    for path in ["/v1/chat/completions", "/v1/messages", "/v1/responses"] {
        assert_eq!(
            send(&app, "GET", path, None).await?.status,
            StatusCode::METHOD_NOT_ALLOWED,
            "{path} should be registered"
        );
    }

    for path in [
        "/v1/decision",
        "/v1/messages/count_tokens",
        "/v1/responses/input_tokens",
        "/v1/responses/compact",
        "/v1/models",
        "/v1/stats",
        "/v1/stats/reset",
        "/v1/routing/session-stats",
        "/metrics",
        "/health",
        "/future/provider/endpoint",
    ] {
        assert_eq!(
            send(&app, "POST", path, None).await?.status,
            StatusCode::NOT_FOUND,
            "{path} should not be registered"
        );
    }
    Ok(())
}

fn empty_token_totals() -> Value {
    json!({
        "prompt": 0,
        "completion": 0,
        "cached": 0,
        "cache_creation": 0,
        "reasoning": 0,
        "total": 0
    })
}

#[tokio::test]
async fn stats_exposes_the_exact_empty_schema_and_no_legacy_alias() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;
    let response = send(&app, "GET", "/v1/stats", None).await?;
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        response.json()?,
        json!({
            "total_requests": 0,
            "total_errors": 0,
            "total_tokens": empty_token_totals(),
            "models": {},
            "routing_overhead": {
                "count": 0,
                "total_ms": 0.0,
                "min_ms": 0.0,
                "max_ms": 0.0,
                "avg_ms": 0.0,
                "p50_ms": 0.0,
                "p99_ms": 0.0
            },
            "routing_fallbacks": {
                "context_window": 0,
                "unavailable": 0
            },
            "classifier": {
                "total_requests": 0,
                "total_errors": 0,
                "total_tokens": empty_token_totals(),
                "models": {},
            },
            "algorithm_stats": {},
        })
    );
    assert_eq!(
        send(&app, "GET", "/v1/routing/stats", None).await?.status,
        StatusCode::NOT_FOUND
    );
    Ok(())
}

#[tokio::test]
async fn stats_accumulates_buffered_success_error_and_shared_routes() -> TestResult {
    let (_upstream, app) = test_app(&[
        ("switchyard/one", &["gemini-3.5-flash"]),
        ("switchyard/two", &["model/unknown"]),
    ])
    .await?;
    for route in ["switchyard/one", "switchyard/two"] {
        assert_eq!(
            send(
                &app,
                "POST",
                "/v1/chat/completions",
                Some(json!({
                    "model": route,
                    "messages": [{"role": "user", "content": "hello"}]
                })),
            )
            .await?
            .status,
            StatusCode::OK
        );
    }
    assert_eq!(
        send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": "switchyard/one",
                "messages": [{"role": "user", "content": "fail"}]
            })),
        )
        .await?
        .status,
        StatusCode::IM_A_TEAPOT
    );

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["total_requests"], 3);
    assert_eq!(stats["total_errors"], 1);
    assert_eq!(
        stats["total_tokens"],
        json!({
            "prompt": 20,
            "completion": 4,
            "cached": 14,
            "cache_creation": 0,
            "reasoning": 0,
            "total": 24
        })
    );
    assert_eq!(stats["models"]["gemini-3.5-flash"]["calls"], 1);
    assert_eq!(stats["models"]["gemini-3.5-flash"]["errors"], 1);
    assert_eq!(stats["models"]["model/unknown"]["calls"], 1);
    assert_eq!(stats["routing_overhead"]["count"], 3);
    Ok(())
}

fn buffered_responses_app(
    upstream: &MockUpstream,
    model: &str,
    fallback: bool,
    forward_auth: bool,
) -> TestResult<Router> {
    let route = if fallback {
        "type = \"random\"\ntargets = [\"first\", \"second\"]\nweights = [1000, 1]\nseed = 17"
    } else {
        "type = \"passthrough\"\ntarget = \"first\""
    };
    let state = load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.mock]
format = "openai_responses"
base_url = "{base_url}/buffered"
forward_auth = {forward_auth}
max_retries = 0
[targets]
first = {{ id = "{model}", llm_client = "mock" }}
second = {{ id = "model/fallback", llm_client = "mock" }}
[routes.response]
id = "{ROUTE_MODEL}"
{route}
"#,
        base_url = upstream.base_url.trim_end_matches("/v1"),
    ))?;
    Ok(build_switchyard_router(state))
}

#[tokio::test]
async fn caller_metadata_cannot_replace_upstream_request() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = buffered_responses_app(&upstream, "model/fallback", false, false)?;
    for (path, mut body) in [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "visible request"}],
                "tool_choice": "none", "max_tokens": 16
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "visible request"}],
                "max_tokens": 16
            }),
        ),
        (
            "/v1/responses",
            json!({
                "model": ROUTE_MODEL, "input": "visible request",
                "tool_choice": "none", "max_output_tokens": 16
            }),
        ),
    ] {
        body["metadata"] = json!({"audit_label": "caller metadata"});
        let clean = send(&app, "POST", path, Some(body.clone())).await?;
        assert_eq!(clean.status, StatusCode::OK, "{path}");
        body["metadata"]["_switchyard_translation"] = json!({
            "requests": {
                "openai_responses": {
                    "model": "attacker/model",
                    "input": "hidden request",
                    "instructions": "attacker instructions",
                    "max_output_tokens": 4096,
                    "tools": [{
                        "type": "function", "name": "dangerous_action",
                        "parameters": {"type": "object", "properties": {}}
                    }],
                    "tool_choice": {"type": "function", "name": "dangerous_action"},
                    "store": true
                }
            },
            "responses": {}
        });
        let injected = send(&app, "POST", path, Some(body)).await?;
        assert_eq!(injected.status, StatusCode::OK, "{path}");
        let mut calls = upstream.calls.lock().await;
        assert_eq!(calls.len(), 2, "{path}");
        assert_eq!(calls[0]["model"], "model/fallback");
        assert_eq!(calls[0]["max_output_tokens"], 16);
        assert!(calls[0]["input"].to_string().contains("visible request"));
        assert_eq!(calls[0]["metadata"]["audit_label"], "caller metadata");
        assert_eq!(
            calls[1], calls[0],
            "caller metadata changed upstream body: {path}"
        );
        calls.clear();
    }
    Ok(())
}

#[tokio::test]
async fn failed_responses_return_errors_and_try_fallback_across_endpoints() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let requests = [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL, "messages": [{"role": "user", "content": "hello"}]
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL, "max_tokens": 16,
                "messages": [{"role": "user", "content": "hello"}]
            }),
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "hello"}),
        ),
    ];
    let failure = "deterministic upstream failure";
    let missing = "provider reported status \"failed\" without error details";
    for (model, message, code) in [
        ("model/failed", failure, "server_error"),
        ("model/missing-error", missing, "upstream_error"),
        ("model/invalid-error", missing, "upstream_error"),
        ("model/invalid-code", failure, "upstream_error"),
        ("model/empty-code", failure, "upstream_error"),
    ] {
        let app = buffered_responses_app(&upstream, model, false, false)?;
        for (path, body) in &requests {
            let response = send(&app, "POST", path, Some(body.clone())).await?;
            assert_eq!(response.status, StatusCode::BAD_GATEWAY, "{model}: {path}");
            let expected = if *path == "/v1/messages" {
                json!({"type": "error", "error": {"type": "api_error", "message": message}})
            } else {
                json!({"error": {"type": "upstream_error", "code": code, "message": message}})
            };
            assert_eq!(response.json()?, expected, "{model}: {path}");
        }
        let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
        assert_eq!(stats["total_requests"], requests.len(), "{model}");
        assert_eq!(stats["total_errors"], requests.len(), "{model}");
        assert_eq!(stats["models"][model]["errors"], requests.len(), "{model}");
    }

    let app = buffered_responses_app(&upstream, "model/failed", false, true)?;
    let (path, body) = &requests[0];
    let response = send_with_headers(
        &app,
        "POST",
        path,
        Some(body.clone()),
        &[("x-private-token", "test-private-credential")],
    )
    .await?;
    assert_eq!(response.status, StatusCode::BAD_GATEWAY);
    assert_eq!(
        response.json()?["error"]["message"],
        "provider rejected [REDACTED]"
    );
    assert_eq!(response.json()?["error"]["code"], "[REDACTED]");

    let app = buffered_responses_app(&upstream, "model/failed", true, false)?;
    for (path, body) in &requests {
        let previous_calls = upstream.models().await.len();
        let response = send(&app, "POST", path, Some(body.clone())).await?;
        assert_eq!(response.status, StatusCode::OK, "{path}");
        assert_eq!(response.json()?["model"], "model/fallback", "{path}");
        assert_eq!(
            &upstream.models().await[previous_calls..],
            ["model/failed", "model/fallback"],
            "{path}"
        );
    }
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["models"]["model/failed"]["errors"], requests.len());
    assert_eq!(stats["models"]["model/fallback"]["calls"], requests.len());
    Ok(())
}

#[tokio::test]
async fn stats_reset_returns_confirmation_and_clears_all_stats() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;
    assert_eq!(
        send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "hello"}]
            })),
        )
        .await?
        .status,
        StatusCode::OK
    );

    let reset = send(&app, "POST", "/v1/stats/reset", None).await?;
    assert_eq!(reset.status, StatusCode::OK);
    assert_eq!(reset.json()?, json!({"status": "reset"}));

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["total_requests"], 0);
    assert_eq!(stats["total_errors"], 0);
    assert_eq!(stats["total_tokens"], empty_token_totals());
    assert_eq!(stats["models"], json!({}));
    assert_eq!(stats["routing_overhead"]["count"], 0);
    assert_eq!(stats["classifier"]["total_requests"], 0);
    assert_eq!(stats["classifier"]["models"], json!({}));
    Ok(())
}

#[tokio::test]
async fn metrics_exposes_switchyard_otel_instruments() -> TestResult {
    const MODEL: &str = "model/metrics-buffered";
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(random_state_with_retries(
        &upstream.base_url,
        &[(ROUTE_MODEL, &[MODEL])],
        1,
    )?);

    let before = send(&app, "GET", "/metrics", None).await?;
    assert_eq!(before.status, StatusCode::OK);
    assert_eq!(
        before
            .headers
            .get("content-type")
            .and_then(|value| value.to_str().ok()),
        Some("text/plain; version=0.0.4; charset=utf-8")
    );
    let seeded = before.text()?;
    for expected in [
        "# TYPE switchyard_client_responses_total counter",
        "switchyard_client_responses_total{outcome=\"ok\",",
        "switchyard_client_responses_total{outcome=\"retryable_error\",",
        "switchyard_client_responses_total{outcome=\"other_error\",",
        "# TYPE switchyard_upstream_attempts_total counter",
        "switchyard_upstream_attempts_total{code=\"200\",outcome=\"ok\",",
        "switchyard_upstream_attempts_total{code=\"429\",outcome=\"retryable_error\",",
        "switchyard_upstream_attempts_total{code=\"500\",outcome=\"retryable_error\",",
        "switchyard_upstream_attempts_total{code=\"504\",outcome=\"retryable_error\",",
        "switchyard_upstream_attempts_total{code=\"none\",outcome=\"retryable_error\",",
        "# TYPE switchyard_router_retry_recovered_total counter",
        "switchyard_router_retry_recovered_total{otel_scope_name=\"switchyard\"} 0",
    ] {
        assert!(
            seeded.contains(expected),
            "missing seeded {expected:?} in metrics:\n{seeded}"
        );
    }

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "retry-once"}]
        })),
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    let after = send(&app, "GET", "/metrics", None).await?;
    let metrics = after.text()?;
    assert_eq!(
        metric_delta(
            seeded,
            metrics,
            "switchyard_router_retry_recovered_total",
            &[]
        ),
        Some(1.0)
    );
    for expected in [
        "# TYPE switchyard_build_info gauge",
        &format!("switchyard_build_info{{version=\"{VERSION}\""),
        "# TYPE switchyard_total_requests gauge",
        "# TYPE switchyard_total_errors gauge",
        "# TYPE switchyard_requests_total counter",
        "# TYPE switchyard_model_call_latency_ms histogram",
        "switchyard_client_responses_total{outcome=\"ok\",",
        "switchyard_upstream_attempts_total{code=\"200\",outcome=\"ok\",",
        "# TYPE switchyard_runs_total counter",
        "# TYPE switchyard_run_duration_ms histogram",
        "# TYPE switchyard_prompt_tokens_total counter",
        "# TYPE switchyard_completion_tokens_total counter",
        "# TYPE switchyard_cached_tokens_total counter",
        "# TYPE switchyard_total_latency_ms histogram",
        "# TYPE switchyard_routing_overhead_ms histogram",
        "algorithm=\"random\"",
        &format!("selected_model=\"{MODEL}\""),
    ] {
        assert!(
            metrics.contains(expected),
            "missing {expected:?} in metrics:\n{metrics}"
        );
    }
    for (name, expected_delta) in [
        ("switchyard_prompt_tokens_total", 10.0),
        ("switchyard_completion_tokens_total", 2.0),
        ("switchyard_cached_tokens_total", 7.0),
        ("switchyard_total_latency_ms_count", 1.0),
    ] {
        assert_eq!(
            metric_delta(seeded, metrics, name, &[("model", MODEL)]),
            Some(expected_delta),
            "unexpected delta for {name}"
        );
    }
    // A sub-millisecond boundary exists only because of the server's bucket view.
    assert!(
        metric_line(
            metrics,
            "switchyard_routing_overhead_ms_bucket",
            &[("algorithm", "random"), ("le", "0.1")]
        )
        .is_some()
    );
    for metric in [
        "switchyard_model_call_latency_ms_bucket",
        "switchyard_total_latency_ms_bucket",
    ] {
        assert!(
            metric_line(metrics, metric, &[("model", MODEL), ("le", "300000")]).is_some(),
            "missing five-minute bucket for {metric}"
        );
    }
    assert!(
        metric_line(
            metrics,
            "switchyard_cache_creation_tokens_total",
            &[("model", MODEL)]
        )
        .is_none()
    );
    assert!(
        metric_line(
            metrics,
            "switchyard_reasoning_tokens_total",
            &[("model", MODEL)]
        )
        .is_none()
    );
    for metric in [
        "switchyard_prompt_tokens_total",
        "switchyard_completion_tokens_total",
        "switchyard_cached_tokens_total",
        "switchyard_total_latency_ms_count",
    ] {
        let line = metric_line(metrics, metric, &[("model", MODEL)])
            .ok_or_else(|| format!("missing {metric} series for {MODEL}"))?;
        assert!(!line.contains("tier="), "unexpected tier label in {line}");
    }
    Ok(())
}

#[tokio::test]
async fn accepts_requests_larger_than_the_axum_default_body_limit() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;
    let content = "x".repeat(2 * 1024 * 1024);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": content}]
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    Ok(())
}

fn load_test_config(toml: &str) -> TestResult<ServerState> {
    let mut config = tempfile::Builder::new()
        .prefix("switchyard-server-config-")
        .suffix(".toml")
        .tempfile()?;
    config.write_all(toml.as_bytes())?;
    config.flush()?;
    Ok(load_server_state(config.path())?)
}

fn weighted_random_state(base_url: &str, weights: [u32; 2]) -> TestResult<ServerState> {
    load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.mock]
format = "openai_chat"
base_url = "{base_url}"
max_retries = 0

[targets.first]
id = "{first}"
llm_client = "mock"
system_prompt = "weak answer prompt"

[targets.second]
id = "{second}"
llm_client = "mock"
system_prompt = "strong answer prompt"

[routes.random]
id = "{ROUTE_MODEL}"
type = "random"
targets = ["first", "second"]
weights = {weights:?}
seed = 17
"#,
        first = "model/weak",
        second = "model/strong",
    ))
}

async fn send(app: &Router, method: &str, path: &str, body: Option<Value>) -> TestResult<Response> {
    send_with_headers(app, method, path, body, &[]).await
}

async fn send_with_headers(
    app: &Router,
    method: &str,
    path: &str,
    body: Option<Value>,
    headers: &[(&str, &str)],
) -> TestResult<Response> {
    let mut builder = HttpRequest::builder().method(method).uri(path);
    for (name, value) in headers {
        builder = builder.header(*name, *value);
    }
    let request_body = if let Some(body) = body {
        builder = builder.header("content-type", "application/json");
        Body::from(serde_json::to_vec(&body)?)
    } else {
        Body::empty()
    };
    let response = app.clone().oneshot(builder.body(request_body)?).await?;
    let status = response.status();
    let headers = response.headers().clone();
    let bytes = response.into_body().collect().await?.to_bytes();
    Ok(Response {
        status,
        headers,
        bytes,
    })
}

async fn send_raw_json(
    app: &Router,
    path: &str,
    body: Vec<u8>,
    content_type: Option<&str>,
) -> TestResult<Response> {
    let mut builder = HttpRequest::builder().method("POST").uri(path);
    if let Some(content_type) = content_type {
        builder = builder.header("content-type", content_type);
    }
    let response = app.clone().oneshot(builder.body(Body::from(body))?).await?;
    let status = response.status();
    let headers = response.headers().clone();
    let bytes = response.into_body().collect().await?.to_bytes();
    Ok(Response {
        status,
        headers,
        bytes,
    })
}

struct Response {
    status: StatusCode,
    headers: axum::http::HeaderMap,
    bytes: Bytes,
}

impl Response {
    fn json(&self) -> TestResult<Value> {
        Ok(serde_json::from_slice(&self.bytes)?)
    }

    fn text(&self) -> TestResult<&str> {
        Ok(std::str::from_utf8(&self.bytes)?)
    }
}

fn metric_line<'a>(metrics: &'a str, name: &str, labels: &[(&str, &str)]) -> Option<&'a str> {
    metrics.lines().find(|line| {
        line.starts_with(name)
            && labels
                .iter()
                .all(|(key, value)| line.contains(&format!("{key}=\"{value}\"")))
    })
}

fn metric_value(metrics: &str, name: &str, labels: &[(&str, &str)]) -> Option<f64> {
    metric_line(metrics, name, labels)?
        .split_whitespace()
        .last()?
        .parse()
        .ok()
}

fn metric_delta(before: &str, after: &str, name: &str, labels: &[(&str, &str)]) -> Option<f64> {
    metric_value(after, name, labels)
        .map(|after| after - metric_value(before, name, labels).unwrap_or_default())
}

fn assert_in_order(haystack: &str, needles: &[&str]) {
    let mut remainder = haystack;
    for needle in needles {
        let offset = remainder
            .find(needle)
            .unwrap_or_else(|| panic!("missing {needle:?} after prior events in:\n{haystack}"));
        remainder = &remainder[offset + needle.len()..];
    }
}

/// A route is a synthetic model (`switchyard/classify`) with no upstream of its own; its
/// algorithm picks real targets, and *those* name the client. One request can emit several
/// `Step::CallModel` for different targets, and two targets may sit on different
/// `[llm_clients.*]` sections — here the judge is on one provider and the serving models on
/// another. Pin that each call reaches its own target's upstream, rather than one client
/// chosen per route serving all of them.
#[tokio::test]
async fn each_target_in_one_request_is_served_by_its_own_client() -> TestResult {
    let judge_upstream = MockUpstream::start().await?;
    let model_upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.judge_provider]
format = "openai_chat"
base_url = "{judge_url}"

[llm_clients.model_provider]
format = "openai_chat"
base_url = "{model_url}"

[targets.judge]
id = "model/judge"
llm_client = "judge_provider"

[targets.strong]
id = "model/strong"
llm_client = "model_provider"

[targets.weak]
id = "model/weak"
llm_client = "model_provider"

[routes.classify]
id = "switchyard/classify"
type = "llm_classifier"
classifier_target = "judge"
strong_target = "strong"
weak_target = "weak"
base_threshold = 0.5
"#,
        judge_url = judge_upstream.base_url,
        model_url = model_upstream.base_url,
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/classify",
            "messages": [{"role": "user", "content": "hi"}]
        })),
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    // The judge call went to the judge's provider and nowhere else; the serving call went to
    // the models' provider. A single per-route client would have sent both to one upstream.
    assert_eq!(
        judge_upstream.models().await,
        vec!["model/judge".to_string()]
    );
    let served = model_upstream.models().await;
    assert_eq!(
        served.len(),
        1,
        "expected exactly one routed call: {served:?}"
    );
    assert!(
        served[0] == "model/weak" || served[0] == "model/strong",
        "routed call went to {served:?}"
    );
    Ok(())
}

#[tokio::test]
async fn decision_removes_api_keys_from_selected_and_fallback_urls() -> TestResult {
    let judge_upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.judge]
format = "openai_chat"
base_url = "{judge_url}"

[llm_clients.model]
format = "openai_chat"
base_url = "https://example.test/v1?key=secret&api_version=2026&api_key=other-secret"

[targets.judge]
id = "model/classifier"
llm_client = "judge"

[targets.quality]
id = "model/strong"
llm_client = "model"

[targets.economy]
id = "model/weak"
llm_client = "model"

[routes.classify]
id = "switchyard/classify"
type = "llm_classifier"
classifier_target = "judge"
strong_target = "quality"
weak_target = "economy"
base_threshold = 0.5
"#,
        judge_url = judge_upstream.base_url,
    ))?;
    let app = build_switchyard_router(state);
    let response = send(
        &app,
        "POST",
        "/v1/decision",
        Some(json!({
            "input_format": "openai_chat",
            "request": {
                "model": "switchyard/classify",
                "messages": [{"role": "user", "content": "bounded task"}]
            }
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let response = response.json()?;
    assert_eq!(response["fallbacks"].as_array().map(Vec::len), Some(1));
    for target in [&response["selected"], &response["fallbacks"][0]] {
        assert_eq!(
            target["llm_client"]["base_url"],
            "https://example.test/v1?api_version=2026"
        );
    }
    Ok(())
}

/// Configure classifier and escalation routes over two Responses providers.
/// `route/shared` uses one answer client; the other routes must return known continuations
/// to the model that served their state, even when the judge would select another provider.
fn state_silo_config(base_url: &str) -> String {
    let root = base_url.trim_end_matches("/v1");
    format!(
        r#"
schema_version = 1
[llm_clients.judge]
format = "openai_responses"
base_url = "{root}/silo/judge"
[llm_clients.a]
format = "openai_responses"
base_url = "{root}/silo/A"
max_retries = 0
[llm_clients.b]
format = "openai_responses"
base_url = "{root}/silo/B"
[targets.judge]
id = "model/judge"
llm_client = "judge"
[targets.a]
id = "model/provider-a"
llm_client = "a"
[targets.b]
id = "model/provider-b"
llm_client = "b"
[targets.shared_b]
id = "model/shared-b"
llm_client = "a"
[routes.shared]
id = "route/shared"
type = "llm_classifier"
classifier_target = "judge"
weak_target = "a"
strong_target = "shared_b"
base_threshold = 0.5
classify_trigger = "every_request"
[routes.escalation]
id = "route/escalation"
type = "llm_classifier"
mode = "escalation"
classifier_target = "judge"
weak_target = "a"
strong_target = "b"
escalation = {{ confirmations = 1 }}
[routes.dynamic]
id = "route/dynamic"
type = "llm_classifier"
classifier_target = "judge"
weak_target = "a"
strong_target = "b"
base_threshold = 0.5
classify_trigger = "every_request"
"#
    )
}

#[tokio::test]
async fn responses_continuations_preserve_state_ownership() -> TestResult {
    for (route, stream, endpoint) in [
        ("route/dynamic", false, "/v1/responses"),
        ("route/dynamic", true, "/v1/responses"),
        ("route/escalation", false, "/v1/decision"),
        ("route/escalation", true, "/v1/decision"),
        ("route/shared", false, "/v1/responses"),
    ] {
        let upstream = MockUpstream::start().await?;
        let app =
            build_switchyard_router(load_test_config(&state_silo_config(&upstream.base_url))?);
        let mut request =
            json!({"model": route, "input": "ROUTE_A remember mango", "stream": stream});
        if endpoint == "/v1/decision" {
            request = json!({"input_format": "openai_responses", "request": request});
        }
        let seed = send(&app, "POST", endpoint, Some(request)).await?;
        assert_eq!(seed.status, StatusCode::OK, "{}", seed.text()?);
        let body = if endpoint == "/v1/decision" {
            seed.json()?["response"].clone()
        } else if stream {
            sse_events(seed.text()?)
                .into_iter()
                .find(|event| event["type"] == "response.completed")
                .ok_or("stream ended without response.completed")?["response"]
                .clone()
        } else {
            seed.json()?
        };
        assert!(
            body["id"]
                .as_str()
                .is_some_and(|id| id.starts_with("resp_A_"))
        );
        let mut follow_request = json!({"model": route, "input": "ROUTE_B recall mango", "previous_response_id": body["id"]});
        let before = upstream.models().await.len();
        let follow = send(&app, "POST", "/v1/responses", Some(follow_request.clone())).await?;
        assert_eq!(follow.status, StatusCode::OK, "{}", follow.text()?);
        let expected = if route == "route/shared" {
            vec!["model/judge", "model/shared-b"]
        } else {
            vec!["model/provider-a"]
        };
        assert_eq!(&upstream.models().await[before..], expected);
        assert_eq!(
            follow.headers["x-model-router-selected-model"],
            *expected.last().ok_or("missing target")?
        );
        if route == "route/dynamic" {
            follow_request["previous_response_id"] = follow.json()?["id"].clone();
            let chained = send(&app, "POST", "/v1/responses", Some(follow_request.clone())).await?;
            assert_eq!(chained.status, StatusCode::OK);
            assert_eq!(
                chained.headers["x-model-router-selected-model"],
                "model/provider-a"
            );
            let before = upstream.models().await.len();
            let fresh = send(
                &app,
                "POST",
                "/v1/responses",
                Some(json!({"model": route, "input": "ROUTE_B a new task"})),
            )
            .await?;
            assert_eq!(fresh.status, StatusCode::OK);
            assert_eq!(
                fresh.headers["x-model-router-selected-model"],
                "model/provider-b"
            );
            assert_eq!(
                &upstream.models().await[before..],
                ["model/judge", "model/provider-b"]
            );
            follow_request["input"] = json!("ROUTE_B owner-unavailable");
            let before = upstream.models().await.len();
            let unavailable = send(&app, "POST", "/v1/responses", Some(follow_request)).await?;
            assert_eq!(unavailable.status, StatusCode::SERVICE_UNAVAILABLE);
            assert_eq!(&upstream.models().await[before..], ["model/provider-a"]);
        }
    }
    for (route, stream, endpoint) in [
        ("route/dynamic", false, "/v1/responses"),
        ("route/dynamic", true, "/v1/responses"),
        ("route/escalation", false, "/v1/decision"),
        ("route/escalation", true, "/v1/decision"),
    ] {
        let upstream = MockUpstream::start().await?;
        let app =
            build_switchyard_router(load_test_config(&state_silo_config(&upstream.base_url))?);
        let decision = endpoint == "/v1/decision";
        let input = if decision {
            "ROUTE_B state-id-conflict"
        } else {
            "ROUTE_A state-id-conflict"
        };
        let seed = send(
            &app,
            "POST",
            "/v1/responses",
            Some(json!({"model": route, "input": input})),
        )
        .await?;
        assert_eq!(seed.status, StatusCode::OK);
        let owner = seed.headers["x-model-router-selected-model"].clone();
        let input = if decision {
            "ROUTE_A state-id-conflict"
        } else {
            "ROUTE_B state-id-conflict"
        };
        let mut request = json!({"model": route, "input": input, "stream": stream});
        if decision {
            request = json!({"input_format": "openai_responses", "request": request});
        }
        let before = upstream.models().await.len();
        let rejected = send(&app, "POST", endpoint, Some(request)).await?;
        if stream && !decision {
            assert_eq!(rejected.status, StatusCode::OK);
            let events = sse_events(rejected.text()?);
            assert_eq!(events.len(), 1);
            assert_eq!(events[0]["type"], "error");
        } else {
            assert_eq!(
                rejected.status,
                StatusCode::CONFLICT,
                "{}",
                rejected.text()?
            );
            assert_eq!(rejected.json()?["error"]["code"], "response_state_conflict");
        }
        assert_eq!(
            &upstream.models().await[before..],
            if decision {
                ["model/provider-a", "model/judge"]
            } else {
                ["model/judge", "model/provider-b"]
            }
        );
        if !decision {
            let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
            assert_eq!(stats["total_requests"], 2);
            assert_eq!(stats["total_errors"], 1);
        }
        let follow = send(&app, "POST", "/v1/responses", Some(json!({"model": route, "input": "ROUTE_B recall", "previous_response_id": seed.json()?["id"], "store": false}))).await?;
        assert_eq!(follow.status, StatusCode::OK);
        assert_eq!(follow.headers["x-model-router-selected-model"], owner);
    }
    Ok(())
}

/// Decision-only routing returns callable metadata and preserves any answer produced while routing.
#[tokio::test]
async fn decision_returns_callable_target_and_routing_answer() -> TestResult {
    let judge_upstream = MockUpstream::start().await?;
    let model_upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.judge_provider]
format = "openai_chat"
base_url = "{judge_url}"

[llm_clients.model_provider]
format = "openai_chat"
base_url = "{model_url}"

[targets.judge]
id = "model/classifier"
llm_client = "judge_provider"
system_prompt = "judge target prompt"

[targets.quality]
id = "model/strong"
llm_client = "model_provider"

[targets.economy]
id = "model/weak"
llm_client = "model_provider"
extra_body = {{ service_tier = "priority" }}
system_prompt = "economy answer prompt"

[routes.classify]
id = "switchyard/classify"
type = "llm_classifier"
classifier_target = "judge"
strong_target = "quality"
weak_target = "economy"
base_threshold = 0.5

[routes.escalation]
id = "switchyard/escalation"
type = "llm_classifier"
mode = "escalation"
classifier_target = "judge"
strong_target = "quality"
weak_target = "economy"
escalation = {{ confirmations = 1 }}
"#,
        judge_url = judge_upstream.base_url,
        model_url = model_upstream.base_url,
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/decision",
        Some(json!({
            "input_format": "openai_chat",
            "request": {
                "model": "switchyard/classify",
                "messages": [{"role": "user", "content": "bounded task"}]
            }
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        response.json()?,
        json!({
            "selected": {
                "target": "economy",
                "model": "model/weak",
                "llm_client": {
                    "format": "openai_chat",
                    "base_url": model_upstream.base_url,
                },
                "extra_body": {"service_tier": "priority"},
            },
            "fallbacks": [{
                "target": "quality",
                "model": "model/strong",
                "llm_client": {
                    "format": "openai_chat",
                    "base_url": model_upstream.base_url,
                },
                "extra_body": {},
            }],
        })
    );
    assert_eq!(
        judge_upstream.models().await,
        vec!["model/classifier".to_string()]
    );
    assert!(model_upstream.models().await.is_empty());

    judge_upstream.calls.lock().await.clear();
    model_upstream.calls.lock().await.clear();
    let response = send(
        &app,
        "POST",
        "/v1/decision",
        Some(json!({
            "input_format": "openai_chat",
            "request": {
                "model": "switchyard/escalation",
                "messages": [{"role": "user", "content": "bounded task"}]
            }
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let response = response.json()?;
    assert_eq!(response["selected"]["target"], "economy");
    assert_eq!(response["fallbacks"], json!([]));
    assert_eq!(response["response"]["model"], "model/weak");
    assert_eq!(
        response["response"]["choices"][0]["message"]["content"],
        "ok"
    );
    assert_eq!(model_upstream.models().await, ["model/weak"]);
    assert_eq!(judge_upstream.models().await, ["model/classifier"]);
    assert!(has_system_prompt(
        &model_upstream.calls.lock().await[0],
        "economy answer prompt"
    ));
    assert!(!has_system_prompt(
        &judge_upstream.calls.lock().await[0],
        "judge target prompt"
    ));
    Ok(())
}

/// A critical tool error must reach the stage router's signal scorer, which reads
/// the decoded conversation. The endpoint records no inbound wire format, so a
/// scorer that parsed the raw body instead would find nothing and route every turn
/// as if the conversation had no signals at all.
#[tokio::test]
async fn stage_route_escalates_on_a_signal_in_the_conversation() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.strong]
id = "model/stats-strong"
llm_client = "upstream"

[targets.weak]
id = "model/stats-weak"
llm_client = "upstream"

[routes.stage]
id = "switchyard/stage"
type = "stage_router"
capable_target = "strong"
efficient_target = "weak"
picker = "efficient_first"
confidence_threshold = 0.5
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/stage",
            "messages": [
                {"role": "user", "content": "fix the build"},
                {"role": "assistant", "tool_calls": [{
                    "id": "call_1",
                    "type": "function",
                    "function": {"name": "Bash", "arguments": "{\"command\": \"cargo test\"}"}
                }]},
                {"role": "tool", "tool_call_id": "call_1", "content": "fatal runtime error: out of memory"},
            ]
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/stats-strong"),
        "a critical error should escalate on the signals alone"
    );
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(
        stats["algorithm_stats"]["stage_router"]["routing_decisions"]["override"]["targets"]["model/stats-strong"],
        1
    );
    Ok(())
}

/// Anthropic failure flags must affect routing before translating to Responses.
#[tokio::test]
async fn stage_route_honors_anthropic_tool_result_errors() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.upstream]
format = "openai_responses"
base_url = "{}/buffered"
[targets.capable]
id = "model/fallback"
llm_client = "upstream"
[targets.efficient]
id = "model/efficient"
llm_client = "upstream"
[routes.stage]
id = "switchyard/stage-structured-failure"
type = "stage_router"
capable_target = "capable"
efficient_target = "efficient"
picker = "efficient_first"
confidence_threshold = 0.5
capable_hold_turns = 0
recent_turn_window = 3
context_window = 131072
tool_calling = true
reasoning = true
"#,
        upstream.base_url.trim_end_matches("/v1")
    ))?);
    let neutral = "Synthetic dependency unavailable; retry with the recovery path.";
    for (is_error, text, expected) in [
        (false, neutral, "model/efficient"),
        (true, neutral, "model/fallback"),
        (
            false,
            "fatal runtime error: out of memory",
            "model/fallback",
        ),
    ] {
        let mut messages = vec![json!({
            "role": "user", "content": "Run the synthetic dependency probe."
        })];
        for id in ["toolu_probe_1", "toolu_probe_2"] {
            messages.push(json!({"role": "assistant", "content": [{
                "type": "tool_use", "id": id,
                "name": "synthetic_dependency_probe", "input": {}
            }]}));
            messages.push(json!({"role": "user", "content": [{
                "type": "tool_result", "tool_use_id": id,
                "content": text, "is_error": is_error
            }]}));
        }
        let body = json!({
            "model": "switchyard/stage-structured-failure",
            "max_tokens": 16, "messages": messages
        });
        for _ in 0..3 {
            let response = send(&app, "POST", "/v1/messages", Some(body.clone())).await?;
            assert_eq!(response.status, StatusCode::OK);
            assert_eq!(
                response.json()?["model"],
                expected,
                "is_error={is_error}, text={text}"
            );
            assert_eq!(
                upstream.models().await.last().map(String::as_str),
                Some(expected)
            );
        }
    }
    Ok(())
}

#[tokio::test]
async fn toml_config_constructs_and_serves_multiple_algorithms() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/classifier"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.random]
id = "switchyard/random"
type = "random"
targets = ["weak"]

[routes.classifier]
id = "switchyard/classifier"
type = "llm_classifier"
classifier_target = "classifier"
strong_target = "strong"
weak_target = "weak"
base_threshold = 0.5

[routes.passthrough]
id = "switchyard/passthrough"
type = "passthrough"
target = "weak"

[routes.stage]
id = "switchyard/stage"
type = "stage_router"
capable_target = "strong"
efficient_target = "weak"
picker = "efficient_first"
confidence_threshold = 0.5
recent_turn_window = 3

[routes.stage.handoff_notes]
escalation_note = "the previous model was stalling"

[routes.stage.classifier]
target = "classifier"
base_threshold = 0.5
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    for (route, selected) in [
        ("switchyard/random", "model/weak"),
        ("switchyard/classifier", "model/weak"),
        ("switchyard/passthrough", "model/weak"),
    ] {
        let response = send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": route,
                "messages": [{"role": "user", "content": "hi"}]
            })),
        )
        .await?;
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some(selected)
        );
    }

    let calls = upstream.calls.lock().await;
    assert_eq!(calls.len(), 4);
    assert_eq!(calls[0]["model"], "model/weak");
    assert_eq!(calls[1]["model"], "model/classifier");
    assert_eq!(calls[2]["model"], "model/weak");
    assert_eq!(calls[3]["model"], "model/weak");
    drop(calls);

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["total_requests"], 3);
    assert_eq!(stats["models"]["model/weak"]["calls"], 3);
    assert_eq!(stats["classifier"]["total_requests"], 1);
    assert_eq!(
        stats["classifier"]["models"]["model/classifier"]["calls"],
        1
    );
    assert_eq!(stats["classifier"]["total_tokens"]["prompt"], 10);
    Ok(())
}

// A configured mutation must select the efficient tier through the HTTP configuration path.
#[tokio::test]
async fn stage_router_uses_configured_tool_semantics() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.stage]
id = "switchyard/stage"
type = "stage_router"
capable_target = "strong"
efficient_target = "weak"
picker = "capable_first"
confidence_threshold = 0.3

[routes.stage.tool_semantics]
mutate = ["send_payment_request"]
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/stage",
            "messages": [
                {"role": "user", "content": "pay the balance"},
                {"role": "assistant", "tool_calls": [{
                    "id": "call_1",
                    "type": "function",
                    "function": {
                        "name": "send_payment_request",
                        "arguments": "{}"
                    }
                }]},
                {"role": "tool", "tool_call_id": "call_1", "content": "payment sent"}
            ]
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/weak")
    );
    Ok(())
}

// Composite TOML must pass custom stage semantics through to the nested stage router.
#[tokio::test]
async fn composite_router_uses_configured_tool_semantics() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/classifier"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.composite]
id = "switchyard/composite"
type = "composite"

[routes.composite.classifier]
target = "classifier"
base_threshold = 0.5
classify_trigger = "user_turn"

[routes.composite.stage]
capable_target = "strong"
efficient_target = "weak"
confidence_threshold = 0.3

[routes.composite.stage.tool_semantics]
new = ["send_message_to_user"]
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/composite",
            "messages": [
                {"role": "user", "content": "help the customer"},
                {"role": "assistant", "content": "working"},
                {"role": "user", "content": "continue"},
                {"role": "assistant", "content": "working"},
                {"role": "user", "content": "continue"},
                {"role": "assistant", "content": "working"},
                {"role": "assistant", "tool_calls": [{
                    "id": "call_1",
                    "type": "function",
                    "function": {
                        "name": "send_message_to_user",
                        "arguments": "{}"
                    }
                }]},
                {"role": "tool", "tool_call_id": "call_1", "content": "message sent"}
            ]
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/weak")
    );
    assert_eq!(
        upstream.models().await,
        ["model/weak"],
        "configured new activity must suppress the deep-turn stall without consulting the judge"
    );
    Ok(())
}

#[tokio::test]
async fn custom_classifier_uses_categories_and_falls_back_on_an_invalid_verdict() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/classifier"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.middle]
id = "model/middle"
llm_client = "upstream"

[targets.premium]
id = "model/premium"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.custom]
id = "switchyard/custom"
type = "llm_classifier"
mode = "custom"
models = {{ judge = ["classifier"], fast = ["weak"], balanced = ["middle"], reasoning = ["strong"], premium = ["premium"], any = ["weak", "middle", "strong", "premium"] }}
default_target = "premium"
prompt = "CUSTOM MULTI TARGET"
response_schema = '''
{{
  "type": "object",
  "properties": {{
    "decision": {{
      "type": "object",
      "properties": {{
        "target": {{"type": "string", "enum": ["fast", "balanced", "reasoning", "premium"]}}
      }},
      "required": ["target"],
      "additionalProperties": false
    }}
  }},
  "required": ["decision"],
  "additionalProperties": false
}}
'''

[routes.custom.policy]
type = "target_selector"
selector = "/decision/target"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    // Each named group resolves to its own model, so the policy picks between
    // four of them rather than between the two tier categories.
    for (task, selected) in [
        ("route to fast", "model/weak"),
        ("route to balanced", "model/middle"),
        ("route to reasoning", "model/strong"),
        ("route to premium", "model/premium"),
        ("return an invalid verdict", "model/premium"),
    ] {
        let response = send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": "switchyard/custom",
                "messages": [{"role": "user", "content": task}]
            })),
        )
        .await?;
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some(selected)
        );
    }

    let calls = upstream.calls.lock().await;
    let judge_call = calls
        .iter()
        .find(|call| call["model"] == "model/classifier")
        .ok_or("custom classifier target was not called")?;
    let prompt = judge_call["messages"][0]["content"]
        .as_str()
        .ok_or("custom classifier prompt was not text")?;
    assert_eq!(prompt, "CUSTOM MULTI TARGET");
    assert_eq!(judge_call["response_format"]["type"], "json_schema");
    assert_eq!(
        judge_call["response_format"]["json_schema"]["name"],
        "switchyard_classifier_response"
    );
    assert_eq!(judge_call["response_format"]["json_schema"]["strict"], true);
    assert_eq!(
        judge_call["response_format"]["json_schema"]["schema"]["properties"]["decision"]["properties"]
            ["target"]["enum"],
        json!(["fast", "balanced", "reasoning", "premium"])
    );
    Ok(())
}

#[tokio::test]
async fn classifier_contract_overrides_reach_every_server_mode() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/classifier"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.capability]
id = "switchyard/capability"
type = "llm_classifier"
mode = "capability"
classifier_target = "classifier"
strong_target = "strong"
weak_target = "weak"
base_threshold = 0.5
prompt = "CUSTOM CAPABILITY"
response_format_type = "json_object"

[routes.escalation]
id = "switchyard/escalation"
type = "llm_classifier"
mode = "escalation"
classifier_target = "classifier"
strong_target = "strong"
weak_target = "weak"
prompt = "CUSTOM ESCALATION"
response_format_type = "json_object"
escalation = {{ confirmations = 1 }}

[routes.stage]
id = "switchyard/stage"
type = "stage_router"
capable_target = "strong"
efficient_target = "weak"
picker = "efficient_first"
confidence_threshold = 1.0

[routes.stage.classifier]
target = "classifier"
base_threshold = 0.5
prompt = "CUSTOM STAGE"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    for (route, prompt_prefix, schema_field, json_object) in [
        (
            "switchyard/capability",
            "CUSTOM CAPABILITY",
            "p_solve",
            true,
        ),
        (
            "switchyard/escalation",
            "CUSTOM ESCALATION",
            "escalate",
            true,
        ),
        ("switchyard/stage", "CUSTOM STAGE", "p_solve", false),
    ] {
        upstream.calls.lock().await.clear();
        let response = send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": route,
                "messages": [{"role": "user", "content": "bounded task"}]
            })),
        )
        .await?;

        assert_eq!(response.status, StatusCode::OK);
        let calls = upstream.calls.lock().await;
        let judge_call = calls
            .iter()
            .find(|call| call["model"] == "model/classifier")
            .ok_or("classifier target was not called")?;
        let prompt = judge_call["messages"][0]["content"]
            .as_str()
            .ok_or("classifier prompt was not text")?;
        assert!(prompt.starts_with(prompt_prefix), "{route}: {prompt}");
        if json_object {
            assert_eq!(
                judge_call["response_format"],
                json!({"type": "json_object"}),
                "{route}: {judge_call}"
            );
            assert!(prompt.contains("JSON Schema"), "{route}: {prompt}");
            assert!(
                prompt.contains(&format!("\"{schema_field}\"")),
                "{route}: missing {schema_field} in {prompt}"
            );
        } else {
            assert!(
                judge_call["response_format"]["json_schema"]["schema"]["properties"]
                    .get(schema_field)
                    .is_some(),
                "{route}: missing {schema_field} in {judge_call}"
            );
        }
    }
    Ok(())
}

#[tokio::test]
async fn classifier_task_input_excludes_tool_results_across_request_formats() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"
max_retries = 0
[targets.judge]
id = "model/classifier"
llm_client = "upstream"
[targets.strong]
id = "model/strong"
llm_client = "upstream"
[targets.weak]
id = "model/weak"
llm_client = "upstream"
[routes.task]
id = "task"
type = "llm_classifier"
classifier_target = "judge"
strong_target = "strong"
weak_target = "weak"
base_threshold = 0.5
classify_trigger = "every_request"
[routes.window]
id = "window"
type = "llm_classifier"
classifier_target = "judge"
strong_target = "strong"
weak_target = "weak"
base_threshold = 0.5
classify_trigger = "every_request"
recent_turn_window = 1
"#,
        base_url = upstream.base_url
    ))?);
    let chat = json!({"messages": [
        {"role": "user", "content": "Read the file."},
        {"role": "assistant", "content": null, "tool_calls": [{
            "id": "call_read", "type": "function", "function": {"name": "read_file", "arguments": "{}"}
        }]},
        {"role": "tool", "tool_call_id": "call_read", "content": "File contents."}
    ]});
    for (route, endpoint, mut body) in [
        ("task", "/v1/chat/completions", chat.clone()),
        (
            "task",
            "/v1/messages",
            json!({"messages": [
                {"role": "user", "content": "Read the file."},
                {"role": "assistant", "content": [{"type": "tool_use", "id": "call_read", "name": "read_file", "input": {}}]},
                {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_read", "content": "File contents."}]}
            ]}),
        ),
        (
            "task",
            "/v1/responses",
            json!({"input": [
                {"role": "user", "content": "Read the file."},
                {"type": "function_call", "call_id": "call_read", "name": "read_file", "arguments": "{}"},
                {"type": "function_call_output", "call_id": "call_read", "output": "File contents."}
            ]}),
        ),
        ("window", "/v1/chat/completions", chat),
    ] {
        upstream.calls.lock().await.clear();
        body["model"] = json!(route);
        let response = send(&app, "POST", endpoint, Some(body)).await?;
        assert_eq!(response.status, StatusCode::OK, "{}", response.text()?);
        assert_eq!(
            response.headers["x-model-router-selected-model"], "model/weak",
            "{endpoint}"
        );
        let calls = upstream.calls.lock().await;
        assert_eq!(calls.len(), 2);
        let judge_roles: Vec<_> = calls[0]["messages"]
            .as_array()
            .ok_or("missing judge messages")?
            .iter()
            .map(|message| message["role"].clone())
            .collect();
        assert_eq!(
            judge_roles,
            if route == "task" {
                json!(["system", "user"])
            } else {
                json!(["system", "user", "assistant", "tool", "user"])
            }
            .as_array()
            .ok_or("missing expected roles")?
            .clone()
        );
        assert_eq!(calls[1]["messages"][1]["tool_calls"][0]["id"], "call_read");
        assert_eq!(calls[1]["messages"][2]["tool_call_id"], "call_read");
    }
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["classifier"]["total_requests"], 4);
    assert_eq!(
        stats["classifier"]["models"]["model/classifier"]["errors"],
        0
    );
    Ok(())
}

#[tokio::test]
async fn accepted_escalation_response_is_logged_once_as_the_final_answer() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/strong"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"
system_prompt = "strong answer prompt"

[targets.weak]
id = "model/weak"
llm_client = "upstream"
system_prompt = "weak answer prompt"

[routes.escalation]
id = "switchyard/escalation"
type = "llm_classifier"
mode = "escalation"
classifier_target = "classifier"
strong_target = "strong"
weak_target = "weak"
escalation = {{ confirmations = 1 }}
"#,
        base_url = upstream.base_url
    ))?
    .with_routing_log(temp_dir.path().join("routing.jsonl"))?;
    let app = build_switchyard_router(state);

    let response = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/escalation",
            "messages": [{"role": "user", "content": "bounded task"}]
        })),
        &[("x-switchyard-session-id", "accepted-escalation")],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(upstream.models().await, ["model/weak", "model/strong"]);
    let calls = upstream.calls.lock().await;
    assert!(has_system_prompt(&calls[0], "weak answer prompt"));
    assert!(!has_system_prompt(&calls[1], "strong answer prompt"));
    drop(calls);

    let stats = send(
        &app,
        "GET",
        "/v1/routing/session-stats?session_id=accepted-escalation",
        None,
    )
    .await?;
    assert_eq!(stats.status, StatusCode::OK);
    let stats = stats.json()?;
    assert_eq!(stats["total_calls"], 2);
    assert_eq!(stats["total_prompt_tokens"], 20);
    assert_eq!(stats["total_completion_tokens"], 4);
    assert_eq!(stats["models"]["model/weak"]["calls"], 1);
    assert_eq!(stats["models"]["model/strong"]["calls"], 1);

    let process_stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(process_stats["total_requests"], 1);
    assert_eq!(process_stats["models"]["model/weak"]["calls"], 1);
    assert_eq!(
        process_stats["models"]["model/weak"]["model_call_latency"]["count"],
        1
    );
    Ok(())
}

#[tokio::test]
async fn stage_classifier_can_request_json_object_output() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.classifier]
id = "model/classifier"
llm_client = "upstream"

[targets.strong]
id = "model/strong"
llm_client = "upstream"

[targets.weak]
id = "model/weak"
llm_client = "upstream"

[routes.stage]
id = "switchyard/stage"
type = "stage_router"
capable_target = "strong"
efficient_target = "weak"
picker = "efficient_first"
confidence_threshold = 1.0

[routes.stage.classifier]
target = "classifier"
base_threshold = 0.5
response_format_type = "json_object"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/stage",
            "messages": [{"role": "user", "content": "bounded task"}]
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let calls = upstream.calls.lock().await;
    let judge_call = calls
        .iter()
        .find(|call| call["model"] == "model/classifier")
        .ok_or("classifier target was not called")?;
    assert_eq!(
        judge_call["response_format"],
        json!({"type": "json_object"})
    );
    let prompt = judge_call["messages"][0]["content"]
        .as_str()
        .ok_or("classifier prompt was not text")?;
    assert!(prompt.contains("JSON Schema"), "{prompt}");
    assert!(prompt.contains("\"p_solve\""), "{prompt}");

    drop(calls);
    let invalid_response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "switchyard/stage",
            "messages": [{"role": "user", "content": "return a schema-invalid verdict"}]
        })),
    )
    .await?;
    assert_eq!(invalid_response.status, StatusCode::OK);
    assert_eq!(
        invalid_response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/weak")
    );
    Ok(())
}

#[tokio::test]
async fn model_bearing_auxiliary_endpoints_use_configured_route_targets() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.claude]
format = "anthropic_messages"
base_url = "{base_url}"

[llm_clients.responses]
format = "openai_responses"
base_url = "{base_url}"
extra_headers = {{ "x-configured-client" = "responses" }}

[targets.responses]
id = "real/responses-model"
llm_client = "responses"

[targets.strong]
id = "real/opus"
llm_client = "claude"
system_prompt = "completion instructions"

[targets.other]
id = "real/sonnet"
llm_client = "claude"

[routes.random]
id = "switchyard/random"
type = "random"
targets = ["responses", "other", "strong"]
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let count_tokens = send(
        &app,
        "POST",
        "/v1/messages/count_tokens",
        Some(json!({
            "model": "switchyard/random",
            "messages": [{"role": "user", "content": "hi"}]
        })),
    )
    .await?;
    assert_eq!(count_tokens.status, StatusCode::OK);
    assert_eq!(count_tokens.json()?["input_tokens"], 7);

    let input_tokens = send(
        &app,
        "POST",
        "/v1/responses/input_tokens",
        Some(json!({"model": "switchyard/random", "input": "count me"})),
    )
    .await?;
    assert_eq!(input_tokens.status, StatusCode::OK);
    assert_eq!(input_tokens.json()?["input_tokens"], 11);

    let compact = send(
        &app,
        "POST",
        "/v1/responses/compact",
        Some(json!({"model": "switchyard/random", "input": "compact me"})),
    )
    .await?;
    assert_eq!(compact.status, StatusCode::OK);
    assert_eq!(compact.json()?["id"], "resp_compacted");

    let calls = upstream.calls.lock().await;
    assert_eq!(calls.len(), 3);
    assert_eq!(calls[0]["model"], "real/opus");
    assert!(calls[0].get("system").is_none());
    assert_eq!(
        calls[1],
        json!({
            "path": "/v1/responses/input_tokens",
            "body": {"model": "real/responses-model", "input": "count me"},
            "configured_header": "responses"
        })
    );
    assert_eq!(
        calls[2],
        json!({
            "path": "/v1/responses/compact",
            "body": {"model": "real/responses-model", "input": "compact me"},
            "configured_header": "responses"
        })
    );
    drop(calls);

    let unsupported = random_state(&upstream.base_url, &[(ROUTE_MODEL, &["model/weak"])])?;
    let unsupported = build_switchyard_router(unsupported);
    for (path, body) in [
        (
            "/v1/messages/count_tokens",
            json!({"model": ROUTE_MODEL, "messages": [{"role": "user", "content": "hi"}]}),
        ),
        (
            "/v1/responses/input_tokens",
            json!({"model": ROUTE_MODEL, "input": "count me"}),
        ),
        (
            "/v1/responses/compact",
            json!({"model": ROUTE_MODEL, "input": "compact me"}),
        ),
    ] {
        let response = send(&unsupported, "POST", path, Some(body)).await?;
        assert_eq!(response.status, StatusCode::BAD_REQUEST, "{path}");
    }
    Ok(())
}

#[tokio::test]
async fn fallback_client_forwards_unmatched_requests_and_is_optional() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1
fallback_client = "fallback"

[llm_clients.fallback]
format = "openai_responses"
base_url = "{base_url}"
extra_headers = {{ "x-configured-secret" = "must-not-forward" }}

[llm_clients.routed]
format = "openai_chat"
base_url = "{base_url}"

[targets.weak]
id = "model/weak"
llm_client = "routed"

[routes.random]
id = "switchyard/random"
type = "passthrough"
target = "weak"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send_with_headers(
        &app,
        "POST",
        "/future/provider/endpoint?mode=raw",
        Some(json!({
            "model": "provider/model",
            "provider_field": {"nested": true}
        })),
        &[
            ("authorization", "Bearer caller-key"),
            ("connection", "keep-alive, x-remove-me"),
            ("keep-alive", "timeout=5"),
            ("x-remove-me", "remove"),
            ("x-end-to-end", "preserve"),
        ],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(response.json()?["input_tokens"], 7);
    assert!(!response.headers.contains_key("connection"));
    assert!(!response.headers.contains_key("x-upstream-hop"));
    assert_eq!(
        response
            .headers
            .get("x-end-to-end-response")
            .and_then(|value| value.to_str().ok()),
        Some("preserve")
    );
    let calls = upstream.calls.lock().await;
    assert_eq!(
        calls.as_slice(),
        &[json!({
            "body": {
                "model": "provider/model",
                "provider_field": {"nested": true}
            },
            "authorization": "Bearer caller-key",
            "end_to_end": "preserve",
            "configured_secret": false,
            "connection": false,
            "connection_nominated": false
        })]
    );
    drop(calls);

    let state = random_state(&upstream.base_url, &[(ROUTE_MODEL, &["model/weak"])])?;
    let app = build_switchyard_router(state);
    let response = send(&app, "POST", "/future/provider/endpoint", None).await?;
    assert_eq!(response.status, StatusCode::NOT_FOUND);
    Ok(())
}

#[tokio::test]
async fn transport_errors_hide_credential_bearing_upstream_urls() -> TestResult {
    const CANARY: &str = "CANARY_ADMIN_QUERY_KEY";

    let listener = TcpListener::bind("127.0.0.1:0").await?;
    let base_url = format!("http://{}/v1?key={CANARY}", listener.local_addr()?);
    drop(listener);

    let routed = build_switchyard_router(random_state(&base_url, &[(ROUTE_MODEL, &["model/a"])])?);
    let routed_response = send(
        &routed,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "hello"}]
        })),
    )
    .await?;

    let fallback = load_test_config(&format!(
        r#"
schema_version = 1
fallback_client = "upstream"

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.model]
id = "model/a"
llm_client = "upstream"

[routes.model]
id = "switchyard/model"
type = "passthrough"
target = "model"
"#
    ))?;
    let fallback = build_switchyard_router(fallback);
    let fallback_response = send(&fallback, "POST", "/unmatched", None).await?;

    for response in [routed_response, fallback_response] {
        assert_eq!(response.status, StatusCode::BAD_GATEWAY);
        let body = response.json()?;
        let message = body["error"]["message"].as_str().unwrap_or_default();
        assert!(
            !message.contains(CANARY),
            "credential leaked in {message:?}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn anthropic_client_forwards_oauth_when_configured() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.claude]
format = "anthropic_messages"
base_url = "{base_url}"
forward_auth = true
max_retries = 0

[targets.claude]
id = "claude-opus"
llm_client = "claude"

[routes.claude]
id = "switchyard/claude"
type = "passthrough"
target = "claude"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send_with_headers(
        &app,
        "POST",
        "/v1/messages",
        Some(json!({
            "model": "switchyard/claude",
            "max_tokens": 16,
            "messages": [{"role": "user", "content": "hello"}]
        })),
        &[
            ("authorization", "Bearer claude-oauth-token"),
            ("anthropic-beta", "oauth-2025-04-20,unsupported-beta"),
            ("chatgpt-account-id", "account-123"),
            ("x-openai-fedramp", "true"),
        ],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    let wrong_api = send_with_headers(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({"model": "switchyard/claude", "input": "hello"})),
        &[("authorization", "Bearer codex-login-token")],
    )
    .await?;
    assert_eq!(wrong_api.status, StatusCode::BAD_REQUEST);
    assert_eq!(upstream.calls.lock().await.len(), 1);

    Ok(())
}

#[tokio::test]
async fn responses_client_forwards_openai_login_when_configured() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.openai]
format = "openai_responses"
base_url = "{base_url}"
forward_auth = true
max_retries = 0

[targets.openai]
id = "gpt-codex"
llm_client = "openai"

[routes.openai]
id = "switchyard/codex"
type = "passthrough"
target = "openai"
"#,
        base_url = upstream.base_url
    ))?;
    let app = build_switchyard_router(state);

    let response = send_with_headers(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({"model": "switchyard/codex", "input": "hello"})),
        &[
            ("authorization", "Bearer codex-login-token"),
            ("chatgpt-account-id", "account-123"),
            ("x-openai-fedramp", "true"),
            ("x-api-key", "provider-api-key"),
            ("anthropic-beta", "provider-beta"),
        ],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    let redirect = send_with_headers(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({"model": "switchyard/codex", "input": "hello"})),
        &[
            ("authorization", "Bearer codex-login-token"),
            ("chatgpt-account-id", "account-123"),
            ("x-openai-fedramp", "true"),
            ("x-test-redirect", "1"),
        ],
    )
    .await?;
    assert_eq!(redirect.status, StatusCode::TEMPORARY_REDIRECT);
    assert_eq!(upstream.calls.lock().await.len(), 2);

    let echoed_auth = send_with_headers(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({"model": "switchyard/codex", "input": "hello"})),
        &[
            ("authorization", "Bearer codex-login-token"),
            ("x-test-echo-auth", "1"),
        ],
    )
    .await?;
    assert_eq!(echoed_auth.status, StatusCode::UNAUTHORIZED);
    let error = echoed_auth.text()?;
    assert!(error.contains("[REDACTED]"));
    assert!(!error.contains("codex-login-token"));

    Ok(())
}

#[tokio::test]
async fn routes_dispatch_and_discovery_endpoints_are_stable() -> TestResult {
    let (upstream, app) = test_app(&[
        ("switchyard/coding", &["model/code"]),
        ("switchyard/general", &["model/general"]),
    ])
    .await?;

    let health = send(&app, "GET", "/health", None).await?;
    assert_eq!(health.status, StatusCode::OK);
    assert_eq!(health.json()?, json!({"status": "ok"}));

    let models = send(&app, "GET", "/v1/models", None).await?;
    assert_eq!(models.status, StatusCode::OK);
    assert_eq!(
        models.json()?["model_pool"],
        json!(["switchyard/coding", "switchyard/general"])
    );

    let missing = send(&app, "GET", "/missing", None).await?;
    assert_eq!(missing.status, StatusCode::NOT_FOUND);
    assert_eq!(missing.json()?["error"]["code"], "endpoint_not_found");

    for (route_model, target_model) in [
        ("switchyard/general", "model/general"),
        ("switchyard/coding", "model/code"),
    ] {
        let response = send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": route_model,
                "messages": [{"role": "user", "content": "hi"}]
            })),
        )
        .await?;
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some(target_model)
        );
    }

    let calls = upstream.calls.lock().await;
    assert_eq!(calls[0]["model"], "model/general");
    assert_eq!(calls[1]["model"], "model/code");
    Ok(())
}

#[tokio::test]
async fn json_extractor_statuses_keep_api_specific_error_envelopes() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;

    for (content_type, expected_status) in [
        (Some("application/json"), StatusCode::BAD_REQUEST),
        (None, StatusCode::UNSUPPORTED_MEDIA_TYPE),
        (Some("text/plain"), StatusCode::UNSUPPORTED_MEDIA_TYPE),
    ] {
        let body = if expected_status == StatusCode::BAD_REQUEST {
            br#"{"model":"broken""#.to_vec()
        } else {
            br#"{"model":"valid-json"}"#.to_vec()
        };
        let response = send_raw_json(&app, "/v1/chat/completions", body, content_type).await?;
        assert_eq!(response.status, expected_status);
        let body = response.json()?;
        assert_eq!(body["error"]["type"], "invalid_request_error");
        assert_eq!(body["error"]["code"], "invalid_body");
    }

    let response = send_raw_json(
        &app,
        "/v1/chat/completions",
        vec![b' '; DEFAULT_MAX_REQUEST_BODY_BYTES + 1],
        Some("application/json"),
    )
    .await?;
    assert_eq!(response.status, StatusCode::PAYLOAD_TOO_LARGE);
    assert_eq!(response.json()?["error"]["code"], "invalid_body");

    for (body, content_type, expected_status, expected_type) in [
        (
            br#"{"model":"broken""#.as_slice(),
            Some("application/json"),
            StatusCode::BAD_REQUEST,
            "invalid_request_error",
        ),
        (
            br#"{"model":"valid-json"}"#.as_slice(),
            None,
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "api_error",
        ),
    ] {
        let response = send_raw_json(&app, "/v1/messages", body.to_vec(), content_type).await?;
        assert_eq!(response.status, expected_status);
        let body = response.json()?;
        assert_eq!(body["type"], "error");
        assert_eq!(body["error"]["type"], expected_type);
    }

    let response = send_raw_json(
        &app,
        "/v1/messages",
        vec![b' '; DEFAULT_MAX_REQUEST_BODY_BYTES + 1],
        Some("application/json"),
    )
    .await?;
    assert_eq!(response.status, StatusCode::PAYLOAD_TOO_LARGE);
    let body = response.json()?;
    assert_eq!(body["type"], "error");
    assert_eq!(body["error"]["type"], "request_too_large");
    Ok(())
}

#[tokio::test]
async fn models_endpoint_reports_declared_route_capabilities_and_null_when_undeclared() -> TestResult
{
    const CONFIG: &str = r#"
schema_version = 1

[llm_clients.primary]
format = "openai_chat"
base_url = "https://example.test/v1"

[targets.shared]
id = "nvidia/deepseek-ai/deepseek-v4-pro"
llm_client = "primary"

[routes.declared]
id = "declared"
type = "passthrough"
target = "shared"
context_window = 1000000
tool_calling = true
vision = true

[routes.restricted]
id = "restricted"
type = "passthrough"
target = "shared"
context_window = 262000
tool_calling = false
vision = false

[routes.undeclared]
id = "undeclared"
type = "passthrough"
target = "shared"
"#;
    let app = build_switchyard_router(load_test_config(CONFIG)?);
    let models = send(&app, "GET", "/v1/models?client_version=0.152.0", None).await?;
    assert_eq!(models.status, StatusCode::OK);
    let body = models.json()?;
    let data = body["data"].as_array().cloned().unwrap_or_default();
    let capabilities = data
        .iter()
        .filter_map(|entry| entry["id"].as_str().map(|id| (id, &entry["capabilities"])))
        .collect::<BTreeMap<_, _>>();

    assert_eq!(capabilities["declared"]["context_window"], json!(1_000_000));
    assert_eq!(capabilities["declared"]["tool_calling"], json!(true));
    assert_eq!(capabilities["restricted"]["context_window"], json!(262_000));
    assert_eq!(capabilities["restricted"]["tool_calling"], json!(false));
    assert_eq!(capabilities["undeclared"]["context_window"], json!(null));
    assert_eq!(capabilities["undeclared"]["tool_calling"], json!(null));

    assert_eq!(capabilities["declared"]["vision"], json!(true));
    assert_eq!(capabilities["restricted"]["vision"], json!(false));
    assert_eq!(capabilities["undeclared"]["vision"], json!(null));
    assert_eq!(body["models"], json!([]));

    Ok(())
}

// Build routes through the TOML loader to test disabled, enabled, and unset capabilities.
fn capability_app(base_url: &str, format: &str) -> TestResult<Router> {
    Ok(build_switchyard_router(load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.upstream]
format = "{format}"
base_url = "{base_url}"
[targets]
shared = {{ id = "model/efficient", llm_client = "upstream" }}
[routes]
restricted = {{ id = "restricted", type = "passthrough", target = "shared", vision = false, reasoning = false, tool_calling = false }}
enabled = {{ id = "enabled", type = "passthrough", target = "shared", vision = true, reasoning = true, tool_calling = true }}
undeclared = {{ id = "undeclared", type = "passthrough", target = "shared" }}
"#,
    ))?))
}

// Chat Completions, Responses, and Messages reject disabled inputs before dispatch.
// Allowed Responses input retains instructions and options after translation
// to Chat Completions.
#[tokio::test]
async fn disabled_route_capabilities_reject_requests_before_calling_upstream() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = capability_app(&upstream.base_url, "openai_chat")?;
    let cases = [
        (
            "/v1/chat/completions",
            "vision",
            json!({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "https://example.test/image.png"}}]}]}),
        ),
        (
            "/v1/messages",
            "vision",
            json!({"messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": "https://example.test/image.png"}}]}]}),
        ),
        (
            "/v1/responses",
            "vision",
            json!({"input": [{"role": "user", "content": [{"type": "input_image", "image_url": "https://example.test/image.png"}]}]}),
        ),
        (
            "/v1/chat/completions",
            "reasoning",
            json!({"messages": [{"role": "user", "content": "hello"}], "reasoning_effort": "high"}),
        ),
        (
            "/v1/messages",
            "reasoning",
            json!({"messages": [{"role": "user", "content": "hello"}], "thinking": {"type": "enabled", "budget_tokens": 1024}}),
        ),
        (
            "/v1/responses",
            "reasoning",
            json!({"input": "hello", "reasoning": {"summary": "auto"}}),
        ),
        (
            "/v1/chat/completions",
            "tool_calling",
            json!({"messages": [{"role": "user", "content": "hello"}], "tools": [{"type": "function", "function": {"name": "exec_command", "parameters": {"type": "object"}}}]}),
        ),
        (
            "/v1/messages",
            "tool_calling",
            json!({"messages": [{"role": "user", "content": "hello"}], "tools": [{"name": "exec_command", "input_schema": {"type": "object"}}]}),
        ),
        (
            "/v1/responses",
            "tool_calling",
            json!({"input": [{"type": "additional_tools", "tools": [{"type": "function", "name": "exec_command", "parameters": {"type": "object"}}]}, {"role": "user", "content": "hello"}]}),
        ),
    ];
    for (endpoint, capability, mut body) in cases {
        body["model"] = json!("restricted");
        let response = send(&app, "POST", endpoint, Some(body)).await?;
        assert_eq!(
            response.status,
            StatusCode::BAD_REQUEST,
            "{endpoint}: {capability}"
        );
        let error = response.json()?;
        assert_eq!(error["error"]["type"], "invalid_request_error");
        if endpoint == "/v1/messages" {
            assert_eq!(error["type"], "error");
        } else {
            assert_eq!(error["error"]["code"], "unsupported_capability");
        }
        assert!(
            error["error"]["message"]
                .as_str()
                .unwrap_or_default()
                .contains(&format!("{capability} = false"))
        );
    }
    assert!(upstream.calls.lock().await.is_empty());

    let body = json!({
        "model": "restricted", "instructions": "Keep the caller's instructions.", "input": "hello"
    });
    let response = send(&app, "POST", "/v1/responses", Some(body)).await?;
    assert_eq!(response.status, StatusCode::OK);
    for model in ["enabled", "undeclared"] {
        let response = send(&app, "POST", "/v1/responses", Some(json!({
            "model": model,
            "instructions": "Keep the caller's instructions.",
            "input": [{"role": "user", "content": [{"type": "input_image", "image_url": "https://example.test/image.png"}]}],
            "reasoning": {"effort": "high"},
            "tools": [{"type": "function", "name": "exec_command", "parameters": {"type": "object"}}]
        }))).await?;
        assert_eq!(response.status, StatusCode::OK);
    }
    let calls = upstream.calls.lock().await;
    assert_eq!(calls.len(), 3);
    assert!(
        calls
            .iter()
            .all(|call| has_system_prompt(call, "Keep the caller's instructions."))
    );
    for call in &calls[1..] {
        assert_eq!(call["reasoning_effort"], "high");
        assert_eq!(call["tools"][0]["function"]["name"], "exec_command");
        assert!(call["messages"].as_array().is_some_and(|messages| {
            messages
                .iter()
                .any(|message| message["content"][0]["type"] == "image_url")
        }));
    }
    Ok(())
}

// Approval replies can resume tool use without a tools field or a decoded tool call.
#[tokio::test]
async fn tool_approval_replies_follow_route_capabilities() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let base_url = format!("{}/buffered", upstream.base_url.trim_end_matches("/v1"));
    let app = capability_app(&base_url, "openai_responses")?;
    let input = json!([
        {"type": "mcp_approval_response", "approval_request_id": "approval_1", "approve": true}
    ]);
    for model in ["restricted", "enabled", "undeclared"] {
        let body = json!({"model": model, "input": input});
        let response = send(&app, "POST", "/v1/responses", Some(body)).await?;
        if model == "restricted" {
            assert_eq!(response.status, StatusCode::BAD_REQUEST);
            let error = response.json()?;
            assert_eq!(error["error"]["code"], "unsupported_capability");
            assert!(upstream.calls.lock().await.is_empty());
        } else {
            assert_eq!(response.status, StatusCode::OK);
        }
    }
    let calls = upstream.calls.lock().await;
    assert_eq!(calls.len(), 2);
    for call in calls.iter() {
        assert_eq!(call["input"], input);
    }
    Ok(())
}

// Tool results and blank user messages must not replace the classifier's task text.
#[tokio::test]
async fn subagent_tool_continuations_are_classified_on_every_request_across_apis() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"
[targets]
classifier = {{ id = "model/classifier", llm_client = "upstream" }}
strong = {{ id = "model/strong", llm_client = "upstream" }}
weak = {{ id = "model/weak", llm_client = "upstream" }}
[routes.agent]
id = "agent"
type = "passthrough"
target = "weak"
[routes.agent.subagents]
type = "llm_classifier"
mode = "custom"
classify_trigger = "every_request"
models = {{ judge = ["classifier"], capable = ["strong"], efficient = ["weak"], any = ["strong", "weak"] }}
default_target = "efficient"
prompt = "classify the delegated task"
response_schema = '''{{"type":"object","properties":{{"decision":{{"type":"object","properties":{{"target":{{"type":"string","enum":["capable","efficient"]}}}},"required":["target"],"additionalProperties":false}}}},"required":["decision"],"additionalProperties":false}}'''
[routes.agent.subagents.policy]
type = "target_selector"
selector = "/decision/target"
"#,
        base_url = upstream.base_url
    ))?);
    let headers = [
        ("x-claude-code-session-id", "root-session"),
        ("x-claude-code-agent-id", "child-agent"),
    ];
    for (path, key, mut body, tool_turn) in [
        (
            "/v1/chat/completions",
            "messages",
            json!({"model":"agent","messages":[
                {"role":"system","content":"child system instructions"},
                {"role":"user","content":"harness context"},
                {"role":"user","content":[{"type":"text","text":"injected context"},{"type":"text","text":"opening task: route to capable"}]}
            ]}),
            vec![
                json!({"role":"assistant","tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{}"}}]}),
                json!({"role":"tool","tool_call_id":"call_1","content":"tool output"}),
            ],
        ),
        (
            "/v1/messages",
            "messages",
            json!({"model":"agent","max_tokens":16,"system":"child system instructions","messages":[
                {"role":"user","content":"harness context"},
                {"role":"user","content":[{"type":"text","text":"injected context"},{"type":"text","text":"opening task: route to capable"}]}
            ]}),
            vec![
                json!({"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read_file","input":{}}]}),
                json!({"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"tool output"}]}),
            ],
        ),
        (
            "/v1/responses",
            "input",
            json!({"model":"agent","instructions":"child system instructions","input":[
                {"role":"user","content":"harness context"},
                {"role":"user","content":[{"type":"input_text","text":"injected context"},{"type":"input_text","text":"opening task: route to capable"}]}
            ]}),
            vec![
                json!({"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}),
                json!({"type":"function_call_output","call_id":"call_1","output":"tool output"}),
            ],
        ),
    ] {
        for (step, (additions, expected_prompt)) in [
            (vec![], "opening task: route to capable"),
            (tool_turn.clone(), "opening task: route to capable"),
            (
                vec![json!({"role":"user","content":" \n\t"})],
                "opening task: route to capable",
            ),
            (
                vec![json!({"role":"user","content":"continue task: route to capable"})],
                "continue task: route to capable",
            ),
        ]
        .into_iter()
        .enumerate()
        {
            body[key]
                .as_array_mut()
                .ok_or("missing request messages")?
                .extend(additions);
            let response =
                send_with_headers(&app, "POST", path, Some(body.clone()), &headers).await?;
            assert_eq!(response.status, StatusCode::OK);
            assert_eq!(
                response.headers["x-model-router-selected-model"],
                "model/strong"
            );
            let calls = upstream.calls.lock().await;
            let judge = &calls[calls.len() - 2];
            assert_eq!(judge["model"], "model/classifier");
            assert_eq!(
                judge["messages"],
                json!([
                    {"role":"system","content":"classify the delegated task"},
                    {"role":"user","content":expected_prompt}
                ])
            );
            let answer = calls.last().ok_or("missing answer request")?.to_string();
            for preserved in [
                "child system instructions",
                "harness context",
                "injected context",
                "opening task: route to capable",
                expected_prompt,
            ] {
                assert!(answer.contains(preserved));
            }
            if step > 0 {
                assert!(answer.contains("tool output"));
                assert!(answer.contains("call_1"));
            }
        }
        let mut text_free = body;
        text_free[key] = json!(tool_turn);
        let response = send_with_headers(&app, "POST", path, Some(text_free), &headers).await?;
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(
            response.headers["x-model-router-selected-model"],
            "model/weak"
        );
    }
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["classifier"]["total_requests"], 12);
    Ok(())
}

// Codex's structured kind takes precedence over the flat `collab_spawn` header:
// maintenance uses the parent classifier; delegated work uses the subagent route.
#[tokio::test]
async fn codex_maintenance_uses_the_parent_classifier_across_apis() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(load_test_config(&format!(
        r#"
schema_version = 1
[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"
[targets]
classifier = {{ id = "model/classifier", llm_client = "upstream" }}
strong = {{ id = "model/strong", llm_client = "upstream" }}
weak = {{ id = "model/weak", llm_client = "upstream" }}
[routes.agent]
id = "agent"
type = "composite"
classifier = {{ target = "classifier", base_threshold = 0.5, classify_trigger = "user_turn" }}
stage = {{ capable_target = "strong", efficient_target = "weak", confidence_threshold = 0.3 }}
subagents = {{ type = "passthrough", target = "strong" }}
"#,
        base_url = upstream.base_url
    ))?);
    let cases = [
        (Some("compact"), None, "model/weak"),
        (Some("review"), None, "model/strong"),
        (Some("thread_spawn"), None, "model/strong"),
        (Some("collab_spawn"), None, "model/strong"),
        (Some("unknown"), None, "model/weak"),
        (Some("memory_consolidation"), None, "model/weak"),
        (None, None, "model/strong"),
        (Some("review"), Some("false"), "model/weak"),
        (Some("compact"), Some("true"), "model/weak"),
    ];
    for (path, body, cases) in [
        (
            "/v1/chat/completions",
            json!({"model":"agent","messages":[{"role":"user","content":"hi"}]}),
            &cases[..],
        ),
        (
            "/v1/messages",
            json!({"model":"agent","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}),
            &cases[..3],
        ),
        (
            "/v1/responses",
            json!({"model":"agent","input":"hi"}),
            &cases[..3],
        ),
    ] {
        for (kind, explicit, expected) in cases {
            let mut headers = Vec::new();
            let mut metadata = json!({
                "thread_id": "child",
                "parent_thread_id": "root",
                "thread_source": "subagent",
            });
            if let Some(kind) = kind {
                metadata["subagent_kind"] = json!(kind);
                headers.push(("x-openai-subagent", "collab_spawn"));
            }
            let metadata = metadata.to_string();
            headers.push(("x-codex-turn-metadata", metadata.as_str()));
            if let Some(explicit) = explicit {
                headers.push(("x-switchyard-is-subagent", explicit));
            }
            let response =
                send_with_headers(&app, "POST", path, Some(body.clone()), &headers).await?;
            assert_eq!(response.status, StatusCode::OK);
            assert_eq!(response.headers["x-model-router-selected-model"], *expected);
        }
    }
    let models = upstream.models().await;
    for (model, expected) in [
        ("model/classifier", 7),
        ("model/weak", 7),
        ("model/strong", 8),
    ] {
        assert_eq!(
            models.iter().filter(|actual| *actual == model).count(),
            expected
        );
    }
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["classifier"]["total_requests"], 7);
    Ok(())
}

#[tokio::test]
async fn all_inbound_formats_run_libsy_and_return_the_caller_format() -> TestResult {
    let (upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;

    let cases = [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "hi"}]
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "max_tokens": 16,
                "messages": [{"role": "user", "content": "hi"}]
            }),
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "hi"}),
        ),
    ];

    let mut responses = Vec::new();
    for (path, body) in cases {
        responses.push(send(&app, "POST", path, Some(body)).await?);
    }

    assert!(
        responses
            .iter()
            .all(|response| response.status == StatusCode::OK)
    );
    assert_eq!(
        responses[0].json()?["choices"][0]["message"]["content"],
        "ok"
    );
    assert_eq!(responses[1].json()?["content"][0]["text"], "ok");
    assert_eq!(
        responses[2].json()?["output"][0]["content"][0]["text"],
        "ok"
    );
    assert_eq!(responses[0].json()?["usage"]["prompt_tokens"], 10);
    assert_eq!(
        responses[0].json()?["usage"]["prompt_tokens_details"]["cached_tokens"],
        7
    );
    assert_eq!(responses[1].json()?["usage"]["input_tokens"], 3);
    assert_eq!(responses[1].json()?["usage"]["cache_read_input_tokens"], 7);
    assert_eq!(responses[2].json()?["usage"]["input_tokens"], 10);
    assert_eq!(
        responses[2].json()?["usage"]["input_tokens_details"]["cached_tokens"],
        7
    );
    for response in &responses {
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some("model/a")
        );
        // The body names the model that answered, not the route id the caller
        // addressed, so it agrees with the routing header above.
        assert_eq!(response.json()?["model"], "model/a");
    }

    let calls = upstream.calls.lock().await;
    assert_eq!(calls.len(), 3);
    assert!(calls.iter().all(|call| call["model"] == "model/a"));
    Ok(())
}

// Normalized metadata is authoritative when both ID forms are present;
// legacy-only callers remain supported for backward compatibility.
#[tokio::test]
async fn routing_log_prefers_canonical_and_preserves_legacy_fallback() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let log_path = temp_dir.path().join("routing.jsonl");
    let state = random_state(&upstream.base_url, &[(ROUTE_MODEL, &["model/a"])])?
        .with_routing_log(&log_path)?;
    let app = build_switchyard_router(state);

    let request = HttpRequest::builder()
        .method("POST")
        .uri("/v1/chat/completions")
        .header("content-type", "application/json")
        .header("x-switchyard-session-id", "canonical-session")
        .header("proxy_x_session_id", "legacy-session")
        .header("x-switchyard-origin", r#"custom-agent/"quoted"\path"#)
        .body(Body::from(serde_json::to_vec(&json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "hello"}]
        }))?))?;
    let response = app.clone().oneshot(request).await?;
    assert_eq!(response.status(), StatusCode::OK);

    let stats = send(
        &app,
        "GET",
        "/v1/routing/session-stats?session_id=canonical-session",
        None,
    )
    .await?;
    assert_eq!(stats.status, StatusCode::OK);
    let stats = stats.json()?;
    assert_eq!(stats["total_calls"], 1);
    assert_eq!(stats["total_prompt_tokens"], 10);
    assert_eq!(stats["total_cached_tokens"], 7);
    assert_eq!(stats["models"]["model/a"]["completion_tokens"], 2);

    let legacy = send(
        &app,
        "GET",
        "/v1/routing/session-stats?session_id=legacy-session",
        None,
    )
    .await?;
    assert_eq!(legacy.status, StatusCode::NOT_FOUND);

    let legacy_only = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "hello"}]
        })),
        &[("proxy_x_session_id", "legacy-only-session")],
    )
    .await?;
    assert_eq!(legacy_only.status, StatusCode::OK);

    let legacy_stats = send(
        &app,
        "GET",
        "/v1/routing/session-stats?session_id=legacy-only-session",
        None,
    )
    .await?;
    assert_eq!(legacy_stats.status, StatusCode::OK);
    assert_eq!(legacy_stats.json()?["total_calls"], 1);

    let records = std::fs::read_to_string(log_path)?;
    let first: Value =
        serde_json::from_str(records.lines().next().ok_or("routing log was empty")?)?;
    assert_eq!(first["session_id"], "canonical-session");
    assert_eq!(first["origin"], r#"custom-agent/"quoted"\path"#);
    let second: Value = serde_json::from_str(records.lines().nth(1).ok_or("missing record")?)?;
    assert_eq!(second.get("origin"), Some(&Value::Null));
    assert!(
        first["ts"]
            .as_str()
            .is_some_and(|value| value.ends_with('Z'))
    );
    Ok(())
}

/// Two routes serving one model must remain distinguishable in the durable accounting record.
#[tokio::test]
async fn routing_log_attributes_shared_models_to_the_requested_route() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let log_path = temp_dir.path().join("routing.jsonl");
    let state = load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.shared]
id = "model/shared"
llm_client = "upstream"

[targets.capable]
id = "model/capable"
llm_client = "upstream"

[routes.passthrough]
id = "route/passthrough"
type = "passthrough"
target = "shared"

[routes.stage]
id = "route/stage"
type = "stage_router"
capable_target = "capable"
efficient_target = "shared"
picker = "efficient_first"
confidence_threshold = 1.0
"#,
        base_url = upstream.base_url
    ))?
    .with_routing_log(&log_path)?;
    let app = build_switchyard_router(state);

    for route_id in ["route/passthrough", "route/stage"] {
        let response = send(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(json!({
                "model": route_id,
                "messages": [{"role": "user", "content": "hello"}]
            })),
        )
        .await?;
        assert_eq!(response.status, StatusCode::OK, "{route_id}");
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some("model/shared"),
            "{route_id}"
        );
    }

    let records = std::fs::read_to_string(&log_path)?
        .lines()
        .map(serde_json::from_str::<Value>)
        .collect::<Result<Vec<_>, _>>()?;
    assert_eq!(records.len(), 2);
    assert_eq!(records[0]["route_id"], "route/passthrough");
    assert_eq!(records[0]["algorithm"], "passthrough");
    assert_eq!(records[0]["model"], "model/shared");
    assert_eq!(records[1]["route_id"], "route/stage");
    assert_eq!(records[1]["algorithm"], "stage_router");
    assert_eq!(records[1]["model"], "model/shared");
    Ok(())
}

#[tokio::test]
async fn routing_log_keeps_the_canonical_session_id_until_a_stream_drains() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let log_path = temp_dir.path().join("routing.jsonl");
    let state = random_state(&upstream.base_url, &[(ROUTE_MODEL, &["model/a"])])?
        .with_routing_log(&log_path)?;
    let app = build_switchyard_router(state);

    // `send_with_headers` collects the response body, so the stream wrapper reaches
    // its terminal usage record before the stats query runs.
    let response = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "hello"}],
            "stream": true
        })),
        &[
            ("x-switchyard-session-id", "streaming-session"),
            ("x-switchyard-origin", "codex-cli"),
        ],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    assert!(response.text()?.contains("data: [DONE]"));

    let stats = send(
        &app,
        "GET",
        "/v1/routing/session-stats?session_id=streaming-session",
        None,
    )
    .await?;
    assert_eq!(stats.status, StatusCode::OK);
    let stats = stats.json()?;
    assert_eq!(stats["total_calls"], 1);
    assert_eq!(stats["total_prompt_tokens"], 12);
    assert_eq!(stats["total_cached_tokens"], 7);
    assert_eq!(stats["total_cache_creation_tokens"], 2);
    assert_eq!(stats["total_completion_tokens"], 5);

    let record: Value = serde_json::from_str(&std::fs::read_to_string(log_path)?)?;
    assert_eq!(record["route_id"], ROUTE_MODEL);
    assert_eq!(record["algorithm"], "random");
    assert_eq!(record["origin"], "codex-cli");
    Ok(())
}

#[tokio::test]
async fn random_zero_weight_target_is_not_advertised_or_called() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(weighted_random_state(&upstream.base_url, [1, 0])?);
    let response = send(
        &app,
        "POST",
        "/v1/decision",
        Some(json!({
            "input_format": "openai_chat",
            "request": {
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "unavailable"}]
            }
        })),
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    let decision = response.json()?;
    assert_eq!(decision["selected"]["target"], "first");
    assert_eq!(decision["fallbacks"], json!([]));
    assert!(upstream.models().await.is_empty());

    for (path, body) in [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "unavailable"}]
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "max_tokens": 16,
                "messages": [{"role": "user", "content": "unavailable"}]
            }),
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "unavailable"}),
        ),
    ] {
        upstream.calls.lock().await.clear();
        let response = send(&app, "POST", path, Some(body)).await?;
        assert_eq!(response.status, StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(upstream.models().await, ["model/weak"]);
    }
    Ok(())
}

#[tokio::test]
async fn unavailable_target_fails_over_across_endpoints_and_stops_when_exhausted() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let log_path = temp_dir.path().join("routing.jsonl");
    // The fixed seed selects `first` for these requests while keeping `second` enabled.
    let state =
        weighted_random_state(&upstream.base_url, [1000, 1])?.with_routing_log(&log_path)?;
    let app = build_switchyard_router(state);
    let cases = [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "unavailable"}]
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "max_tokens": 16,
                "messages": [{"role": "user", "content": "unavailable"}]
            }),
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "unavailable"}),
        ),
    ];

    for (path, body) in cases {
        let previous_call_count = upstream.calls.lock().await.len();
        let response = send(&app, "POST", path, Some(body)).await?;
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(
            response
                .headers
                .get("x-model-router-selected-model")
                .and_then(|value| value.to_str().ok()),
            Some("model/strong")
        );
        assert_eq!(response.json()?["model"], "model/strong");
        let calls = upstream.calls.lock().await;
        let candidate_calls = &calls[previous_call_count..];
        assert_eq!(
            candidate_calls
                .iter()
                .map(|call| call["model"].as_str().unwrap_or(""))
                .collect::<Vec<_>>(),
            ["model/weak", "model/strong"]
        );
        assert!(has_system_prompt(&candidate_calls[0], "weak answer prompt"));
        assert!(has_system_prompt(
            &candidate_calls[1],
            "strong answer prompt"
        ));
        assert!(!has_system_prompt(
            &candidate_calls[1],
            "weak answer prompt"
        ));
    }

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    // Fallback causes are logged rather than accumulated in the legacy stats counters.
    assert_eq!(stats["routing_fallbacks"]["unavailable"], 0);
    assert_eq!(stats["routing_fallbacks"]["context_window"], 0);
    assert_eq!(stats["models"]["model/strong"]["calls"], 3);
    assert_eq!(stats["models"]["model/weak"]["errors"], 3);

    let records = std::fs::read_to_string(&log_path)?;
    let records = records
        .lines()
        .map(serde_json::from_str::<Value>)
        .collect::<Result<Vec<_>, _>>()?;
    assert_eq!(records.len(), 3);
    assert!(records.iter().all(|record| {
        record["model"] == "model/strong" && record.get("fallback_reason").is_none()
    }));

    let previous_call_count = upstream.calls.lock().await.len();
    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "all-unavailable"}]
        })),
    )
    .await?;
    assert_eq!(response.status, StatusCode::SERVICE_UNAVAILABLE);
    let error = response.json()?;
    assert_eq!(error["error"]["type"], "upstream_error");
    assert_eq!(error["error"]["code"], "upstream_error");
    let calls = upstream.calls.lock().await;
    assert_eq!(
        calls[previous_call_count..]
            .iter()
            .map(|call| call["model"].as_str().unwrap_or(""))
            .collect::<Vec<_>>(),
        ["model/weak", "model/strong"]
    );
    Ok(())
}

#[tokio::test]
async fn streaming_response_is_framed_for_the_inbound_api() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "hi"}],
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert!(response.text()?.contains("hello"));
    assert!(response.text()?.contains("data: [DONE]"));
    Ok(())
}

// SWITCH-922: every streaming codec must report the routed target, not the route
// id the caller addressed — the route id is meaningless to anything reading the
// trajectory (a Bench UI, a spend log, the client's own display).
#[tokio::test]
async fn streamed_response_model_names_the_served_model_not_the_route() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;

    // Each case names the JSON pointer to the model on that format's first event.
    let cases = [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "hi"}],
                "stream": true
            }),
            vec!["model"],
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "max_tokens": 16,
                "messages": [{"role": "user", "content": "hi"}],
                "stream": true
            }),
            vec!["message", "model"],
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "hi", "stream": true}),
            vec!["response", "model"],
        ),
    ];

    for (path, body, pointer) in cases {
        let response = send(&app, "POST", path, Some(body)).await?;
        assert_eq!(response.status, StatusCode::OK, "{path}");

        let first = first_sse_event(response.text()?)
            .ok_or_else(|| format!("{path} produced no SSE data frames"))?;
        let model = pointer
            .iter()
            .try_fold(&first, |value, key| value.get(key))
            .and_then(Value::as_str);
        assert_eq!(model, Some("model/a"), "{path}");
    }
    Ok(())
}

// Returns the first `data:` frame of an SSE body as JSON, skipping `[DONE]`.
fn first_sse_event(body: &str) -> Option<Value> {
    body.lines()
        .filter_map(|line| line.strip_prefix("data: "))
        .filter(|data| *data != "[DONE]")
        .find_map(|data| serde_json::from_str(data).ok())
}

#[tokio::test]
async fn streaming_success_records_only_final_usage_and_one_latency() -> TestResult {
    const MODEL: &str = "model/stream-success";
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &[MODEL])]).await?;
    let before = send(&app, "GET", "/metrics", None).await?;
    let before = before.text()?;

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "stream-success"}],
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_in_order(
        response.text()?,
        &[
            "hello",
            "-partial",
            "-final",
            "\"finish_reason\":\"stop\"",
            "[DONE]",
        ],
    );

    let after = send(&app, "GET", "/metrics", None).await?;
    let after = after.text()?;
    for (name, expected_delta) in [
        ("switchyard_prompt_tokens_total", 12.0),
        ("switchyard_completion_tokens_total", 5.0),
        ("switchyard_cached_tokens_total", 7.0),
        ("switchyard_cache_creation_tokens_total", 2.0),
        ("switchyard_reasoning_tokens_total", 3.0),
        ("switchyard_total_latency_ms_count", 1.0),
    ] {
        assert_eq!(
            metric_delta(before, after, name, &[("model", MODEL)]),
            Some(expected_delta),
            "unexpected delta for {name}"
        );
    }
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["total_requests"], 1);
    assert_eq!(
        stats["total_tokens"],
        json!({
            "prompt": 12, "completion": 5, "cached": 7,
            "cache_creation": 2, "reasoning": 3, "total": 17
        })
    );
    assert_eq!(stats["models"][MODEL]["model_call_latency"]["count"], 1);
    assert_eq!(stats["models"][MODEL]["total_latency"]["count"], 1);
    Ok(())
}

#[tokio::test]
// A terminal stream failure records errors without usage or terminal latency.
async fn streaming_error_records_error_without_usage_or_latency() -> TestResult {
    const MODEL: &str = "model/stream-error";
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &[MODEL])]).await?;
    let before = send(&app, "GET", "/metrics", None).await?;
    let before = before.text()?;

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "stream-error"}],
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    assert_in_order(
        response.text()?,
        &["before", "still here", "upstream stream failed"],
    );

    let after = send(&app, "GET", "/metrics", None).await?;
    let after = after.text()?;
    for name in [
        "switchyard_requests_total",
        "switchyard_model_call_latency_ms_count",
        "switchyard_prompt_tokens_total",
        "switchyard_completion_tokens_total",
        "switchyard_cached_tokens_total",
        "switchyard_cache_creation_tokens_total",
        "switchyard_reasoning_tokens_total",
        "switchyard_total_latency_ms_count",
    ] {
        assert_eq!(
            metric_value(after, name, &[("model", MODEL)]),
            metric_value(before, name, &[("model", MODEL)]),
            "{name} changed after a failed stream"
        );
    }
    assert_eq!(
        metric_delta(
            before,
            after,
            "switchyard_errors_total",
            &[("model", MODEL)]
        ),
        Some(1.0)
    );
    assert!(metric_delta(before, after, "switchyard_total_errors", &[]).unwrap_or_default() >= 1.0);
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["total_requests"], 1);
    assert_eq!(stats["total_errors"], 1);
    assert_eq!(stats["total_tokens"], empty_token_totals());
    assert_eq!(stats["models"][MODEL]["calls"], 1);
    assert_eq!(stats["models"][MODEL]["errors"], 1);
    assert_eq!(stats["models"][MODEL]["total_latency"]["count"], 0);
    assert_eq!(stats["routing_overhead"]["count"], 1);
    Ok(())
}

#[tokio::test]
async fn responses_stream_error_does_not_emit_success_terminal_events() -> TestResult {
    // A distinct target keeps this test's error-counter increments off the shared
    // model/stream-error metric that streaming_error_records_... asserts an exact delta on.
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/responses-stream-error"])]).await?;

    let response = send(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({
            "model": ROUTE_MODEL,
            "input": "stream-error",
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let body = response.text()?;
    assert_in_order(body, &["before", "upstream stream failed"]);
    for event_type in [
        "response.output_text.done",
        "response.content_part.done",
        "response.output_item.done",
        "response.completed",
    ] {
        assert!(
            !body.contains(event_type),
            "{event_type} followed an upstream stream error"
        );
    }
    Ok(())
}

#[tokio::test]
async fn chat_stream_error_does_not_emit_success_terminal_chunk() -> TestResult {
    // A distinct target keeps this test's error-counter increments off the shared
    // model/stream-error metric that streaming_error_records_... asserts an exact delta on.
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/chat-stream-error"])]).await?;

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "stream-error"}],
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let body = response.text()?;
    assert_in_order(body, &["before", "still here", "upstream stream failed"]);
    // The finalizer must not synthesize a `finish_reason: stop` completion chunk after the error.
    let after_error = body
        .split_once("upstream stream failed")
        .map(|(_, rest)| rest)
        .unwrap_or_default();
    assert!(
        !after_error.contains(r#""finish_reason":"stop""#),
        "a finish_reason=stop chunk followed an upstream stream error:\n{body}"
    );
    // `[DONE]` is the Chat success sentinel: an SDK client stops there and keeps the
    // truncated turn as a completed answer, so a failed stream must not emit it.
    assert!(
        !after_error.contains("[DONE]"),
        "a [DONE] success sentinel followed an upstream stream error:\n{body}"
    );
    Ok(())
}

#[tokio::test]
async fn anthropic_stream_error_does_not_emit_success_terminal_events() -> TestResult {
    // A distinct target keeps this test's error-counter increments off the shared
    // model/stream-error metric that streaming_error_records_... asserts an exact delta on.
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/anthropic-stream-error"])]).await?;

    let response = send(
        &app,
        "POST",
        "/v1/messages",
        Some(json!({
            "model": ROUTE_MODEL,
            "messages": [{"role": "user", "content": "stream-error"}],
            "max_tokens": 16,
            "stream": true
        })),
    )
    .await?;

    assert_eq!(response.status, StatusCode::OK);
    let body = response.text()?;
    assert_in_order(body, &["before", "upstream stream failed"]);
    // The finalizer must not close the turn with message_delta/message_stop after the error.
    let after_error = body
        .split_once("upstream stream failed")
        .map(|(_, rest)| rest)
        .unwrap_or_default();
    for event_type in ["message_delta", "message_stop"] {
        assert!(
            !after_error.contains(event_type),
            "{event_type} followed an upstream stream error:\n{body}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn request_and_upstream_errors_use_the_inbound_wire_format() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;

    let unknown = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({
            "model": "other",
            "messages": [{"role": "user", "content": "hi"}]
        })),
    )
    .await?;
    assert_eq!(unknown.status, StatusCode::NOT_FOUND);
    assert_eq!(unknown.json()?["error"]["code"], "model_not_found");

    let missing_model = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(json!({"messages": [{"role": "user", "content": "hi"}]})),
    )
    .await?;
    assert_eq!(missing_model.status, StatusCode::BAD_REQUEST);
    assert_eq!(
        missing_model.json()?["error"]["code"],
        "invalid_request_error"
    );

    let upstream_cases = [
        (
            "/v1/chat/completions",
            json!({
                "model": ROUTE_MODEL,
                "messages": [{"role": "user", "content": "auth-fail"}]
            }),
            json!({
                "error": {
                    "message": "upstream authentication failed",
                    "type": "upstream_error",
                    "code": "upstream_error"
                }
            }),
        ),
        (
            "/v1/responses",
            json!({"model": ROUTE_MODEL, "input": "auth-fail"}),
            json!({
                "error": {
                    "message": "upstream authentication failed",
                    "type": "upstream_error",
                    "code": "upstream_error"
                }
            }),
        ),
        (
            "/v1/messages",
            json!({
                "model": ROUTE_MODEL,
                "max_tokens": 64,
                "messages": [{"role": "user", "content": "auth-fail"}]
            }),
            json!({
                "type": "error",
                "error": {
                    "type": "authentication_error",
                    "message": "upstream authentication failed"
                }
            }),
        ),
    ];
    for (path, body, expected) in upstream_cases {
        let response = send(&app, "POST", path, Some(body)).await?;
        assert_eq!(response.status, StatusCode::UNAUTHORIZED, "{path}");
        assert_eq!(response.json()?, expected, "{path}");
    }

    let anthropic_unknown = send(
        &app,
        "POST",
        "/v1/messages",
        Some(json!({
            "model": "other",
            "max_tokens": 64,
            "messages": [{"role": "user", "content": "hi"}]
        })),
    )
    .await?;
    assert_eq!(anthropic_unknown.status, StatusCode::NOT_FOUND);
    assert_eq!(
        anthropic_unknown.json()?,
        json!({
            "type": "error",
            "error": {
                "type": "not_found_error",
                "message": "No route registered for model other"
            }
        })
    );
    Ok(())
}

/// A `type = "advisor"` deployment: gated executor + reviewer on one mock upstream.
fn advisor_state(base_url: &str) -> TestResult<ServerState> {
    load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[targets.executor]
id = "model/executor"
llm_client = "upstream"
system_prompt = "executor answer prompt"

[targets.advisor]
id = "model/advisor"
llm_client = "upstream"
system_prompt = "advisor target prompt"

[routes.gated]
id = "switchyard/advisor"
type = "advisor"
executor_target = "executor"
advisor_target = "advisor"
"#,
    ))
}

fn advisor_chat_body(prompt: &str) -> Value {
    json!({
        "model": "switchyard/advisor",
        "messages": [{"role": "user", "content": prompt}]
    })
}

#[tokio::test]
async fn advisor_route_approve_flow_and_stats() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(advisor_state(&upstream.base_url)?);

    let response = send(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(advisor_chat_body("hi")),
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(response.json()?["choices"][0]["message"]["content"], "ok");
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/executor")
    );
    // Executor turn first, then the review consult.
    assert_eq!(upstream.models().await, ["model/executor", "model/advisor"]);
    let calls = upstream.calls.lock().await;
    assert!(has_system_prompt(&calls[0], "executor answer prompt"));
    assert!(!has_system_prompt(&calls[1], "advisor target prompt"));
    drop(calls);

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(stats["models"]["model/executor"]["calls"], 1);
    // The consult lands in the classifier bucket with its usage.
    assert_eq!(stats["classifier"]["models"]["model/advisor"]["calls"], 1);
    assert_eq!(stats["classifier"]["total_tokens"]["prompt"], 40);
    Ok(())
}

#[tokio::test]
async fn advisor_route_budget_scoped_by_proxy_header() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(advisor_state(&upstream.base_url)?);

    for (session, expected_consults) in [("eval-a", 1), ("eval-a", 1), ("eval-b", 2)] {
        let response = send_with_headers(
            &app,
            "POST",
            "/v1/chat/completions",
            Some(advisor_chat_body("hi")),
            &[("proxy_x_session_id", session)],
        )
        .await?;
        assert_eq!(response.status, StatusCode::OK);
        let consults = upstream
            .models()
            .await
            .iter()
            .filter(|model| *model == "model/advisor")
            .count();
        assert_eq!(consults, expected_consults, "session {session}");
    }
    Ok(())
}

#[tokio::test]
async fn advisor_route_streaming_approval_replays_provider_events() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(advisor_state(&upstream.base_url)?);

    let mut body = advisor_chat_body("hi");
    body["stream"] = json!(true);
    let response = send(&app, "POST", "/v1/chat/completions", Some(body)).await?;
    assert_eq!(response.status, StatusCode::OK);
    // The gate buffered the executor stream for the review, then replayed the
    // provider events verbatim.
    assert_eq!(upstream.models().await, ["model/executor", "model/advisor"]);
    let text = response.text()?;
    let events: Vec<Value> = text
        .lines()
        .filter_map(|line| line.strip_prefix("data: "))
        .filter(|data| *data != "[DONE]")
        .map(serde_json::from_str)
        .collect::<Result<_, _>>()?;
    assert_eq!(events.len(), 5);
    assert_eq!(events[1]["choices"][0]["delta"]["content"], "hello");
    assert_eq!(events[2]["choices"][0]["delta"]["content"], "-partial");
    assert_eq!(events[3]["choices"][0]["delta"]["content"], "-final");
    // Provider-specific usage detail rides through untouched.
    assert_eq!(
        events[3]["usage"]["prompt_tokens_details"]["cache_creation_tokens"],
        2
    );
    assert_eq!(events[4]["choices"][0]["finish_reason"], "stop");
    assert!(text.trim_end().ends_with("data: [DONE]"));
    Ok(())
}

#[tokio::test]
async fn advisor_route_routing_log_records_classifier_tier() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let temp_dir = tempfile::tempdir()?;
    let log_path = temp_dir.path().join("routing.jsonl");
    let state = advisor_state(&upstream.base_url)?.with_routing_log(&log_path)?;
    let app = build_switchyard_router(state);

    let response = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(advisor_chat_body("hi")),
        &[
            ("proxy_x_session_id", "session-1"),
            ("x-switchyard-origin", "custom-agent"),
        ],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    let records: Vec<Value> = std::fs::read_to_string(&log_path)?
        .lines()
        .map(serde_json::from_str)
        .collect::<Result<_, _>>()?;
    // The consult is appended under the shared judge tier; the served turn is
    // the terminal answer row. The discarded-turn row does not exist in v1 —
    // its tokens live in the advisor_gate stats block instead.
    assert_eq!(records.len(), 2);
    assert!(
        records
            .iter()
            .all(|record| record["origin"] == "custom-agent")
    );
    let consult = records
        .iter()
        .find(|record| record["model"] == "model/advisor")
        .ok_or("consult row present")?;
    assert_eq!(consult["tier"], "classifier");
    assert_eq!(consult["route_id"], "switchyard/advisor");
    assert_eq!(consult["algorithm"], "advisor_gate");
    assert_eq!(consult["session_id"], "session-1");
    assert_eq!(consult["prompt_tokens"], 40);
    Ok(())
}

/// An advisor deployment whose reviewer client never retries, so a down
/// advisor hits fail-open after a single attempt (the documented deployment
/// posture for the advisor tier).
fn advisor_state_no_retry(base_url: &str) -> TestResult<ServerState> {
    load_test_config(&format!(
        r#"
schema_version = 1

[llm_clients.upstream]
format = "openai_chat"
base_url = "{base_url}"

[llm_clients.reviewer]
format = "openai_chat"
base_url = "{base_url}"
max_retries = 0

[targets.executor]
id = "model/executor"
llm_client = "upstream"

[targets.advisor]
id = "model/advisor"
llm_client = "reviewer"

[routes.gated]
id = "switchyard/advisor"
type = "advisor"
executor_target = "executor"
advisor_target = "advisor"
"#,
    ))
}

fn gate_count(stats: &Value, path: &[&str]) -> u64 {
    let mut value = &stats["algorithm_stats"]["advisor_gate"];
    for key in path {
        value = &value[*key];
    }
    value.as_u64().unwrap_or(0)
}

// REDO mechanics, fail-open, and the /v1/stats advisor_gate projection in one
// sequential test: the OpenTelemetry meter behind algorithm_stats is
// process-global, so this is the only test that emits redo / consult-failure
// metrics and the only one that may assert their exact counts.
#[tokio::test]
async fn advisor_route_redo_client_error_and_stats_projection() -> TestResult {
    let upstream = MockUpstream::start().await?;
    let app = build_switchyard_router(advisor_state_no_retry(&upstream.base_url)?);
    let before = send(&app, "GET", "/v1/stats", None).await?.json()?;

    // REDO: the gated turn is discarded, the advisor plan is fed back, and
    // the executor continues. Each flow gets its own budget scope so the
    // second one is still reviewable.
    let response = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(advisor_chat_body("please-redo")),
        &[("proxy_x_session_id", "redo-flow")],
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(response.json()?["choices"][0]["message"]["content"], "ok");
    assert_eq!(
        upstream.models().await,
        ["model/executor", "model/advisor", "model/executor"]
    );
    let calls = upstream.calls.lock().await;
    let redo_messages = calls[2]["messages"]
        .as_array()
        .ok_or("redo call has messages")?
        .clone();
    drop(calls);
    assert_eq!(redo_messages.len(), 3);
    assert_eq!(redo_messages[1]["role"], "assistant");
    assert_eq!(redo_messages[1]["content"], "ok");
    assert_eq!(redo_messages[2]["role"], "user");
    let feedback = redo_messages[2]["content"]
        .as_str()
        .ok_or("feedback is text")?;
    assert!(feedback.starts_with("A senior reviewer examined your work"));
    assert!(feedback.ends_with("run the tests"));

    // A failed HTTP advisor call stops the request before the algorithm can approve it.
    let response = send_with_headers(
        &app,
        "POST",
        "/v1/chat/completions",
        Some(advisor_chat_body("advisor-down")),
        &[("proxy_x_session_id", "fail-flow")],
    )
    .await?;
    assert_eq!(response.status, StatusCode::SERVICE_UNAVAILABLE);
    assert_eq!(response.json()?["error"]["type"], "upstream_error");
    assert_eq!(
        upstream.models().await,
        [
            "model/executor",
            "model/advisor",
            "model/executor",
            "model/executor",
            "model/advisor",
        ]
    );

    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    // Only the successful redo request returns an executor answer.
    assert_eq!(stats["models"]["model/executor"]["calls"], 1);
    assert_eq!(stats["classifier"]["total_errors"], 1);
    // Projection deltas for the metrics only this test emits.
    let redo = gate_count(&stats, &["reviews", "redo", "total"])
        - gate_count(&before, &["reviews", "redo", "total"]);
    assert_eq!(redo, 1);
    assert_eq!(
        gate_count(&stats, &["reviews", "redo", "by_trigger", "no_tool_call"]),
        gate_count(&before, &["reviews", "redo", "by_trigger", "no_tool_call"]) + 1
    );
    assert_eq!(
        gate_count(&stats, &["discarded", "turns"]),
        gate_count(&before, &["discarded", "turns"]) + 1
    );
    // Mock usage: prompt 10 with 7 cached -> 3 non-cached input, 2 output.
    assert_eq!(
        gate_count(&stats, &["discarded", "tokens", "input"]),
        gate_count(&before, &["discarded", "tokens", "input"]) + 3
    );
    assert_eq!(
        gate_count(&stats, &["discarded", "tokens", "cached"]),
        gate_count(&before, &["discarded", "tokens", "cached"]) + 7
    );
    assert_eq!(
        gate_count(&stats, &["discarded", "tokens", "output"]),
        gate_count(&before, &["discarded", "tokens", "output"]) + 2
    );
    // The host stops before the algorithm records a fail-open advisor decision.
    assert_eq!(
        gate_count(&stats, &["consult_failures", "upstream_5xx"]),
        gate_count(&before, &["consult_failures", "upstream_5xx"])
    );

    // Reset re-baselines the projection: the redo/discard counts this test
    // produced disappear from the next snapshot.
    let reset = send(&app, "POST", "/v1/stats/reset", None).await?;
    assert_eq!(reset.status, StatusCode::OK);
    let stats = send(&app, "GET", "/v1/stats", None).await?.json()?;
    assert_eq!(gate_count(&stats, &["reviews", "redo", "total"]), 0);
    assert_eq!(gate_count(&stats, &["discarded", "turns"]), 0);
    Ok(())
}

// Returns every `data:` frame of an SSE body as JSON, skipping `[DONE]`.
fn sse_events(body: &str) -> Vec<Value> {
    body.lines()
        .filter_map(|line| line.strip_prefix("data: "))
        .filter(|data| *data != "[DONE]")
        .filter_map(|data| serde_json::from_str(data).ok())
        .collect()
}

// Two MCP servers expose `search`, so the upstream needs a qualified name for
// each tool. Tool definitions, history, and the forced tool choice must use the
// same qualified names. Response items and argument completions must contain
// the tool name and namespace that Codex uses to select the tool.
#[tokio::test]
async fn responses_round_trips_codex_tool_namespaces() -> TestResult {
    const MODEL: &str = "model/mcp-namespaces";
    let (upstream, app) = test_app(&[(ROUTE_MODEL, &[MODEL])]).await?;

    let response = send(
        &app,
        "POST",
        "/v1/responses",
        Some(json!({
            "model": ROUTE_MODEL,
            "stream": true,
            "input": [
                {"type": "message", "role": "user",
                 "content": [{"type": "input_text", "text": "mcp-tool-call"}]},
                {"type": "function_call", "call_id": "call_prior", "name": "search",
                 "namespace": "mcp__b", "arguments": "{}"},
                {"type": "function_call_output", "call_id": "call_prior", "output": "earlier"}
            ],
            "tool_choice": {"type": "function", "name": "search", "namespace": "mcp__b"},
            "tools": [
                {"type": "namespace", "name": "mcp__a", "tools": [{
                    "type": "function", "name": "search",
                    "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}
                }]},
                {"type": "namespace", "name": "mcp__b", "tools": [{
                    "type": "function", "name": "search",
                    "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}
                }]}
            ]
        })),
    )
    .await?;
    assert_eq!(response.status, StatusCode::OK);

    // The upstream sees two distinct tools, and every reference to the forced
    // one uses the qualified spelling.
    let calls = upstream.calls.lock().await;
    let sent = &calls[0];
    let offered = sent["tools"]
        .as_array()
        .map(|tools| {
            tools
                .iter()
                .filter_map(|tool| tool["function"]["name"].as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    assert_eq!(offered, vec!["mcp__a__search", "mcp__b__search"]);
    assert_eq!(sent["tool_choice"]["function"]["name"], "mcp__b__search");
    let recorded = sent["messages"]
        .as_array()
        .and_then(|messages| {
            messages
                .iter()
                .find_map(|message| message["tool_calls"][0]["function"]["name"].as_str())
        })
        .ok_or("no recorded tool call reached the upstream")?;
    assert_eq!(recorded, "mcp__b__search");
    drop(calls);

    // The upstream answers with the qualified name; Codex must receive the tool
    // name and the namespace it dispatches on, on every event that names a call.
    let events = sse_events(response.text()?);
    for event_type in ["response.output_item.added", "response.output_item.done"] {
        let item = events
            .iter()
            .find(|event| event["type"] == event_type)
            .map(|event| event["item"].clone())
            .ok_or(format!("stream produced no {event_type}"))?;
        assert_eq!(item["name"], "search", "{event_type}");
        assert_eq!(item["namespace"], "mcp__b", "{event_type}");
    }
    let arguments_done = events
        .iter()
        .find(|event| event["type"] == "response.function_call_arguments.done");
    assert_eq!(
        arguments_done.map(|event| &event["name"]),
        Some(&json!("search"))
    );
    assert_eq!(
        arguments_done.map(|event| &event["namespace"]),
        Some(&json!("mcp__b"))
    );
    let completed = events
        .iter()
        .find(|event| event["type"] == "response.completed")
        .ok_or("stream produced no response.completed event")?;
    assert_eq!(completed["response"]["output"][0]["name"], "search");
    assert_eq!(completed["response"]["output"][0]["namespace"], "mcp__b");
    Ok(())
}

/// Allowed upstream response headers ride through to the client, while body, cookie,
/// and Switchyard-owned headers do not; a header this server writes always beats an
/// upstream echo of the same name.
#[tokio::test]
async fn upstream_headers_forward_but_switchyard_writes_win() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;
    let body = json!({
        "model": ROUTE_MODEL,
        "messages": [{"role": "user", "content": "upstream-headers"}]
    });
    let response = send(&app, "POST", "/v1/chat/completions", Some(body)).await?;
    assert_eq!(response.status, StatusCode::OK);

    // Observability headers survive the proxy hop.
    let traces = response
        .headers
        .get_all("x-upstream-trace")
        .iter()
        .map(|value| value.to_str())
        .collect::<Result<Vec<_>, _>>()?;
    assert_eq!(traces, ["trace-123", "trace-456"]);
    assert_eq!(
        response
            .headers
            .get("x-request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req-42")
    );
    // Anthropic spells its correlation id without the `x-` prefix.
    assert_eq!(
        response
            .headers
            .get("request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req_anthropic_42")
    );
    assert!(!response.headers.contains_key("link"));

    // Upstream cookies must never become Switchyard-origin cookies.
    assert!(!response.headers.contains_key("set-cookie"));

    // Switchyard's own namespace never forwards from upstream.
    assert!(!response.headers.contains_key("x-switchyard-session-id"));

    // …and Switchyard's routing write beats the upstream echo.
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/a")
    );
    Ok(())
}

/// A streamed reply captures its headers off the response head, on a branch the
/// buffered path never touches, so the same contract is asserted there too.
#[tokio::test]
async fn upstream_headers_forward_on_streaming_responses() -> TestResult {
    let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;
    let body = json!({
        "model": ROUTE_MODEL,
        "stream": true,
        "messages": [{"role": "user", "content": "upstream-headers"}]
    });
    let response = send(&app, "POST", "/v1/chat/completions", Some(body)).await?;
    assert_eq!(response.status, StatusCode::OK);

    let traces = response
        .headers
        .get_all("x-upstream-trace")
        .iter()
        .map(|value| value.to_str())
        .collect::<Result<Vec<_>, _>>()?;
    assert_eq!(traces, ["trace-123", "trace-456"]);
    assert_eq!(
        response
            .headers
            .get("x-request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req-42")
    );
    assert_eq!(
        response
            .headers
            .get("request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req_anthropic_42")
    );
    assert!(!response.headers.contains_key("link"));
    assert!(!response.headers.contains_key("set-cookie"));
    assert!(!response.headers.contains_key("x-switchyard-session-id"));
    assert_eq!(
        response
            .headers
            .get("x-model-router-selected-model")
            .and_then(|value| value.to_str().ok()),
        Some("model/a")
    );
    Ok(())
}