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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Rust HTTP server for libsy algorithms.

mod capabilities;
pub mod config;
mod metrics;
mod observability;
mod redaction;
mod response;
mod routing_log;
mod shutdown;
mod sse;
mod stats;
mod usage_metrics;

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::future::Future;
use std::io::IsTerminal;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use axum::body::Body;
use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::extract::{DefaultBodyLimit, Query, Request as HttpRequest, State};
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Extension, Json, Router};
use axum_server::tls_rustls::RustlsConfig;
use libsy::{LibsyError, RoutingOutcome};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use switchyard_llm_client::{AuxiliaryOperation, RunObservation, RunObserver};
use switchyard_protocol::{LlmClientError, Metadata, ModelId, Request, Usage};
use switchyard_runner::{
    CallerAuthKind, DecisionTarget, ModelCapabilities, Route, RunOutput, Runner, RunnerError,
};
use tokio::net::{TcpListener, TcpSocket};
use tokio::task;
use tracing::{Instrument, Level};

use switchyard_translation::{WireFormat, decode_request, encode_aggregated_response};

use crate::response::into_http_response;
use crate::stats::{StatsAccumulator, StatsSnapshot, prefix_probe, tracking_enabled_from_env};

pub use observability::{flush_observability, initialize_observability};

/// Default TCP listen backlog used by the Rust server.
pub const DEFAULT_LISTEN_BACKLOG: u32 = 65_535;

/// Default time allowed for active requests to finish during shutdown.
pub const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);

/// Maximum buffered JSON request size accepted by the LLM endpoints.
pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 32 * 1024 * 1024;

const HEADER_SELECTED_MODEL: &str = "x-model-router-selected-model";
const FORWARDED_UPSTREAM_HEADERS: &[&str] = &[
    "baggage",
    "openai-processing-ms",
    // Anthropic spells its correlation id without the `x-` prefix.
    "request-id",
    "traceparent",
    "tracestate",
    "x-request-id",
];
const FORWARDED_UPSTREAM_HEADER_PREFIXES: &[&str] =
    &["anthropic-ratelimit-", "x-ratelimit-", "x-upstream-"];
const MAX_ROUTING_HEADER_VALUE_LEN: usize = 512;

/// Whether an upstream header is safe and useful to expose downstream.
fn should_forward_upstream_header(name: &HeaderName) -> bool {
    let name = name.as_str();
    FORWARDED_UPSTREAM_HEADERS.contains(&name)
        || FORWARDED_UPSTREAM_HEADER_PREFIXES
            .iter()
            .any(|prefix| name.starts_with(prefix))
}
/// Non-standard status used only in logs and metrics for a request whose
/// downstream client disconnected before any response was written.
const CLIENT_CLOSED_REQUEST: u16 = 499;
const STARTUP_BANNER_ART: &str = include_str!("../assets/startup_banner.txt");

/// Error returned while configuring or running the server.
#[derive(Debug)]
pub struct ServerError {
    message: String,
}

impl ServerError {
    /// Creates a server error with a user-facing message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl Display for ServerError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for ServerError {}

impl From<RunnerError> for ServerError {
    fn from(error: RunnerError) -> Self {
        let mut message = error.to_string();
        let mut source = error.source();
        while let Some(error) = source {
            message.push_str(": ");
            message.push_str(&error.to_string());
            source = error.source();
        }
        Self::new(message)
    }
}

/// Result returned by server setup and lifecycle operations.
pub type ServerResult<T> = std::result::Result<T, ServerError>;

/// Decision result using the same selected/fallback order as libsy.
#[derive(Serialize)]
struct DecisionResponse {
    selected: DecisionTargetResponse,
    fallbacks: Vec<DecisionTargetResponse>,
    #[serde(skip_serializing_if = "Option::is_none")]
    response: Option<Value>,
}

/// Response view over one target's existing configuration.
#[derive(Serialize)]
struct DecisionTargetResponse {
    target: String,
    model: ModelId,
    llm_client: DecisionLlmClientResponse,
    extra_body: BTreeMap<String, Value>,
}

/// Non-secret client settings needed to call a selected model.
#[derive(Serialize)]
struct DecisionLlmClientResponse {
    format: WireFormat,
    base_url: String,
}

/// Shared server state used by all endpoint handlers.
#[derive(Clone)]
pub struct ServerState {
    runner: Arc<Runner>,
    redactor: Arc<redaction::Redactor>,
    fallback_http: reqwest::Client,
    metrics: prometheus::Registry,
    stats: StatsAccumulator,
    routing_log: Option<SharedRoutingLog>,
    track_cache_eligibility: bool,
}

#[derive(Clone)]
struct SharedRoutingLog {
    writer: Arc<Mutex<routing_log::RoutingLog>>,
    path: PathBuf,
}

impl SharedRoutingLog {
    fn new(path: PathBuf) -> ServerResult<Self> {
        Ok(Self {
            writer: Arc::new(Mutex::new(routing_log::RoutingLog::new(path.clone())?)),
            path,
        })
    }

    fn append(
        &self,
        context: routing_log::RoutingLogContext,
        model: &str,
        tier: Option<&str>,
        usage: &Usage,
    ) {
        if let Err(error) = self.writer.lock().append(context, model, tier, usage) {
            tracing::warn!(path = %self.path.display(), %error, "routing log append failed");
        }
    }

    fn snapshot_session(
        &self,
        session_id: &str,
    ) -> std::io::Result<Option<routing_log::SessionStatsSnapshot>> {
        routing_log::snapshot(&self.path, session_id)
    }
}

impl ServerState {
    /// Creates HTTP-server state around an already configured runner.
    pub fn from_runner(runner: Runner) -> ServerResult<Self> {
        let metrics = metrics::registry().map_err(ServerError::new)?;
        let fallback_http = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|error| ServerError::new(error.to_string()))?;
        let stats = StatsAccumulator::new(
            metrics.clone(),
            runner.models().map(|model| model.algorithm),
        );
        let redactor = redaction::Redactor::new(runner.provider_api_keys());
        Ok(Self {
            redactor: Arc::new(redactor),
            runner: Arc::new(runner),
            fallback_http,
            metrics,
            stats,
            routing_log: None,
            track_cache_eligibility: tracking_enabled_from_env(),
        })
    }

    /// Enables durable per-request routing records at `path`.
    pub fn with_routing_log(mut self, path: impl Into<PathBuf>) -> ServerResult<Self> {
        self.routing_log = Some(SharedRoutingLog::new(path.into())?);
        Ok(self)
    }

    /// Returns the route model IDs served by the configured algorithms.
    pub fn models(&self) -> impl Iterator<Item = &str> {
        self.runner.models().map(|model| model.id.as_str())
    }

    /// Returns the caller credential family used by `model`, if any.
    pub fn caller_auth_kind(&self, model: &str) -> Option<&'static str> {
        self.runner
            .route(model)
            .and_then(|route| route.caller_auth())
            .map(|kind| kind.as_str())
    }

    fn route_for_model(&self, model: &str) -> Option<&Route> {
        self.runner.route(model)
    }

    fn decision_response(
        &self,
        route_model: &ModelId,
        outcome: &RoutingOutcome,
        response: Option<Value>,
    ) -> Option<DecisionResponse> {
        let description = self.runner.describe_decision(route_model, outcome)?;
        let convert = |target: DecisionTarget| DecisionTargetResponse {
            target: target.target,
            model: target.model,
            llm_client: DecisionLlmClientResponse {
                format: target.format,
                base_url: target.base_url,
            },
            extra_body: target.extra_body,
        };
        Some(DecisionResponse {
            selected: convert(description.selected),
            fallbacks: description.fallbacks.into_iter().map(convert).collect(),
            response,
        })
    }
}
/// Runtime options shared by server entry points.
#[derive(Clone, Debug)]
pub struct ServerRunOptions {
    /// Socket address to bind.
    pub addr: SocketAddr,
    /// TCP listen backlog.
    pub backlog: u32,
    /// Validate runtime construction without binding a socket.
    pub dry_run: bool,
    /// Maximum time active requests may drain after shutdown begins.
    pub shutdown_timeout: Duration,
    /// TLS certificate configuration, when HTTPS is enabled.
    pub tls: Option<TlsOptions>,
}

/// TLS certificate paths used by the server.
#[derive(Clone, Debug)]
pub struct TlsOptions {
    /// TLS certificate path in PEM format.
    pub cert: PathBuf,
    /// TLS private-key path in PEM format.
    pub key: PathBuf,
}

impl ServerRunOptions {
    fn is_tls(&self) -> bool {
        self.tls.is_some()
    }
}

/// Validates the runtime and starts the HTTP server unless `dry_run` is set.
pub async fn run_server(state: ServerState, options: ServerRunOptions) -> ServerResult<()> {
    if options.dry_run {
        println!("{}", dry_run_summary(&state));
        return Ok(());
    }

    let server = BoundServer::bind(state, options)?;
    println!("{}", server.startup_banner(std::io::stdout().is_terminal()));
    server.serve(shutdown::signal()).await
}

/// A configured server with its listening socket already bound.
pub struct BoundServer {
    listener: TcpListener,
    router: Router,
    options: ServerRunOptions,
    state: ServerState,
}

impl BoundServer {
    /// Binds the configured address and prepares the HTTP router.
    pub fn bind(state: ServerState, options: ServerRunOptions) -> ServerResult<Self> {
        let listener = bind_tcp_listener(options.addr, options.backlog)?;
        let addr = listener.local_addr().map_err(server_io_error)?;
        Ok(Self {
            listener,
            router: build_switchyard_router(state.clone()),
            options: ServerRunOptions { addr, ..options },
            state,
        })
    }

    /// Returns the actual bound address, including an OS-selected port.
    pub fn local_addr(&self) -> SocketAddr {
        self.options.addr
    }

    /// Serves requests until the supplied shutdown future resolves.
    pub async fn serve(
        self,
        shutdown: impl Future<Output = ()> + Send + 'static,
    ) -> ServerResult<()> {
        let shutdown_timeout = self.options.shutdown_timeout;
        if let Some(tls) = self.options.tls {
            serve_tls(self.listener, self.router, tls, shutdown_timeout, shutdown).await
        } else {
            serve(self.listener, self.router, shutdown_timeout, shutdown).await
        }
    }

    fn startup_banner(&self, color: bool) -> String {
        startup_banner(&self.options, &self.state, color)
    }
}

async fn serve_tls(
    listener: TcpListener,
    router: Router,
    tls: TlsOptions,
    shutdown_timeout: Duration,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> ServerResult<()> {
    if let Err(error) = rustls::crypto::aws_lc_rs::default_provider().install_default() {
        tracing::debug!(?error, "TLS crypto provider was already installed");
    }

    let config = RustlsConfig::from_pem_file(tls.cert, tls.key)
        .await
        .map_err(server_io_error)?;
    let std_listener = listener.into_std().map_err(server_io_error)?;
    let server = axum_server::from_tcp_rustls(std_listener, config).map_err(server_io_error)?;
    let handle = axum_server::Handle::new();
    let server = server
        .handle(handle.clone())
        .serve(router.into_make_service());
    serve_until_shutdown(server, handle, shutdown_timeout, shutdown).await
}

async fn serve(
    listener: TcpListener,
    router: Router,
    shutdown_timeout: Duration,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> ServerResult<()> {
    let std_listener = listener.into_std().map_err(server_io_error)?;
    let server = axum_server::from_tcp(std_listener).map_err(server_io_error)?;
    let handle = axum_server::Handle::new();
    let server = server
        .handle(handle.clone())
        .serve(router.into_make_service());
    serve_until_shutdown(server, handle, shutdown_timeout, shutdown).await
}

/// Runs the server until it exits or shutdown begins, then drains active requests.
async fn serve_until_shutdown(
    server: impl Future<Output = std::io::Result<()>>,
    handle: axum_server::Handle<SocketAddr>,
    timeout: Duration,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> ServerResult<()> {
    tokio::pin!(server);
    tokio::select! {
        result = &mut server => result.map_err(server_io_error),
        _ = shutdown => {
            tracing::info!(
                ?timeout,
                "shutdown signal received; draining active requests"
            );
            handle.graceful_shutdown(Some(timeout));
            server.await.map_err(server_io_error)
        }
    }
}

/// Ingress timestamp for one request, taken before any body is read.
#[derive(Clone, Copy)]
struct RequestStart(Instant);

/// Routing-log marker distinguishing classifier and judge calls from answer calls.
const CLASSIFIER_TIER: &str = "classifier";

/// Maps answer-call observations to backend stats, routing calls to classifier/judge
/// stats, and records routing overhead once the algorithm run completes.
///
/// Successful classifier/judge calls are also appended to `classifier_log` when one is
/// configured, so per-session routing snapshots account for judge token overhead. Routed
/// calls stay off this path: the served call is logged with its terminal usage in
/// [`usage_metrics::observe`], which would make a second append here a double count.
fn stats_observer(
    stats: StatsAccumulator,
    classifier_log: Option<(SharedRoutingLog, routing_log::RoutingLogContext)>,
) -> RunObserver {
    Arc::new(move |observation| match observation {
        RunObservation::Outcome(_) => {}
        RunObservation::AnswerCall(call) => {
            let latency_ms = call.duration.as_secs_f64() * 1_000.0;
            if call.is_success {
                stats.record_success(&call.selected_model, latency_ms);
            } else {
                stats.record_error(&call.selected_model);
            }
        }
        RunObservation::LlmCall(call) => {
            let latency_ms = call.duration.as_secs_f64() * 1_000.0;
            if call.is_success {
                if let (Some((log, context)), Some(usage)) =
                    (classifier_log.as_ref(), call.usage.as_ref())
                {
                    log.append(
                        context.clone(),
                        &call.selected_model,
                        Some(CLASSIFIER_TIER),
                        usage,
                    );
                }
                stats.record_classifier_success(
                    call.selected_model,
                    call.usage.as_ref().map(usage_metrics::token_usage),
                    latency_ms,
                );
            } else {
                stats.record_classifier_error(call.selected_model);
            }
        }
        RunObservation::RoutingOverhead(duration) => {
            stats.record_routing_overhead(duration.as_secs_f64() * 1_000.0);
        }
    })
}

/// Stamps the ingress instant into request extensions. Runs as a router layer,
/// so it executes before the handlers' `Json` extractor buffers the body —
/// request-latency measurements therefore include body read and decode.
async fn stamp_request_start(mut request: HttpRequest, next: Next) -> Response {
    request
        .extensions_mut()
        .insert(RequestStart(Instant::now()));
    next.run(request).await
}

/// Builds an Axum router containing only the primary LLM inference endpoints.
///
/// The registered paths are `/v1/chat/completions`, `/v1/messages`, and `/v1/responses`.
/// The router excludes operational, discovery, auxiliary, and fallback proxy routes so an
/// embedding application can mount those capabilities under its own policies.
pub fn build_llm_router(state: ServerState) -> Router {
    finish_router(primary_llm_routes(), state)
}

/// Builds the full Axum router used by the standalone Switchyard server.
pub fn build_switchyard_router(state: ServerState) -> Router {
    let mut router = primary_llm_routes()
        .route("/v1/decision", post(decision))
        .route("/v1/messages/count_tokens", post(anthropic_count_tokens))
        .route(
            "/v1/responses/input_tokens",
            post(openai_responses_input_tokens),
        )
        .route("/v1/responses/compact", post(openai_responses_compact))
        .route("/v1/models", get(models))
        .route("/v1/stats", get(get_stats))
        .route("/v1/stats/reset", post(reset_stats))
        .route("/metrics", get(prometheus_metrics))
        .route("/health", get(health));
    if state.routing_log.is_some() {
        router = router.route("/v1/routing/session-stats", get(get_session_stats));
    }
    finish_router(router.fallback(proxy_unmatched), state)
}

// Keeps the embedded and standalone servers on the same primary route definitions.
fn primary_llm_routes() -> Router<ServerState> {
    Router::new()
        .route("/v1/chat/completions", post(openai_chat_completions))
        .route("/v1/messages", post(anthropic_messages))
        .route("/v1/responses", post(openai_responses))
}

// Applies the serving limits and request timing shared by both public router constructors.
fn finish_router(router: Router<ServerState>, state: ServerState) -> Router {
    router
        .layer(DefaultBodyLimit::max(DEFAULT_MAX_REQUEST_BODY_BYTES))
        .layer(axum::middleware::from_fn_with_state(
            state.clone(),
            redaction::redact_response,
        ))
        // `layer` only wraps routes registered before it, so this stays last.
        .layer(axum::middleware::from_fn(stamp_request_start))
        .with_state(state)
}

fn bind_tcp_listener(addr: SocketAddr, backlog: u32) -> ServerResult<TcpListener> {
    let socket = if addr.is_ipv4() {
        TcpSocket::new_v4()
    } else {
        TcpSocket::new_v6()
    }
    .map_err(server_io_error)?;

    socket.set_reuseaddr(true).map_err(server_io_error)?;
    socket.bind(addr).map_err(server_io_error)?;
    socket.listen(backlog).map_err(server_io_error)
}

fn server_io_error(error: std::io::Error) -> ServerError {
    ServerError::new(error.to_string())
}

async fn openai_chat_completions(
    State(state): State<ServerState>,
    Extension(started): Extension<RequestStart>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    handle_endpoint(state, started, headers, body, WireFormat::OpenAiChat).await
}

async fn anthropic_messages(
    State(state): State<ServerState>,
    Extension(started): Extension<RequestStart>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    handle_endpoint(state, started, headers, body, WireFormat::AnthropicMessages).await
}

async fn openai_responses(
    State(state): State<ServerState>,
    Extension(started): Extension<RequestStart>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    handle_endpoint(state, started, headers, body, WireFormat::OpenAiResponses).await
}

// Forwards unmatched requests unchanged to the configured API root.
async fn proxy_unmatched(State(state): State<ServerState>, request: HttpRequest) -> Response {
    let Some(base_url) = state.runner.fallback_base_url() else {
        return not_found().await;
    };
    let (mut parts, body) = request.into_parts();
    let path_and_query = parts
        .uri
        .path_and_query()
        .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
    strip_hop_by_hop_headers(&mut parts.headers);
    parts.headers.remove(axum::http::header::HOST);
    let url = match fallback_url(base_url, &path_and_query) {
        Ok(url) => url,
        Err(error) => {
            return error_response(
                StatusCode::BAD_GATEWAY,
                error,
                "upstream_error",
                "upstream_error",
            );
        }
    };
    let body = reqwest::Body::wrap_stream(body.into_data_stream());
    match state
        .fallback_http
        .request(parts.method, url)
        .headers(parts.headers)
        .body(body)
        .send()
        .await
    {
        Ok(response) => {
            let response: http::Response<reqwest::Body> = response.into();
            let (mut parts, body) = response.into_parts();
            strip_hop_by_hop_headers(&mut parts.headers);
            Response::from_parts(parts, Body::new(body))
        }
        Err(error) => error_response(
            StatusCode::BAD_GATEWAY,
            error.without_url().to_string(),
            "upstream_error",
            "upstream_error",
        ),
    }
}

fn fallback_url(base_url: &str, path_and_query: &str) -> Result<reqwest::Url, String> {
    let mut url = reqwest::Url::parse(base_url.trim())
        .map_err(|error| format!("invalid fallback base URL: {error}"))?;
    let base_query = url.query().map(str::to_owned);
    url.set_query(None);
    url.set_fragment(None);

    let base_path = url.path().trim_end_matches('/');
    let root_path = [
        "/v1/chat/completions",
        "/v1/responses",
        "/v1/messages",
        "/v1",
    ]
    .iter()
    .find_map(|suffix| base_path.strip_suffix(suffix))
    .unwrap_or(base_path);
    let (request_path, request_query) = path_and_query
        .split_once('?')
        .map_or((path_and_query, None), |(path, query)| (path, Some(query)));
    let request_path = request_path.strip_prefix('/').unwrap_or(request_path);
    let target_path = if root_path.is_empty() {
        format!("/{request_path}")
    } else if request_path.is_empty() {
        format!("{root_path}/")
    } else {
        format!("{root_path}/{request_path}")
    };
    url.set_path(&target_path);

    let query = match (base_query, request_query) {
        (Some(base_query), Some(request_query)) => Some(format!("{base_query}&{request_query}")),
        (Some(base_query), None) => Some(base_query),
        (None, Some(request_query)) => Some(request_query.to_owned()),
        (None, None) => None,
    };
    url.set_query(query.as_deref());
    Ok(url)
}

fn strip_hop_by_hop_headers(headers: &mut HeaderMap) {
    let connection_headers = headers
        .get_all(axum::http::header::CONNECTION)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .flat_map(|value| value.split(','))
        .filter_map(|name| HeaderName::from_bytes(name.trim().as_bytes()).ok())
        .collect::<Vec<_>>();
    for name in connection_headers {
        headers.remove(name);
    }
    for name in [
        "connection",
        "keep-alive",
        "proxy-authenticate",
        "proxy-authorization",
        "proxy-connection",
        "te",
        "trailer",
        "transfer-encoding",
        "upgrade",
    ] {
        headers.remove(name);
    }
}

/// One provider request submitted for a routing decision without an answer-model call.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DecisionEndpointRequest {
    input_format: WireFormat,
    request: Value,
}

/// Selects a target while still allowing the algorithm's classifier and judge calls.
async fn decision(
    State(state): State<ServerState>,
    headers: HeaderMap,
    body: std::result::Result<Json<DecisionEndpointRequest>, JsonRejection>,
) -> Response {
    let body = match body {
        Ok(Json(body)) if body.request.is_object() => body,
        Ok(_) => {
            return invalid_body_error(StatusCode::BAD_REQUEST, "request must be a JSON object");
        }
        Err(error) => {
            return invalid_body_error(
                error.status(),
                format!("Request body must be valid JSON: {error}"),
            );
        }
    };
    let input_format = body.input_format;
    let (route, request) = match resolve_route(
        &state,
        metadata_from_headers(headers),
        body.request,
        input_format,
    ) {
        Ok(resolved) => resolved,
        Err(response) => return response,
    };
    let route_model = request
        .llm_request
        .model
        .as_deref()
        .map(ModelId::from)
        .unwrap_or_default();

    let mut outcome = match route.decide(request).await {
        Ok(outcome) => outcome,
        Err(error) => return runner_error(error),
    };
    let response = match outcome.response.take() {
        Some(response) => {
            let aggregate = match response.llm_response.into_agg().await {
                Ok(aggregate) => aggregate,
                Err(error) => return client_error(&error),
            };
            // The request moved into the decision run, so its namespace mapping
            // is gone by here. A Codex tool call in this preview keeps its
            // qualified name.
            match encode_aggregated_response(
                &aggregate,
                input_format,
                outcome.selected_model_id().ok().map(ModelId::as_str),
            ) {
                Ok(response) => Some(response),
                Err(error) => return server_error(error.to_string()),
            }
        }
        None => None,
    };
    match state.decision_response(&route_model, &outcome, response) {
        Some(response) => Json(response).into_response(),
        None => {
            server_error("routing outcome contains a model with no callable target configuration")
        }
    }
}

/// Anthropic token counting against the route's explicitly configured target.
async fn anthropic_count_tokens(
    State(state): State<ServerState>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    let body = match llm_json_body(body) {
        Ok(body) => body,
        Err((status, message)) => {
            return anthropic_error_response(invalid_body_error(status, message));
        }
    };
    let (route, request) = match resolve_route(
        &state,
        metadata_from_headers(headers),
        body,
        WireFormat::AnthropicMessages,
    ) {
        Ok(resolved) => resolved,
        Err(response) => return anthropic_error_response(response),
    };
    anthropic_error_response(
        match route
            .call_auxiliary(request, AuxiliaryOperation::AnthropicCountTokens)
            .await
        {
            Ok(payload) => (StatusCode::OK, Json(payload)).into_response(),
            Err(RunnerError::AuxiliaryUnsupported) => error_response(
                StatusCode::BAD_REQUEST,
                "route has no Anthropic target for token counting",
                "invalid_request_error",
                "count_tokens_unsupported",
            ),
            Err(RunnerError::Client(error)) => client_error(&error),
            Err(error) => server_error(error.to_string()),
        },
    )
}

async fn openai_responses_input_tokens(
    State(state): State<ServerState>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    openai_responses_auxiliary(
        state,
        headers,
        body,
        AuxiliaryOperation::ResponsesInputTokens,
    )
    .await
}

async fn openai_responses_compact(
    State(state): State<ServerState>,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> Response {
    openai_responses_auxiliary(state, headers, body, AuxiliaryOperation::ResponsesCompact).await
}

// Resolves route aliases and configured credentials before calling a model-bearing Responses API.
async fn openai_responses_auxiliary(
    state: ServerState,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
    operation: AuxiliaryOperation,
) -> Response {
    let body = match llm_json_body(body) {
        Ok(body) => body,
        Err((status, message)) => {
            return render_error_response(
                invalid_body_error(status, message),
                WireFormat::OpenAiResponses,
            );
        }
    };
    let (route, request) = match resolve_route(
        &state,
        metadata_from_headers(headers),
        body,
        WireFormat::OpenAiResponses,
    ) {
        Ok(resolved) => resolved,
        Err(response) => return render_error_response(response, WireFormat::OpenAiResponses),
    };
    let result = route.call_auxiliary(request, operation).await;
    render_error_response(
        match result {
            Ok(payload) => (StatusCode::OK, Json(payload)).into_response(),
            Err(RunnerError::AuxiliaryUnsupported) => error_response(
                StatusCode::BAD_REQUEST,
                "route has no OpenAI Responses target",
                "invalid_request_error",
                "responses_auxiliary_unsupported",
            ),
            Err(RunnerError::Client(error)) => client_error(&error),
            Err(error) => server_error(error.to_string()),
        },
        WireFormat::OpenAiResponses,
    )
}

async fn handle_endpoint(
    state: ServerState,
    started: RequestStart,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
    wire_format: WireFormat,
) -> Response {
    let span = observability::request_span(&headers);
    handle_endpoint_inner(state, started, headers, body, wire_format)
        .instrument(span)
        .await
}

async fn handle_endpoint_inner(
    state: ServerState,
    started: RequestStart,
    headers: HeaderMap,
    body: std::result::Result<Json<Value>, JsonRejection>,
    wire_format: WireFormat,
) -> Response {
    let metadata = metadata_from_headers(headers);
    let routing_log_context = state
        .routing_log
        .as_ref()
        .map(|_| routing_log::RoutingLogContext::from_metadata(&metadata));
    let request_log = RequestLogContext {
        started: started.0,
        wire_format,
        requested_model: body
            .as_ref()
            .ok()
            .and_then(|body| body.0.get("model"))
            .and_then(Value::as_str)
            .map(str::to_string),
        streaming: body
            .as_ref()
            .ok()
            .and_then(|body| body.0.get("stream"))
            .and_then(Value::as_bool)
            .unwrap_or(false),
        session_id: metadata.session_id.clone(),
        correlation_id: metadata.correlation_id.clone(),
    };

    // Axum drops this future when the downstream client disconnects before the
    // response is written, which cancels the run and its upstream calls. The guard
    // keeps that terminal state observable: the `emit` path below never runs for an
    // abandoned buffered request.
    let mut request_log = RequestLogGuard(Some(request_log));

    let response = match llm_json_body(body) {
        Ok(body) => {
            handle_llm_request(
                state,
                started,
                metadata,
                body,
                wire_format,
                routing_log_context,
            )
            .await
        }
        Err((status, message)) => invalid_body_error(status, message),
    };
    let response = render_error_response(response, wire_format);
    metrics::record_client_response(response.status().as_u16());
    request_log.emit(&response);
    response
}

fn llm_json_body(
    body: std::result::Result<Json<Value>, JsonRejection>,
) -> std::result::Result<Value, (StatusCode, String)> {
    match body {
        Ok(Json(value)) if value.is_object() => Ok(value),
        Ok(_) => Err((
            StatusCode::BAD_REQUEST,
            "Request body must be a JSON object".to_string(),
        )),
        Err(error) => Err((
            error.status(),
            format!("Request body must be valid JSON: {error}"),
        )),
    }
}

/// Decode `body`, resolve the route named by its `model`, and build the
/// [`Request`]. Shared by the completion and `count_tokens` handlers. Returns
/// the resolved route and the built request — or an error [`Response`]
/// (invalid body, empty `model` → 400, unknown route → 404).
// Both callers immediately return the `Err(Response)` as the HTTP response, so
// the large error type is intentional, not propagated up a call stack.
#[allow(clippy::type_complexity, clippy::result_large_err)]
fn resolve_route(
    state: &ServerState,
    metadata: Metadata,
    mut body: Value,
    wire_format: WireFormat,
) -> std::result::Result<(&Route, Request), Response> {
    // Only trusted translation hops may supply exact request preservation state.
    // Strip it before decoding and retaining the raw body for upstream replay.
    if let Some(metadata) = body.get_mut("metadata").and_then(Value::as_object_mut) {
        metadata.remove(switchyard_translation::util::SWITCHYARD_METADATA_KEY);
    }
    let llm_request = decode_request(wire_format, &body)
        .map_err(|error| invalid_body_error(StatusCode::BAD_REQUEST, error.to_string()))?;
    let requested_model = llm_request
        .model
        .clone()
        .filter(|model| !model.trim().is_empty())
        .ok_or_else(|| {
            error_response(
                StatusCode::BAD_REQUEST,
                "request body must include a non-empty string `model`",
                "invalid_request_error",
                "invalid_request_error",
            )
        })?;
    let route = state.route_for_model(&requested_model).ok_or_else(|| {
        error_response(
            StatusCode::NOT_FOUND,
            format!("No route registered for model {requested_model}"),
            "model_not_found",
            "model_not_found",
        )
    })?;
    if let Err(RunnerError::IncompatibleCallerFormat(caller_auth)) =
        route.check_caller_format(wire_format)
    {
        let (provider, expected_endpoint) = match caller_auth {
            CallerAuthKind::Anthropic => ("Anthropic", "/v1/messages"),
            CallerAuthKind::OpenAi => ("OpenAI", "/v1/chat/completions or /v1/responses"),
        };
        return Err(error_response(
            StatusCode::BAD_REQUEST,
            format!(
                "route {requested_model} forwards an {provider} login; call it through {expected_endpoint}",
            ),
            "invalid_request_error",
            "invalid_request_error",
        ));
    }
    if let Some(capability) =
        capabilities::unsupported_capability(route.capabilities(), &llm_request, &body)
    {
        return Err(error_response(
            StatusCode::BAD_REQUEST,
            format!(
                "route {requested_model} declares {capability} = false; remove the unsupported input or select another route"
            ),
            "invalid_request_error",
            "unsupported_capability",
        ));
    }
    let request = Request {
        llm_request,
        raw_request: Some(body),
        metadata: Some(metadata),
    };
    Ok((route, request))
}

/// Resolves and executes an LLM request, attaching route identity when durable logging is enabled.
async fn handle_llm_request(
    state: ServerState,
    started: RequestStart,
    metadata: Metadata,
    body: Value,
    wire_format: WireFormat,
    routing_log_context: Option<routing_log::RoutingLogContext>,
) -> Response {
    let cache_probe = state.track_cache_eligibility.then(|| prefix_probe(&body));
    let (route, request) = match resolve_route(&state, metadata, body, wire_format) {
        Ok(resolved) => resolved,
        Err(response) => return response,
    };
    let routing_log_context = routing_log_context.map(|context| {
        context.with_route(
            request.llm_request.model.as_deref().unwrap_or_default(),
            route.algorithm_name(),
        )
    });
    // Only the Codex namespace mapping is needed downstream, not the whole request.
    let request_extensions = request.llm_request.extensions.clone();
    let observer = stats_observer(
        state.stats.clone(),
        state.routing_log.clone().zip(routing_log_context.clone()),
    );

    let output = match route.execute(request, Some(observer)).await {
        Ok(output) => output,
        Err(error) => {
            if let RunnerError::Algorithm(LibsyError::ClientCall {
                target,
                source:
                    LlmClientError::ResponseStateLimitExceeded { .. }
                    | LlmClientError::ResponseStateConflict,
            }) = &error
            {
                state.stats.record_response_error(target);
            }
            return runner_error(error);
        }
    };
    let RunOutput {
        selected_model,
        response,
    } = output;
    // The response carries the candidate that actually served it. Fall back to the routing
    // selection for algorithms that return a response without an offloaded model call.
    let served_model = response.served_model().cloned().or(Some(selected_model));
    let mut response = if let Some(served_model) = served_model.as_ref() {
        let cache_eligible = cache_probe
            .as_ref()
            .map(|probe| state.stats.prefix_eligibility(served_model, probe))
            .unwrap_or(0.0);
        usage_metrics::observe(
            response,
            served_model.as_str(),
            started.0,
            state.stats,
            cache_eligible,
            state.routing_log.zip(routing_log_context),
        )
    } else {
        response
    };

    let upstream_headers = std::mem::take(&mut response.upstream_headers);
    let response_model = served_model.as_ref().map(ToString::to_string);
    let mut response = match into_http_response(
        response,
        wire_format,
        response_model,
        request_extensions,
        Arc::clone(&state.redactor),
    ) {
        Ok(response) => response,
        Err(error) => return server_error(error.to_string()),
    };
    // Forward upstream headers before Switchyard writes its own so any header
    // this server emits always overrides an upstream echo of the same name.
    let response_headers = response.headers_mut();
    for (name, value) in upstream_headers.iter() {
        if !should_forward_upstream_header(name) {
            continue;
        }
        response_headers.append(name.clone(), value.clone());
    }
    if let Some(served_model) = served_model.as_ref() {
        attach_routing_headers(&mut response, served_model.as_str());
    }
    response
}

/// Holds the request log context until the request reaches a terminal state.
/// Dropping the guard with the context still in place means the handler future was
/// cancelled — the client left before a response existed — so the run is reported
/// as abandoned rather than silently disappearing.
struct RequestLogGuard(Option<RequestLogContext>);

impl RequestLogGuard {
    // Emits the normal terminal event and disarms the cancellation path.
    fn emit(&mut self, response: &Response) {
        if let Some(context) = self.0.take() {
            context.emit(response);
        }
    }
}

impl Drop for RequestLogGuard {
    fn drop(&mut self) {
        if let Some(context) = self.0.take() {
            context.emit_cancelled();
        }
    }
}

// Request metadata held until the terminal response determines the event level.
struct RequestLogContext {
    started: Instant,
    wire_format: WireFormat,
    requested_model: Option<String>,
    streaming: bool,
    session_id: Option<String>,
    correlation_id: Option<String>,
}

// Error text carried separately so terminal logging never consumes an HTTP body.
#[derive(Clone)]
struct RequestLogError(String);

impl RequestLogContext {
    fn emit(self, response: &Response) {
        let selected_model = response
            .headers()
            .get(HEADER_SELECTED_MODEL)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("");
        let duration_ms = self.started.elapsed().as_secs_f64() * 1_000.0;
        let error = response
            .extensions()
            .get::<RequestLogError>()
            .map(|error| error.0.as_str())
            .unwrap_or("");

        macro_rules! emit {
            ($level:expr, $message:literal) => {
                tracing::event!(
                    target: "switchyard_server::request",
                    $level,
                    wire_format = %self.wire_format,
                    status = response.status().as_u16(),
                    requested_model = self.requested_model.as_deref().unwrap_or(""),
                    selected_model,
                    streaming = self.streaming,
                    session_id = self.session_id.as_deref().unwrap_or(""),
                    correlation_id = self.correlation_id.as_deref().unwrap_or(""),
                    handling_duration_ms = duration_ms,
                    error,
                    $message
                )
            };
        }

        match request_log_level(response.status()) {
            Level::ERROR => emit!(Level::ERROR, "LLM request failed"),
            Level::WARN => emit!(Level::WARN, "LLM request failed"),
            _ => emit!(Level::INFO, "LLM request handled"),
        }
    }

    // Terminal event for a request whose client left before a response was written.
    // No model served it, so there is no selected model and no response status.
    fn emit_cancelled(self) {
        metrics::record_client_disconnect();
        tracing::event!(
            target: "switchyard_server::request",
            Level::WARN,
            wire_format = %self.wire_format,
            status = CLIENT_CLOSED_REQUEST,
            requested_model = self.requested_model.as_deref().unwrap_or(""),
            selected_model = "",
            streaming = self.streaming,
            session_id = self.session_id.as_deref().unwrap_or(""),
            correlation_id = self.correlation_id.as_deref().unwrap_or(""),
            handling_duration_ms = self.started.elapsed().as_secs_f64() * 1_000.0,
            error = "client disconnected before a response was written",
            "LLM request cancelled"
        );
    }
}

fn request_log_level(status: StatusCode) -> Level {
    if status.is_server_error() {
        Level::ERROR
    } else if status.is_success() {
        Level::INFO
    } else {
        Level::WARN
    }
}

fn metadata_from_headers(headers: HeaderMap) -> Metadata {
    let mut metadata = Metadata::from_headers(&headers);
    metadata.http_headers = Some(headers);
    metadata
}

fn attach_routing_headers(response: &mut Response, served_model: &str) {
    insert_routing_header(response, HEADER_SELECTED_MODEL, served_model);
}

fn insert_routing_header(response: &mut Response, name: &'static str, value: &str) {
    let Some(value) = sanitize_routing_header_value(value) else {
        return;
    };
    let Ok(value) = HeaderValue::from_str(&value) else {
        return;
    };
    response
        .headers_mut()
        .insert(HeaderName::from_static(name), value);
}

fn sanitize_routing_header_value(value: &str) -> Option<String> {
    let value = value.split_whitespace().collect::<Vec<_>>().join(" ");
    (!value.is_empty()).then(|| value.chars().take(MAX_ROUTING_HEADER_VALUE_LEN).collect())
}

fn algorithm_error(error: LibsyError) -> Response {
    let LibsyError::ClientCall { source, .. } = &error else {
        return server_error(error.to_string());
    };
    client_error(source)
}

fn runner_error(error: RunnerError) -> Response {
    match error {
        RunnerError::Algorithm(error) => algorithm_error(error),
        RunnerError::Client(error) => client_error(&error),
        error => server_error(error.to_string()),
    }
}

fn client_error(error: &LlmClientError) -> Response {
    match error {
        LlmClientError::ResponseStateLimitExceeded { .. } => error_response(
            StatusCode::SERVICE_UNAVAILABLE,
            error.to_string(),
            "server_error",
            "response_state_limit_exceeded",
        ),
        LlmClientError::ResponseStateConflict => error_response(
            StatusCode::CONFLICT,
            error.to_string(),
            "server_error",
            "response_state_conflict",
        ),
        LlmClientError::InvalidRequest { message }
        | LlmClientError::RequestTranslation(message) => error_response(
            StatusCode::BAD_REQUEST,
            message,
            "invalid_request_error",
            "invalid_request_error",
        ),
        LlmClientError::Configuration { message } => error_response(
            StatusCode::BAD_GATEWAY,
            message,
            "upstream_error",
            "upstream_configuration_error",
        ),
        LlmClientError::ContextWindowExceeded { message, .. } => error_response(
            StatusCode::BAD_REQUEST,
            message,
            "invalid_request_error",
            "context_length_exceeded",
        ),
        LlmClientError::UpstreamHttp { status, body } => upstream_error(*status, body),
        LlmClientError::Transport { source } | LlmClientError::InvalidResponse { source } => {
            error_response(
                StatusCode::BAD_GATEWAY,
                source.to_string(),
                "upstream_error",
                "upstream_error",
            )
        }
        LlmClientError::ResponseTranslation(message) => error_response(
            StatusCode::BAD_GATEWAY,
            message,
            "upstream_error",
            "upstream_error",
        ),
        LlmClientError::Timeout { source } => error_response(
            StatusCode::GATEWAY_TIMEOUT,
            source.to_string(),
            "upstream_error",
            "upstream_timeout",
        ),
        LlmClientError::RequestEncoding(message) => server_error(message),
        _ => server_error(error.to_string()),
    }
}

// Keep the provider's message and nonempty string code in our error JSON.
fn upstream_error(status: StatusCode, body: &str) -> Response {
    let parsed = serde_json::from_str::<Value>(body).unwrap_or_default();
    let error = &parsed["error"];
    let message = error["message"].as_str().unwrap_or(body);
    let code = error["code"]
        .as_str()
        .filter(|code| !code.is_empty())
        .unwrap_or("upstream_error");
    error_response(status, message, "upstream_error", code)
}

// Keep error details until the endpoint chooses its response format.
#[derive(Clone)]
struct ApiError {
    status: StatusCode,
    message: String,
    error_type: &'static str,
    code: String,
}

impl ApiError {
    fn new(
        status: StatusCode,
        message: impl Into<String>,
        error_type: &'static str,
        code: impl Into<String>,
    ) -> Self {
        Self {
            status,
            message: message.into(),
            error_type,
            code: code.into(),
        }
    }

    fn into_response(self, wire_format: WireFormat) -> Response {
        let body = match wire_format {
            WireFormat::AnthropicMessages => json!({
                "type": "error",
                "error": {
                    "type": anthropic_error_type(self.status),
                    "message": self.message.clone(),
                }
            }),
            WireFormat::OpenAiChat | WireFormat::OpenAiResponses => json!({
                "error": {
                    "message": self.message.clone(),
                    "type": self.error_type,
                    "code": self.code,
                }
            }),
        };
        let mut response = (self.status, Json(body)).into_response();
        response
            .extensions_mut()
            .insert(RequestLogError(self.message.clone()));
        response.extensions_mut().insert(self);
        response
    }
}

fn render_error_response(response: Response, wire_format: WireFormat) -> Response {
    let Some(error) = response.extensions().get::<ApiError>().cloned() else {
        return response;
    };
    error.into_response(wire_format)
}

fn anthropic_error_response(response: Response) -> Response {
    render_error_response(response, WireFormat::AnthropicMessages)
}

fn anthropic_error_type(status: StatusCode) -> &'static str {
    match status {
        StatusCode::BAD_REQUEST => "invalid_request_error",
        StatusCode::UNAUTHORIZED => "authentication_error",
        StatusCode::FORBIDDEN => "permission_error",
        StatusCode::NOT_FOUND => "not_found_error",
        StatusCode::PAYLOAD_TOO_LARGE => "request_too_large",
        StatusCode::TOO_MANY_REQUESTS => "rate_limit_error",
        status if status.as_u16() == 529 => "overloaded_error",
        _ => "api_error",
    }
}

fn server_error(message: impl Into<String>) -> Response {
    error_response(
        StatusCode::INTERNAL_SERVER_ERROR,
        message,
        "server_error",
        "server_error",
    )
}

fn invalid_body_error(status: StatusCode, message: impl Into<String>) -> Response {
    error_response(status, message, "invalid_request_error", "invalid_body")
}

fn error_response(
    status: StatusCode,
    message: impl Into<String>,
    error_type: &'static str,
    code: impl Into<String>,
) -> Response {
    ApiError::new(status, message, error_type, code).into_response(WireFormat::OpenAiChat)
}

async fn models(State(state): State<ServerState>) -> Json<Value> {
    Json(model_list_payload(
        state
            .runner
            .models()
            .map(|model| (model.id.as_str(), model.capabilities)),
    ))
}

async fn get_stats(State(state): State<ServerState>) -> Json<StatsSnapshot> {
    Json(state.stats.snapshot())
}

async fn reset_stats(State(state): State<ServerState>) -> Json<Value> {
    state.stats.reset();
    Json(json!({"status": "reset"}))
}

#[derive(Deserialize)]
struct SessionStatsQuery {
    session_id: String,
}

// TODO: This loads the entire file. It should stream the JSONL instead.
// Huge files will crash the demo server.
async fn get_session_stats(
    State(state): State<ServerState>,
    query: std::result::Result<Query<SessionStatsQuery>, QueryRejection>,
) -> Response {
    let Query(query) = match query {
        Ok(query) => query,
        Err(error) => {
            return error_response(
                StatusCode::BAD_REQUEST,
                error.to_string(),
                "invalid_request_error",
                "invalid_query",
            );
        }
    };
    let Some(routing_log) = state.routing_log else {
        // Should be unreachable
        return not_found().await;
    };
    let session_id = query.session_id.clone();
    // Loading and de-serializing a large file is a time consuming blocking operation
    let snapshot =
        match task::spawn_blocking(move || routing_log.snapshot_session(&session_id)).await {
            Ok(s) => s,
            Err(err) => {
                return server_error(format!("failed to snapshot: {err}"));
            }
        };

    match snapshot {
        Ok(Some(snapshot)) => (StatusCode::OK, Json(snapshot)).into_response(),
        Ok(None) => error_response(
            StatusCode::NOT_FOUND,
            "Routing session not found",
            "not_found",
            "routing_session_not_found",
        ),
        Err(error) => server_error(format!("failed to read routing log: {error}")),
    }
}

async fn health() -> Json<Value> {
    Json(json!({"status": "ok"}))
}

async fn prometheus_metrics(State(state): State<ServerState>) -> Response {
    match metrics::encode(&state.metrics) {
        Ok(body) => ([(CONTENT_TYPE, metrics::CONTENT_TYPE)], body).into_response(),
        Err(error) => server_error(error),
    }
}

async fn not_found() -> Response {
    error_response(
        StatusCode::NOT_FOUND,
        "Not Found",
        "not_found",
        "endpoint_not_found",
    )
}

fn model_list_payload<'a>(
    entries: impl IntoIterator<Item = (&'a str, ModelCapabilities)>,
) -> Value {
    let mut entries = entries.into_iter().collect::<Vec<_>>();
    entries.sort_unstable_by_key(|(model_id, _)| *model_id);
    let model_ids = entries.iter().map(|(model, _)| *model).collect::<Vec<_>>();
    let first_id = model_ids.first().copied();
    let last_id = model_ids.last().copied();
    json!({
        "object": "list",
        "data": entries.iter().map(|(model, caps)| model_entry_json(model, *caps)).collect::<Vec<_>>(),
        // Codex requires this key; an empty list preserves its own catalog and instructions.
        "models": [],
        "first_id": first_id,
        "last_id": last_id,
        "has_more": false,
        "default_model": first_id,
        "model_pool": model_ids,
    })
}

fn model_entry_json(model: &str, capabilities: ModelCapabilities) -> Value {
    json!({
        "id": model,
        "object": "model",
        "type": "model",
        "created": 0,
        "owned_by": "switchyard",
        "display_name": model,
        "capabilities": {
            "streaming": true,
            "tool_calling": capabilities.tool_calling,
            "vision": capabilities.vision,
            "context_window": capabilities.context_window,
            "supported_inbound_formats": [
                "openai-chat-completions",
                "openai-responses",
                "anthropic-messages",
            ],
        },
    })
}

fn startup_banner(options: &ServerRunOptions, state: &ServerState, color: bool) -> String {
    let scheme = if options.is_tls() { "https" } else { "http" };
    let listen_url = url_for_addr(scheme, options.addr);
    let request_url = request_url_for_addr(scheme, options.addr);
    let routes = state.models().collect::<Vec<_>>();
    let route_list = routes.join(", ");
    let example_model = routes.first().copied().unwrap_or("switchyard/route");
    let example_body = json!({
        "model": example_model,
        "messages": [{"role": "user", "content": "Hello from Switchyard"}],
    });
    let example_url = shell_quote(&format!("{request_url}/v1/chat/completions"));
    let example_body = shell_quote(&example_body.to_string());
    format!(
        "{}\nSwitchyard libsy server\n  listening: {}\n  routes: {}\n\nendpoints:\n{}\n\nexample:\n  curl -s {} \\\n    -H 'Content-Type: application/json' \\\n    -d {}",
        render_startup_banner_art(color),
        listen_url,
        route_list,
        endpoint_listing(state.routing_log.is_some()),
        example_url,
        example_body,
    )
}

// Keep redirected logs plain. Terminal output applies NVIDIA-green ANSI truecolor per line.
fn render_startup_banner_art(color: bool) -> String {
    let banner = STARTUP_BANNER_ART.trim_end();
    if !color {
        return banner.to_string();
    }

    let (red, green, blue) = (118, 185, 0);
    let mut rendered = String::new();
    for line in banner.lines() {
        rendered.push_str(&format!("\x1b[38;2;{red};{green};{blue}m{line}\x1b[0m\n"));
    }
    rendered.trim_end_matches('\n').to_string()
}

fn dry_run_summary(state: &ServerState) -> String {
    format!(
        "server OK: {}",
        state.models().collect::<Vec<_>>().join(", ")
    )
}

fn url_for_addr(scheme: &'static str, addr: SocketAddr) -> String {
    format!("{scheme}://{}:{}", host_for_url(addr.ip()), addr.port())
}

// Use loopback in request examples when the listener binds all interfaces.
fn request_url_for_addr(scheme: &'static str, addr: SocketAddr) -> String {
    let host = if addr.ip().is_unspecified() {
        match addr.ip() {
            std::net::IpAddr::V4(_) => "127.0.0.1".to_string(),
            std::net::IpAddr::V6(_) => "[::1]".to_string(),
        }
    } else {
        host_for_url(addr.ip())
    };
    format!("{scheme}://{host}:{}", addr.port())
}

// Bracket IPv6 literals so they are valid inside a URL authority.
fn host_for_url(ip: std::net::IpAddr) -> String {
    match ip {
        std::net::IpAddr::V4(ip) => ip.to_string(),
        std::net::IpAddr::V6(ip) => format!("[{ip}]"),
    }
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn endpoint_listing(has_routing_log: bool) -> String {
    let mut endpoints = vec![
        "  POST /v1/chat/completions    OpenAI Chat Completions",
        "  POST /v1/messages            Anthropic Messages",
        "  POST /v1/responses           OpenAI Responses",
        "  POST /v1/messages/count_tokens",
        "  POST /v1/responses/input_tokens",
        "  POST /v1/responses/compact",
        "  ANY  unmatched paths          optional fallback client",
        "  GET  /v1/models              configured routes",
        "  GET  /v1/stats               routing stats",
        "  POST /v1/stats/reset",
        "  GET  /metrics                Prometheus metrics",
        "  GET  /health",
    ];
    if has_routing_log {
        endpoints.push("  GET  /v1/routing/session-stats");
    }
    endpoints.join("\n")
}

#[cfg(test)]
mod tests {
    use switchyard_llm_client::LlmCallObservation;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::{Notify, oneshot};

    use super::*;

    /// A successful judge call lands in the per-session routing snapshot under its
    /// model id with the classifier tier, while routed calls stay off the observer's
    /// log path — they are logged with terminal usage when the served response is
    /// observed, so an append here would double count them.
    #[test]
    fn stats_observer_logs_judge_calls_to_the_routing_log() {
        let dir = tempfile::tempdir().expect("temp dir");
        let log = SharedRoutingLog::new(dir.path().join("routing.jsonl")).expect("routing log");
        let mut headers = HeaderMap::new();
        headers.insert("proxy_x_session_id", "session-1".parse().expect("header"));
        let metadata = metadata_from_headers(headers);
        let context = routing_log::RoutingLogContext::from_metadata(&metadata);
        let observer = stats_observer(StatsAccumulator::default(), Some((log.clone(), context)));

        let call = |model: &str, answer: bool| {
            let observation = LlmCallObservation {
                selected_model: ModelId::from(model),
                is_success: true,
                duration: Duration::from_millis(3),
                usage: Some(Usage {
                    input_tokens: Some(100),
                    output_tokens: Some(7),
                    ..Usage::default()
                }),
            };
            if answer {
                RunObservation::AnswerCall(observation)
            } else {
                RunObservation::LlmCall(observation)
            }
        };
        observer(call("judge-model", false));
        observer(call("routed-model", true));

        let snapshot = log
            .snapshot_session("session-1")
            .expect("read log")
            .expect("session recorded");
        let snapshot = serde_json::to_value(&snapshot).expect("serializable snapshot");
        assert_eq!(snapshot["models"]["judge-model"]["calls"], 1);
        assert_eq!(snapshot["models"]["judge-model"]["prompt_tokens"], 100);
        assert_eq!(snapshot["models"]["judge-model"]["completion_tokens"], 7);
        assert!(snapshot["models"].get("routed-model").is_none());
    }

    #[derive(Clone)]
    struct ShutdownTestState {
        started: Arc<Notify>,
        release: Arc<Notify>,
    }

    struct ShutdownTestServer {
        state: ShutdownTestState,
        shutdown: oneshot::Sender<()>,
        server: task::JoinHandle<ServerResult<()>>,
        request: task::JoinHandle<std::io::Result<Vec<u8>>>,
    }

    async fn blocked_request(State(state): State<ShutdownTestState>) -> &'static str {
        state.started.notify_one();
        state.release.notified().await;
        "done"
    }

    async fn raw_request(addr: SocketAddr) -> std::io::Result<Vec<u8>> {
        let mut stream = tokio::net::TcpStream::connect(addr).await?;
        stream
            .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
            .await?;
        let mut response = Vec::new();
        stream.read_to_end(&mut response).await?;
        Ok(response)
    }

    fn shutdown_test_server(shutdown_timeout: Duration) -> ShutdownTestServer {
        let state = ShutdownTestState {
            started: Arc::new(Notify::new()),
            release: Arc::new(Notify::new()),
        };
        let router = Router::new()
            .route("/", get(blocked_request))
            .with_state(state.clone());
        let listener = bind_tcp_listener("127.0.0.1:0".parse().expect("valid address"), 16)
            .expect("listener binds");
        let addr = listener.local_addr().expect("listener has an address");
        let (shutdown, shutdown_receiver) = oneshot::channel();
        let server = tokio::spawn(serve(listener, router, shutdown_timeout, async move {
            let _ = shutdown_receiver.await;
        }));
        let request = tokio::spawn(raw_request(addr));
        ShutdownTestServer {
            state,
            shutdown,
            server,
            request,
        }
    }

    // Active requests may finish within the grace period, while stuck requests are bounded.
    #[tokio::test]
    async fn shutdown_drains_until_configured_deadline() {
        let ShutdownTestServer {
            state,
            shutdown,
            mut server,
            request,
        } = shutdown_test_server(Duration::from_secs(1));
        state.started.notified().await;
        shutdown.send(()).expect("server receives shutdown");
        assert!(
            tokio::time::timeout(Duration::from_millis(25), &mut server)
                .await
                .is_err(),
            "server must wait for the active request"
        );
        state.release.notify_one();
        tokio::time::timeout(Duration::from_secs(1), server)
            .await
            .expect("server stops after request drains")
            .expect("server task completes")
            .expect("server exits cleanly");
        let response = request
            .await
            .expect("request task completes")
            .expect("request succeeds");
        assert!(response.windows(8).any(|part| part == b"200 OK\r\n"));
        assert!(response.ends_with(b"done"));

        let ShutdownTestServer {
            state,
            shutdown,
            server,
            request,
        } = shutdown_test_server(Duration::from_millis(25));
        state.started.notified().await;
        shutdown.send(()).expect("server receives shutdown");
        tokio::time::timeout(Duration::from_secs(1), server)
            .await
            .expect("shutdown deadline is enforced")
            .expect("server task completes")
            .expect("server exits cleanly");
        state.release.notify_one();
        request.abort();
    }

    #[derive(Clone)]
    struct CancelTestState {
        started: Arc<Notify>,
        cancelled: Arc<Notify>,
    }

    // Signals when the handler future is dropped, standing in for the in-flight
    // upstream call that a cancelled run releases.
    struct CancelSentinel(Arc<Notify>);

    impl Drop for CancelSentinel {
        fn drop(&mut self) {
            self.0.notify_one();
        }
    }

    async fn never_responds(State(state): State<CancelTestState>) -> &'static str {
        let _sentinel = CancelSentinel(state.cancelled.clone());
        state.started.notify_one();
        std::future::pending::<()>().await;
        "unreachable"
    }

    // A buffered request produces no response until the run finishes, so nothing is
    // written to the socket to reveal that the client left. The server must still drop
    // the handler future on disconnect, otherwise upstream work outlives its client.
    #[tokio::test]
    async fn client_disconnect_cancels_a_buffered_handler() {
        let state = CancelTestState {
            started: Arc::new(Notify::new()),
            cancelled: Arc::new(Notify::new()),
        };
        let router = Router::new()
            .route("/", post(never_responds))
            .with_state(state.clone());
        let listener = bind_tcp_listener("127.0.0.1:0".parse().expect("valid address"), 16)
            .expect("listener binds");
        let addr = listener.local_addr().expect("listener has an address");
        let (shutdown, shutdown_receiver) = oneshot::channel();
        let server = tokio::spawn(serve(
            listener,
            router,
            Duration::from_millis(25),
            async move {
                let _ = shutdown_receiver.await;
            },
        ));

        let mut stream = tokio::net::TcpStream::connect(addr)
            .await
            .expect("client connects");
        stream
            .write_all(b"POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 2\r\n\r\n{}")
            .await
            .expect("client sends a complete request");
        state.started.notified().await;

        // The client goes away mid-run, before any response byte exists.
        drop(stream);

        tokio::time::timeout(Duration::from_secs(5), state.cancelled.notified())
            .await
            .expect("handler future is dropped when the client disconnects");

        let _ = shutdown.send(());
        let _ = tokio::time::timeout(Duration::from_secs(5), server).await;
    }

    // Collects the terminal request events emitted while it is the active subscriber.
    #[derive(Clone, Default)]
    struct CapturedEvents(Arc<Mutex<Vec<(Level, String)>>>);

    impl tracing_subscriber::Layer<tracing_subscriber::Registry> for CapturedEvents {
        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>,
        ) {
            if event.metadata().target() != "switchyard_server::request" {
                return;
            }
            let mut message = String::new();
            event.record(
                &mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| {
                    if field.name() == "message" {
                        message = format!("{value:?}");
                    }
                },
            );
            self.0.lock().push((*event.metadata().level(), message));
        }
    }

    fn request_log_context() -> RequestLogContext {
        RequestLogContext {
            started: Instant::now(),
            wire_format: WireFormat::OpenAiChat,
            requested_model: Some("switchyard/route".to_string()),
            streaming: false,
            session_id: Some("session".to_string()),
            correlation_id: None,
        }
    }

    fn captured_events(run: impl FnOnce()) -> Vec<(Level, String)> {
        use tracing_subscriber::layer::SubscriberExt;

        let captured = CapturedEvents::default();
        let subscriber = tracing_subscriber::registry().with(captured.clone());
        tracing::subscriber::with_default(subscriber, run);
        captured.0.lock().clone()
    }

    // A dropped handler future is the only trace an abandoned buffered request leaves,
    // so the guard has to turn it into a terminal event rather than logging nothing.
    #[test]
    fn dropping_the_request_log_guard_reports_a_cancelled_request() {
        let events = captured_events(|| {
            drop(RequestLogGuard(Some(request_log_context())));
        });

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].0, Level::WARN);
        assert!(events[0].1.contains("cancelled"), "{:?}", events[0].1);
    }

    // A request that reached a response is not a cancellation, even though the guard
    // is still dropped afterwards.
    #[test]
    fn an_answered_request_reports_only_its_response() {
        let events = captured_events(|| {
            let mut guard = RequestLogGuard(Some(request_log_context()));
            guard.emit(&StatusCode::OK.into_response());
        });

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].0, Level::INFO);
        assert!(events[0].1.contains("handled"), "{:?}", events[0].1);
    }

    // Terminal request severity follows HTTP status instead of error-path bookkeeping.
    #[test]
    fn request_log_level_follows_http_status() {
        assert_eq!(request_log_level(StatusCode::OK), Level::INFO);
        assert_eq!(request_log_level(StatusCode::BAD_REQUEST), Level::WARN);
        assert_eq!(
            request_log_level(StatusCode::INTERNAL_SERVER_ERROR),
            Level::ERROR
        );
    }

    // Canonical error text remains available without consuming the response body.
    #[test]
    fn error_response_carries_request_log_error() {
        let response = error_response(
            StatusCode::BAD_REQUEST,
            "invalid request",
            "invalid_request_error",
            "invalid_request_error",
        );

        assert_eq!(
            response
                .extensions()
                .get::<RequestLogError>()
                .map(|error| error.0.as_str()),
            Some("invalid request")
        );
    }
}