llmposter 0.4.5

Drop-in mock server for OpenAI, Anthropic & Gemini APIs — library or standalone CLI. SSE streaming, tool calling, OAuth2, failure injection, streaming chaos, stateful scenarios, request capture, hot-reload, response templating. Test LLM apps without burning tokens.
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
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::{header, StatusCode};
use axum::middleware::{self, Next};
use axum::response::Response;
use axum::routing::{get, post};
use axum::Router;
use tokio::net::TcpListener;

use crate::fixture::Fixture;
use crate::format::IdGenerator;

/// OAuth client configuration for the embedded oauth-mock server.
#[cfg(feature = "oauth")]
#[derive(Clone)]
pub struct OAuthConfig {
    /// OAuth client_id for the mock client.
    pub client_id: String,
    /// OAuth client_secret for the mock client.
    pub client_secret: String,
    /// Redirect URIs. Defaults to `["https://example.com/callback"]`.
    pub redirect_uris: Vec<String>,
    /// Scopes. Defaults to `["openid", "profile", "email"]`.
    pub scopes: Vec<String>,
}

#[cfg(feature = "oauth")]
impl Default for OAuthConfig {
    fn default() -> Self {
        Self {
            client_id: "mock-client".to_string(),
            client_secret: "mock-secret".to_string(),
            redirect_uris: vec!["https://example.com/callback".to_string()],
            scopes: vec![
                "openid".to_string(),
                "profile".to_string(),
                "email".to_string(),
            ],
        }
    }
}

pub(crate) struct AppState {
    /// Live fixture list — wrapped in `RwLock` to support hot-reload
    /// via [`MockServer::set_fixtures`] without restarting the server.
    ///
    /// Each fixture is stored inside an `Arc` so handlers can clone a
    /// matched fixture out of the read lock by bumping a refcount instead
    /// of deep-cloning the whole struct (which, for fixtures with large
    /// tool-call arguments, was showing up in per-request profiles).
    pub(crate) fixtures: std::sync::RwLock<Vec<Arc<Fixture>>>,
    pub(crate) id_gen: IdGenerator,
    pub(crate) verbose: bool,
    /// Separate counter for x-request-id headers (doesn't interfere with response IDs).
    pub(crate) request_counter: AtomicU64,
    /// Monotonically increasing per-request counter feeding the chaos PRNG
    /// seed derivation. Distinct from `request_counter` so x-request-id IDs
    /// stay stable even if chaos plumbing changes.
    pub(crate) chaos_counter: AtomicU64,
    pub(crate) auth: Option<crate::auth::AuthState>,
    /// Scenario state machines — keyed by scenario name, value is current state.
    pub(crate) scenarios: std::sync::RwLock<std::collections::HashMap<String, String>>,
    /// Captured requests for test assertions. `VecDeque` gives O(1)
    /// `pop_front` when `capture_capacity` trimming kicks in, which
    /// matters for long-lived standalone servers at steady state
    /// (otherwise every capture would `Vec::remove(0)` and shift).
    pub(crate) captured_requests: std::sync::RwLock<std::collections::VecDeque<CapturedRequest>>,
    /// Upper bound on `captured_requests` length — when the log reaches
    /// this size, the oldest entry is dropped to make room for the new
    /// one. `None` means unbounded (the pre-v0.4.5 default, kept for
    /// tests that call `get_requests()` once and expect every entry).
    pub(crate) capture_capacity: Option<usize>,
}

/// What happened when the server handled a captured request.
///
/// Marked `#[non_exhaustive]` — future versions may add new variants
/// (e.g. for rate-limited paths, scenario mismatches, or replayed
/// responses). External callers matching on `RequestOutcome` must
/// include a catch-all arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestOutcome {
    /// A fixture was selected for this request, regardless of the
    /// resulting HTTP status. Covers `response:` fixtures (HTTP 200),
    /// `error:` fixtures (any 4xx/5xx the fixture asks for), `refusal:`
    /// fixtures (HTTP 200 for non-streaming; HTTP 400 when the client
    /// requested `stream: true`), and all streaming chaos paths
    /// (`corrupt_body`, `truncate_after_frames`, `disconnect_after_ms`).
    /// The meaning is "the server matched and dispatched a fixture",
    /// not "the client got a 200".
    Matched,
    /// Request reached an LLM endpoint and parsed successfully but no
    /// fixture matched (HTTP 404).
    NoFixtureMatch,
    /// Request was rejected at parse / validation time on an LLM endpoint
    /// (HTTP 400). Includes JSON parse errors and
    /// [`crate::format`]-level extractor failures.
    BadRequest,
    /// Bearer-token auth rejected the request before it reached a handler
    /// (HTTP 401).
    AuthRejected,
    /// Request hit the `/code/{status}` echo endpoint (any status).
    CodeEndpoint,
}

/// A captured HTTP request for test assertions.
///
/// Available via [`MockServer::get_requests()`] after requests have been
/// handled. The struct is `#[non_exhaustive]` so future versions may add
/// new fields (e.g. captured response status) without a semver break —
/// prefer the builder-free accessors over exhaustive destructuring.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CapturedRequest {
    /// HTTP method (always POST for LLM endpoints, GET for `/code/`).
    pub method: String,
    /// Resolved request path — for Gemini, the *real*
    /// `/v1beta/models/{model}:{action}` the client used, not the router
    /// wildcard pattern.
    pub path: String,
    /// Raw request body as received on the wire. Present for `Matched`,
    /// `NoFixtureMatch`, and `BadRequest` outcomes. Empty for
    /// `AuthRejected` (the auth middleware does not buffer the body to
    /// stay off the hot path) and `CodeEndpoint` (GET has no body).
    pub body: String,
    /// What the server decided about this request. See [`RequestOutcome`].
    pub outcome: RequestOutcome,
    /// Name of the matched fixture's scenario, if any. Always `None` for
    /// non-`Matched` outcomes.
    pub matched_scenario: Option<String>,
    /// Timestamp when the request was received.
    pub timestamp: std::time::Instant,
}

impl CapturedRequest {
    /// `true` when a fixture was selected for this request — the server
    /// matched and dispatched it, regardless of the resulting HTTP
    /// status. Use this for the common test assertion "my client retry
    /// path actually hit a matched fixture after the 429". See
    /// [`RequestOutcome::Matched`] for the full list of cases that
    /// count as matched.
    pub fn was_matched(&self) -> bool {
        self.outcome == RequestOutcome::Matched
    }
}

impl AppState {
    pub(crate) fn next_request_id(&self) -> String {
        let n = self.request_counter.fetch_add(1, Ordering::Relaxed);
        format!("req-llmposter-{}", n)
    }

    /// Validates and atomically replaces the fixture list.
    ///
    /// On validation failure, returns an error and the existing fixtures are
    /// unchanged. **Scenario state (the `scenarios` hashmap) is intentionally
    /// preserved across a swap** so in-progress multi-turn conversations
    /// survive a config correction while the server is under load. Callers
    /// that want to reset scenarios on every reload can follow up with
    /// [`MockServer::reset`].
    pub(crate) fn set_fixtures(
        &self,
        mut fixtures: Vec<Fixture>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        for (i, fixture) in fixtures.iter_mut().enumerate() {
            fixture
                .validate()
                .map_err(|e| format!("Fixture #{}: {}", i + 1, e))?;
        }
        self.swap_fixtures_unchecked(fixtures);
        Ok(())
    }

    /// Atomically replaces the fixture list WITHOUT running validation.
    ///
    /// Safe to call only when the caller has already validated the list
    /// (e.g. hot-reload paths re-reading sources through `load_yaml_file`,
    /// which validates at load time). Same scenario-preservation semantics
    /// as [`set_fixtures`](Self::set_fixtures): existing scenario state is
    /// not reset.
    pub(crate) fn swap_fixtures_unchecked(&self, fixtures: Vec<Fixture>) {
        let arced: Vec<Arc<Fixture>> = fixtures.into_iter().map(Arc::new).collect();
        let mut guard = self.fixtures.write().unwrap_or_else(|e| e.into_inner());
        *guard = arced;
    }
}

/// Which source caused a hot-reload attempt. Used for logging only.
#[cfg(any(feature = "watch", unix))]
#[derive(Debug, Clone, Copy)]
enum ReloadTrigger {
    #[cfg(feature = "watch")]
    Watch,
    #[cfg(unix)]
    Sighup,
}

#[cfg(any(feature = "watch", unix))]
impl ReloadTrigger {
    fn label(self) -> &'static str {
        match self {
            #[cfg(feature = "watch")]
            Self::Watch => "watch",
            #[cfg(unix)]
            Self::Sighup => "SIGHUP",
        }
    }
}

/// Re-read tracked sources and atomically swap them into the given state.
/// On parse failure, the old fixtures are left untouched and the error is
/// logged to stderr. Used by the file watcher and the SIGHUP handler.
///
/// `reload_sources` already validates each fixture at load time, so the swap
/// itself is infallible here — we use `swap_fixtures_unchecked` to avoid
/// revalidating (and to make the unreachable error branch actually unreachable).
#[cfg(any(feature = "watch", unix))]
fn reload_and_swap(
    state: &AppState,
    sources: &[std::path::PathBuf],
    verbose: bool,
    trigger: ReloadTrigger,
) {
    let label = trigger.label();
    match crate::fixture::reload_sources(sources) {
        Ok(fixtures) => {
            state.swap_fixtures_unchecked(fixtures);
            if verbose {
                eprintln!("[llmposter] {} reload: fixtures swapped", label);
            }
        }
        Err(e) => {
            eprintln!(
                "[llmposter] {} reload parse failed, keeping old fixtures: {}",
                label, e
            );
        }
    }
}

/// Spawn a background OS thread that debounces file-system events for
/// `sources` and calls [`reload_and_swap`] on each batch. The thread holds a
/// `Weak<AppState>`, so it exits on the next event after the server is dropped.
///
/// Only watches paths that exist at spawn time. Recursive for directories,
/// single-file for files. Uses `notify-debouncer-mini` with a 250ms debounce
/// window to collapse editor "save as temp → rename" sequences into a single
/// reload.
#[cfg(feature = "watch")]
fn spawn_file_watcher(
    state: std::sync::Weak<AppState>,
    sources: Vec<std::path::PathBuf>,
    verbose: bool,
) -> Option<std::thread::JoinHandle<()>> {
    use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode};
    use std::time::Duration;

    let (tx, rx) = std::sync::mpsc::channel();
    let mut debouncer = match new_debouncer(Duration::from_millis(250), tx) {
        Ok(d) => d,
        Err(e) => return log_watcher_setup_failure(e),
    };

    // Register each source independently. If one path fails (e.g. was
    // deleted between load and build), log and continue so the remaining
    // paths still get watched. Only bail entirely when every source fails.
    let mut watched_any = false;
    for path in &sources {
        let mode = if path.is_dir() {
            RecursiveMode::Recursive
        } else {
            RecursiveMode::NonRecursive
        };
        match debouncer.watcher().watch(path, mode) {
            Ok(()) => {
                watched_any = true;
            }
            Err(e) => {
                eprintln!(
                    "[llmposter] file watcher failed to watch {}: {}",
                    path.display(),
                    e
                );
            }
        }
    }
    if !watched_any {
        eprintln!(
            "[llmposter] file watcher: no sources could be registered ({} tried), giving up",
            sources.len()
        );
        return None;
    }

    Some(std::thread::spawn(move || {
        // The debouncer must live as long as this thread; when the thread
        // exits, the debouncer drops and `rx` closes.
        let _debouncer = debouncer;
        watcher_loop(&state, &sources, verbose, &rx);
    }))
}

/// Log a debouncer setup failure and return `None` from
/// `spawn_file_watcher`. Extracted into its own helper so the error arm
/// in the `match` is one line and the (rare) OS-failure path can be
/// covered by a unit test without driving a real notify failure.
#[cfg(feature = "watch")]
fn log_watcher_setup_failure(
    e: notify_debouncer_mini::notify::Error,
) -> Option<std::thread::JoinHandle<()>> {
    eprintln!("[llmposter] file watcher setup failed: {}", e);
    None
}

/// File-watcher polling loop. Extracted from `spawn_file_watcher` so tests
/// can drive it directly with a controlled channel and `Weak<AppState>`,
/// bypassing the real debouncer's OS-level setup and shutdown costs.
///
/// Polls `state.upgrade()` every 500ms (via `recv_timeout`) so an idle
/// watcher exits within half a second of `MockServer::drop`, even when no
/// filesystem event ever arrives.
#[cfg(feature = "watch")]
fn watcher_loop(
    state: &std::sync::Weak<AppState>,
    sources: &[std::path::PathBuf],
    verbose: bool,
    rx: &std::sync::mpsc::Receiver<
        Result<Vec<notify_debouncer_mini::DebouncedEvent>, notify_debouncer_mini::notify::Error>,
    >,
) {
    use std::sync::mpsc::RecvTimeoutError;
    loop {
        if state.upgrade().is_none() {
            return;
        }
        match rx.recv_timeout(std::time::Duration::from_millis(500)) {
            Ok(Ok(_events)) => {
                let Some(arc) = state.upgrade() else {
                    return;
                };
                reload_and_swap(&arc, sources, verbose, ReloadTrigger::Watch);
            }
            Ok(Err(e)) => {
                eprintln!("[llmposter] file watcher error: {}", e);
            }
            Err(RecvTimeoutError::Timeout) => {
                // Loop back to the Weak::upgrade() check above.
            }
            Err(RecvTimeoutError::Disconnected) => {
                return;
            }
        }
    }
}

/// Log a tokio signal-setup failure. Extracted so the error arm in
/// `spawn_sighup_handler` is one line and the rare OS-level failure
/// path is unit-testable.
#[cfg(unix)]
fn log_sighup_setup_failure(e: std::io::Error) {
    eprintln!("[llmposter] SIGHUP handler setup failed: {}", e);
}

/// Log a spawn_blocking panic from the SIGHUP reload worker. Unit-
/// testable helper for the (unreachable-in-practice) panic path.
#[cfg(unix)]
fn log_sighup_reload_panic(e: tokio::task::JoinError) {
    eprintln!("[llmposter] SIGHUP reload worker panicked: {}", e);
}

/// Install a `SIGHUP` handler that reloads fixtures on each signal.
///
/// Traditional Unix convention: `kill -HUP <pid>` tells a daemon to re-read
/// its config. The handler holds a `Weak<AppState>` and polls it every
/// 500ms (via a tokio interval inside `tokio::select!`) so it exits cleanly
/// within half a second of the server being dropped, even if no signal
/// ever arrives.
///
/// `SIGHUP` is process-wide. When multiple `MockServer` instances run in the
/// same process, each installs its own handler and all reload on every
/// signal — this is fine because each has its own source list.
#[cfg(unix)]
fn spawn_sighup_handler(
    state: std::sync::Weak<AppState>,
    sources: Vec<std::path::PathBuf>,
    verbose: bool,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        use tokio::signal::unix::{signal, SignalKind};
        let mut sig = match signal(SignalKind::hangup()) {
            Ok(s) => s,
            Err(e) => return log_sighup_setup_failure(e),
        };
        // 500ms shutdown-check interval. Skip the immediate first tick so
        // the initial loop iteration blocks on `sig.recv()` rather than
        // wasting a cycle on the shutdown check.
        let mut shutdown_check = tokio::time::interval(std::time::Duration::from_millis(500));
        shutdown_check.tick().await;

        loop {
            // Upgrade at the top of each iteration and KEEP the Arc
            // alive for the duration of the tick. This prevents the
            // race between "state alive at top check" and "state dead
            // inside the signal arm" that would otherwise need an
            // extra None-check after `sig.recv()`.
            let Some(arc_tick) = state.upgrade() else {
                return;
            };
            let got_signal = tokio::select! {
                recv = sig.recv() => recv.is_some(),
                _ = shutdown_check.tick() => false,
            };
            if got_signal {
                // Off-load the synchronous std::fs + YAML parse to
                // spawn_blocking so we don't stall a tokio worker
                // thread for the duration. The file-watcher path
                // uses `std::thread::spawn` for the same reason.
                let arc = arc_tick.clone();
                let sources_clone = sources.clone();
                let blocking = tokio::task::spawn_blocking(move || {
                    reload_and_swap(&arc, &sources_clone, verbose, ReloadTrigger::Sighup);
                });
                if let Err(e) = blocking.await {
                    log_sighup_reload_panic(e);
                }
            }
        }
    })
}

/// Format a UNIX timestamp as an RFC 3339 UTC string (e.g. "2026-03-22T10:30:00Z").
fn format_rfc3339_utc(epoch_secs: u64) -> String {
    const SECS_PER_DAY: u64 = 86400;
    const DAYS_PER_400Y: u64 = 146097;
    const DAYS_PER_100Y: u64 = 36524;
    const DAYS_PER_4Y: u64 = 1461;
    const DAYS_PER_Y: u64 = 365;
    let secs = epoch_secs % SECS_PER_DAY;
    let hour = secs / 3600;
    let min = (secs % 3600) / 60;
    let sec = secs % 60;

    let days = epoch_secs / SECS_PER_DAY + 719468; // shift to 0000-03-01
    let era = days / DAYS_PER_400Y;
    let doe = days - era * DAYS_PER_400Y;
    let yoe = (doe - doe / (DAYS_PER_4Y - 1) + doe / DAYS_PER_100Y - doe / (DAYS_PER_400Y - 1))
        / DAYS_PER_Y;
    let y = yoe + era * 400;
    let doy = doe - (DAYS_PER_Y * yoe + yoe / 4 - yoe / 100);
    let mut m = (5 * doy + 2) / 153;
    let d = doy - (153 * m + 2) / 5 + 1;
    m = if m < 10 { m + 3 } else { m - 9 };
    let year = if m <= 2 { y + 1 } else { y };

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, m, d, hour, min, sec
    )
}

/// Handler for `GET /code/200`, `GET /code/429`, etc. — returns the requested
/// HTTP status code. The path segment is a numeric status code (100–599).
/// Useful for testing client error-handling without writing a fixture.
/// 3xx responses include a `Location: /` header. 429 responses get rate-limit
/// headers automatically via the `add_response_headers` middleware.
async fn handle_status_code(
    State(state): State<Arc<AppState>>,
    Path(raw_code): Path<String>,
) -> Response<Body> {
    // Parse the path segment ourselves (rather than using `Path<u16>`)
    // so non-numeric `/code/abc` requests still reach capture as
    // `BadRequest` instead of being rejected by axum's extractor
    // before we see them.
    let parsed = raw_code.parse::<u16>().ok();
    let validated = parsed
        .and_then(|c| StatusCode::from_u16(c).ok())
        .filter(|s| s.as_u16() <= 599);

    let outcome = if validated.is_some() {
        RequestOutcome::CodeEndpoint
    } else {
        RequestOutcome::BadRequest
    };
    crate::handler::capture_non_matched(&state, "GET", &format!("/code/{}", raw_code), "", outcome);

    match validated {
        Some(status) => {
            // 1xx, 204, 205, 304 must not have a body per HTTP spec
            if status.as_u16() < 200
                || status == StatusCode::NO_CONTENT
                || status == StatusCode::RESET_CONTENT
                || status == StatusCode::NOT_MODIFIED
            {
                return Response::builder()
                    .status(status)
                    .body(Body::empty())
                    .expect("static headers");
            }
            let description = status.canonical_reason().unwrap_or("Unknown");
            let code = status.as_u16();
            let body = serde_json::json!({"code": code, "description": description}).to_string();
            let mut builder = Response::builder()
                .status(status)
                .header(header::CONTENT_TYPE, "application/json");
            if status.is_redirection() {
                builder = builder.header(header::LOCATION, "/");
            }
            builder.body(Body::from(body)).expect("static headers")
        }
        None => Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(
                r#"{"code":400,"description":"Invalid status code — use 100-599"}"#,
            ))
            .expect("static headers"),
    }
}

/// Middleware: adds x-request-id to every response, provider-specific rate limit headers on 429.
async fn add_response_headers(
    State(state): State<Arc<AppState>>,
    request: axum::extract::Request,
    next: Next,
) -> axum::response::Response {
    let path = request.uri().path().to_string();
    let mut resp = next.run(request).await;
    let request_id = state.next_request_id();
    resp.headers_mut()
        .insert("x-request-id", request_id.parse().unwrap());

    // Auto-emit rate limit headers on 429 responses.
    // retry-after: 60 is emitted for ALL providers first, then provider-specific headers.
    if resp.status() == StatusCode::TOO_MANY_REQUESTS {
        let headers = resp.headers_mut();
        // Common to all providers:
        headers
            .entry("retry-after")
            .or_insert("60".parse().unwrap());

        if path.starts_with("/v1/messages") {
            // Anthropic: additional anthropic-ratelimit-requests-{limit,remaining,reset}
            // Reset is an RFC 3339 timestamp 60s in the future per Anthropic spec.
            let reset_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                + 60;
            let reset_ts = format_rfc3339_utc(reset_secs);
            headers
                .entry("anthropic-ratelimit-requests-limit")
                .or_insert("100".parse().unwrap());
            headers
                .entry("anthropic-ratelimit-requests-remaining")
                .or_insert("0".parse().unwrap());
            headers
                .entry("anthropic-ratelimit-requests-reset")
                .or_insert(reset_ts.parse().unwrap());
        } else if path.starts_with("/v1beta/models") {
            // Gemini: no additional provider-specific headers (retry-after set above)
        } else {
            // OpenAI (chat completions + responses): x-ratelimit-*
            headers
                .entry("x-ratelimit-limit-requests")
                .or_insert("100".parse().unwrap());
            headers
                .entry("x-ratelimit-remaining-requests")
                .or_insert("0".parse().unwrap());
            headers
                .entry("x-ratelimit-reset-requests")
                .or_insert("1m0s".parse().unwrap());
        }
    }

    resp
}

/// Forward an `axum::serve` result to the caller via the `server_error`
/// oneshot. Logs and sends on `Err`, no-ops on `Ok`. Extracted from the
/// spawned task body so unit tests can exercise the error path without
/// having to force a real `axum::serve` failure.
fn report_serve_result(result: std::io::Result<()>, err_tx: tokio::sync::oneshot::Sender<String>) {
    if let Err(e) = result {
        let msg = format!("[llmposter] server error: {}", e);
        eprintln!("{}", msg);
        let _ = err_tx.send(msg);
    }
}

/// Builder for configuring and starting a [`MockServer`].
///
/// Use method chaining to add fixtures, set bind address, enable auth, then call
/// [`build()`](Self::build) to start the server.
pub struct ServerBuilder {
    fixtures: Vec<Fixture>,
    /// Paths passed to [`load_yaml`](Self::load_yaml) or [`load_yaml_dir`](Self::load_yaml_dir).
    /// Used by hot-reload (`--watch` and SIGHUP) to know what to re-read.
    fixture_sources: Vec<std::path::PathBuf>,
    /// Enable file-watching hot-reload of `fixture_sources`.
    #[cfg(feature = "watch")]
    watch_enabled: bool,
    bind_addr: String,
    verbose: bool,
    auth_enabled: bool,
    bearer_tokens: Vec<(String, Option<u64>)>,
    #[cfg(feature = "oauth")]
    oauth_config: Option<OAuthConfig>,
    /// Upper bound on captured-request count. See [`Self::capture_capacity`].
    capture_capacity: Option<usize>,
}

impl ServerBuilder {
    /// Creates a new builder with default settings (bind to `127.0.0.1:0`, no auth).
    pub fn new() -> Self {
        Self {
            fixtures: Vec::new(),
            fixture_sources: Vec::new(),
            #[cfg(feature = "watch")]
            watch_enabled: false,
            bind_addr: "127.0.0.1:0".to_string(),
            verbose: false,
            auth_enabled: false,
            bearer_tokens: Vec::new(),
            #[cfg(feature = "oauth")]
            oauth_config: None,
            capture_capacity: None,
        }
    }

    /// Cap the captured-request log at `max` entries. When the log fills,
    /// the oldest entry is dropped to make room for each new one (FIFO).
    ///
    /// Defaults to unbounded so short-lived `#[tokio::test]` servers can
    /// call `get_requests()` once and see every request. Long-lived
    /// standalone servers should set this to cap memory use — the body
    /// field alone can be multi-KB per entry.
    ///
    /// **`capture_capacity(0)` disables capture entirely.** Nothing is
    /// pushed to the log, `get_requests()` always returns an empty
    /// `Vec`, and `request_count()` always returns 0. Use this when
    /// running under memory pressure and you don't need the capture
    /// API at all — it's measurably cheaper than the default
    /// (unbounded) path because `push_captured` short-circuits before
    /// taking the write lock contents.
    pub fn capture_capacity(mut self, max: usize) -> Self {
        self.capture_capacity = Some(max);
        self
    }

    /// Appends a single fixture to the server's match list.
    pub fn fixture(mut self, f: Fixture) -> Self {
        self.fixtures.push(f);
        self
    }

    /// Appends multiple fixtures to the server's match list.
    pub fn fixtures(mut self, fixtures: Vec<Fixture>) -> Self {
        self.fixtures.extend(fixtures);
        self
    }

    /// Returns the number of fixtures currently staged in the builder.
    /// Useful for callers (e.g. the CLI) that want to warn when nothing was loaded.
    pub fn fixture_count(&self) -> usize {
        self.fixtures.len()
    }

    /// Sets the TCP bind address (e.g. `"127.0.0.1:8080"`). Defaults to `"127.0.0.1:0"` (random port).
    pub fn bind(mut self, addr: &str) -> Self {
        self.bind_addr = addr.to_string();
        self
    }

    /// Enables or disables verbose logging of matched fixtures and request details.
    pub fn verbose(mut self, v: bool) -> Self {
        self.verbose = v;
        self
    }

    /// Enable or disable auth enforcement on all LLM endpoints.
    /// When enabled, requests without a valid `Authorization: Bearer <token>` header
    /// receive a provider-specific HTTP 401 response.
    pub fn with_auth(mut self, enabled: bool) -> Self {
        self.auth_enabled = enabled;
        self
    }

    /// Register a bearer token with unlimited uses and implicitly enable auth.
    /// Requests with `Authorization: Bearer <token>` are accepted; requests without
    /// a valid token receive HTTP 401.
    pub fn with_bearer_token(mut self, token: &str) -> Self {
        self.auth_enabled = true;
        self.bearer_tokens.push((token.to_string(), None));
        self
    }

    /// Register a bearer token that expires after `max_uses` requests, and
    /// implicitly enable auth. After exhaustion, the token returns HTTP 401.
    /// Use this to test token refresh flows deterministically (no real-time clocks).
    pub fn with_bearer_token_uses(mut self, token: &str, max_uses: u64) -> Self {
        self.auth_enabled = true;
        self.bearer_tokens.push((token.to_string(), Some(max_uses)));
        self
    }

    /// Enable the embedded OAuth server with custom client configuration.
    #[cfg(feature = "oauth")]
    pub fn with_oauth(mut self, config: OAuthConfig) -> Self {
        self.auth_enabled = true;
        self.oauth_config = Some(config);
        self
    }

    /// Enable the embedded OAuth server with default client credentials
    /// (client_id: "mock-client", client_secret: "mock-secret").
    #[cfg(feature = "oauth")]
    pub fn with_oauth_defaults(mut self) -> Self {
        self.auth_enabled = true;
        self.oauth_config = Some(OAuthConfig::default());
        self
    }

    /// Loads fixtures from a single YAML file and appends them to the match list.
    ///
    /// The path is also recorded as a hot-reload source. When [`watch`](Self::watch)
    /// is enabled (or the process receives `SIGHUP` on Unix), this file is re-read
    /// and the fixture list is atomically swapped.
    pub fn load_yaml(mut self, path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
        let fixtures = crate::fixture::load_yaml_file(path)?;
        self.fixtures.extend(fixtures);
        self.fixture_sources.push(path.to_path_buf());
        Ok(self)
    }

    /// Loads fixtures from all YAML files in a directory and appends them to the match list.
    ///
    /// The directory path is also recorded as a hot-reload source. When
    /// [`watch`](Self::watch) is enabled (or the process receives `SIGHUP` on Unix),
    /// the directory is re-scanned and the fixture list is atomically swapped.
    pub fn load_yaml_dir(
        mut self,
        dir: &std::path::Path,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let fixtures = crate::fixture::load_yaml_dir(dir)?;
        self.fixtures.extend(fixtures);
        self.fixture_sources.push(dir.to_path_buf());
        Ok(self)
    }

    /// Enable file-watching hot-reload for any files or directories loaded via
    /// [`load_yaml`](Self::load_yaml) or [`load_yaml_dir`](Self::load_yaml_dir).
    ///
    /// When a change is detected (debounced by ~250ms), all tracked sources are
    /// re-read, validated, and atomically swapped. If parsing or validation
    /// fails, the previously loaded fixtures continue serving unchanged and the
    /// error is logged to stderr — a partial edit or invalid YAML will never
    /// take down the live server.
    ///
    /// Programmatically-added fixtures (via [`fixture`](Self::fixture) or
    /// [`fixtures`](Self::fixtures)) are **not** affected by watching: only
    /// file-backed fixtures are reloaded.
    ///
    /// Requires the `watch` feature (enabled by default).
    ///
    /// On Unix, `SIGHUP` also triggers a reload — always on whenever any
    /// fixture source path is tracked, regardless of this flag. This matches
    /// traditional daemon conventions so `kill -HUP <pid>` works out of the box.
    #[cfg(feature = "watch")]
    pub fn watch(mut self, enabled: bool) -> Self {
        self.watch_enabled = enabled;
        self
    }

    /// Validates all fixtures, starts the HTTP server, and returns a running [`MockServer`].
    ///
    /// Returns an error if any fixture is invalid or the bind address is unavailable.
    pub async fn build(mut self) -> Result<MockServer, Box<dyn std::error::Error>> {
        // Validate all fixtures (including programmatically-added ones)
        for (i, fixture) in self.fixtures.iter_mut().enumerate() {
            fixture
                .validate()
                .map_err(|e| format!("Fixture #{}: {}", i + 1, e))?;
        }

        // Spawn the embedded oauth-mock server if configured.
        #[cfg(feature = "oauth")]
        let oauth_server = if let Some(ref config) = self.oauth_config {
            let redirect_uris: Vec<&str> =
                config.redirect_uris.iter().map(String::as_str).collect();
            let scopes: Vec<&str> = config.scopes.iter().map(String::as_str).collect();
            let oauth = oauth_mock::MockServer::builder()
                .with_client(
                    &config.client_id,
                    &config.client_secret,
                    redirect_uris,
                    scopes,
                )
                .spawn_on_free_port()
                .await
                .map_err(|e| format!("Failed to start OAuth server: {}", e))?;
            Some(oauth)
        } else {
            None
        };

        let auth = if self.auth_enabled {
            let auth_state = crate::auth::AuthState::new();
            for (token, max_uses) in &self.bearer_tokens {
                auth_state.add_token(token, *max_uses);
            }
            // Bridge oauth-mock token validation via introspect endpoint.
            #[cfg(feature = "oauth")]
            if let Some(ref oauth) = oauth_server {
                if let Some(ref config) = self.oauth_config {
                    auth_state.set_oauth_introspect(crate::auth::OAuthIntrospect {
                        url: format!("{}/introspect", oauth.base_url()),
                        client_id: config.client_id.clone(),
                        client_secret: config.client_secret.clone(),
                        client: reqwest::Client::builder()
                            .timeout(std::time::Duration::from_secs(5))
                            .build()
                            .map_err(|e| {
                                format!("Failed to build OAuth introspect client: {}", e)
                            })?,
                    });
                }
            }
            Some(auth_state)
        } else {
            None
        };

        let arced_fixtures: Vec<Arc<Fixture>> = self.fixtures.into_iter().map(Arc::new).collect();
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(arced_fixtures),
            id_gen: IdGenerator::new(),
            verbose: self.verbose,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: self.capture_capacity,
        });

        // Spawn hot-reload watchers if fixture sources are tracked.
        // The file watcher is opt-in via `.watch(true)`; SIGHUP (Unix) is
        // always on for file-backed fixtures so `kill -HUP <pid>` works.
        // Handles are intentionally detached — both workers hold a
        // `Weak<AppState>` and exit within ~500ms of `MockServer::drop`.
        if !self.fixture_sources.is_empty() {
            #[cfg(feature = "watch")]
            if self.watch_enabled {
                let _watcher = spawn_file_watcher(
                    Arc::downgrade(&state),
                    self.fixture_sources.clone(),
                    self.verbose,
                );
            }
            #[cfg(unix)]
            let _sighup = spawn_sighup_handler(
                Arc::downgrade(&state),
                self.fixture_sources.clone(),
                self.verbose,
            );
        }

        let server_state = state.clone(); // keep for MockServer API access
        let app = Router::new()
            .route("/v1/chat/completions", post(crate::handler::openai::handle))
            .route("/v1/messages", post(crate::handler::anthropic::handle))
            .route("/v1/responses", post(crate::handler::responses::handle))
            .route(
                "/v1beta/models/{*path}",
                post(crate::handler::gemini::handle),
            )
            .route("/code/{status}", get(handle_status_code))
            .layer(axum::extract::DefaultBodyLimit::max(16 * 1024 * 1024)) // 16 MB (inner)
            .layer(middleware::from_fn_with_state(
                state.clone(),
                crate::auth::bearer_auth_check,
            ))
            .layer(middleware::from_fn_with_state(
                state.clone(),
                add_response_headers,
            ))
            .with_state(state);

        let listener = TcpListener::bind(&self.bind_addr).await?;
        let addr = listener.local_addr()?;

        let (err_tx, err_rx) = tokio::sync::oneshot::channel::<String>();
        let handle = tokio::spawn(async move {
            report_serve_result(axum::serve(listener, app).await, err_tx);
        });

        Ok(MockServer {
            addr,
            _handle: handle,
            server_error: tokio::sync::Mutex::new(err_rx),
            state: server_state,
            #[cfg(feature = "oauth")]
            oauth_server,
        })
    }
}

impl Default for ServerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// A running mock LLM API server.
///
/// Created via [`ServerBuilder::build()`]. The server runs on a random port by default
/// and stops when dropped. Use [`url()`](Self::url) to get the base URL for client configuration.
pub struct MockServer {
    addr: std::net::SocketAddr,
    _handle: tokio::task::JoinHandle<()>,
    /// Check for post-bind server errors via `check_error()`.
    server_error: tokio::sync::Mutex<tokio::sync::oneshot::Receiver<String>>,
    /// Shared state — used for request capture and scenario queries.
    state: Arc<AppState>,
    /// Embedded OAuth server (dropped together with MockServer).
    #[cfg(feature = "oauth")]
    oauth_server: Option<oauth_mock::MockServer>,
}

impl std::fmt::Debug for MockServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MockServer")
            .field("addr", &self.addr)
            .finish()
    }
}

impl MockServer {
    /// Returns the base URL of the running server (e.g. `"http://127.0.0.1:12345"`).
    pub fn url(&self) -> String {
        format!("http://{}", self.addr)
    }

    /// Returns the TCP port the server is listening on.
    pub fn port(&self) -> u16 {
        self.addr.port()
    }

    /// Returns the base URL of the embedded OAuth server, if configured.
    #[cfg(feature = "oauth")]
    pub fn oauth_url(&self) -> Option<String> {
        self.oauth_server.as_ref().map(|s| s.base_url().to_string())
    }

    /// Returns the default OAuth client credentials (client_id, client_secret).
    #[cfg(feature = "oauth")]
    pub async fn oauth_client_credentials(&self) -> Option<(String, String)> {
        match &self.oauth_server {
            Some(s) => s.default_client().await,
            None => None,
        }
    }

    /// Approve a device code by user_code (for device authorization flow tests).
    #[cfg(feature = "oauth")]
    pub async fn approve_device_code(
        &self,
        user_code: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        match &self.oauth_server {
            Some(s) => Ok(s.approve_device_code(user_code).await?),
            None => Err("OAuth not configured".into()),
        }
    }

    /// Check whether the server encountered a post-bind error.
    ///
    /// Returns `Ok(())` if healthy, or `Err(message)` if the server task failed.
    /// The error is consumed on first call — subsequent calls return `Ok(())`.
    pub async fn check_error(&self) -> Result<(), String> {
        let mut rx = self.server_error.lock().await;
        match rx.try_recv() {
            Ok(msg) => Err(msg),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty) => Ok(()),
            Err(tokio::sync::oneshot::error::TryRecvError::Closed) => Ok(()),
        }
    }

    /// Returns all captured requests received by this server, in order.
    ///
    /// Each request includes the method, path, body, matched scenario name, and timestamp.
    pub fn get_requests(&self) -> Vec<CapturedRequest> {
        self.state
            .captured_requests
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .cloned()
            .collect()
    }

    /// Returns the number of requests captured so far.
    pub fn request_count(&self) -> usize {
        self.state
            .captured_requests
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .len()
    }

    /// Returns the number of fixtures currently active on the running server.
    ///
    /// Reflects live state after any [`set_fixtures`](Self::set_fixtures)
    /// swap or hot-reload, so tests can assert that a reload picked up the
    /// expected fixture count without rebuilding the server.
    pub fn fixture_count(&self) -> usize {
        self.state
            .fixtures
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .len()
    }

    /// Returns the current state of a named scenario, or `None` if the scenario
    /// has not been entered yet.
    pub fn scenario_state(&self, name: &str) -> Option<String> {
        self.state
            .scenarios
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .get(name)
            .cloned()
    }

    /// Atomically replaces the server's fixture list at runtime.
    ///
    /// Every fixture is validated before the swap — if any fixture is invalid,
    /// an error is returned and the existing fixtures continue to serve requests
    /// unchanged. On success, subsequent requests match against the new list.
    ///
    /// Use this for hot-reload scenarios (e.g. reloading a YAML file after edits)
    /// or for test setups that mutate the fixture list between phases.
    pub fn set_fixtures(
        &self,
        fixtures: Vec<Fixture>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.state.set_fixtures(fixtures)
    }

    /// Resets all scenario states and clears captured requests.
    pub fn reset(&self) {
        self.state
            .scenarios
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
        self.state
            .captured_requests
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }
}

impl Drop for MockServer {
    fn drop(&mut self) {
        self._handle.abort();
    }
}

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

    #[tokio::test]
    async fn should_build_and_start_server() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("test"))
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
        assert!(server.url().starts_with("http://127.0.0.1:"));
    }

    #[tokio::test]
    async fn should_return_404_for_unknown_routes() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("test"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/unknown", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
    }

    #[tokio::test]
    async fn should_support_custom_bind_address() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("test"))
            .bind("127.0.0.1:0")
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
    }

    #[tokio::test]
    async fn should_support_default_builder() {
        let builder = ServerBuilder::default();
        let server = builder
            .fixture(Fixture::new().respond_with_content("default"))
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
    }

    #[tokio::test]
    async fn should_support_fixtures_vec() {
        let fixtures = vec![
            Fixture::new()
                .match_user_message("a")
                .respond_with_content("A"),
            Fixture::new()
                .match_user_message("b")
                .respond_with_content("B"),
        ];
        let server = ServerBuilder::new()
            .fixtures(fixtures)
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
    }

    #[tokio::test]
    async fn should_support_verbose_mode() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("test"))
            .verbose(true)
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
    }

    #[tokio::test]
    async fn should_load_yaml_file() {
        let dir = std::env::temp_dir().join("llmposter_server_test_yaml");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("test.yaml");
        std::fs::write(
            &file,
            "fixtures:\n  - match:\n      user_message: test\n    response:\n      content: loaded",
        )
        .unwrap();
        let server = ServerBuilder::new()
            .load_yaml(&file)
            .unwrap()
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn should_load_yaml_dir() {
        let dir = std::env::temp_dir().join("llmposter_server_test_dir");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("a.yaml"),
            "fixtures:\n  - response:\n      content: a",
        )
        .unwrap();
        let server = ServerBuilder::new()
            .load_yaml_dir(&dir)
            .unwrap()
            .build()
            .await
            .unwrap();
        assert!(server.port() > 0);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn should_return_error_when_bind_address_invalid() {
        // Hits the `TcpListener::bind(...).await?` error branch in
        // `ServerBuilder::build`: the address is malformed, bind fails, the
        // `?` propagates an io error, and the builder returns it.
        let result = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .bind("not-a-valid-address")
            .build()
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn should_return_error_when_load_yaml_file_missing() {
        // Hits the `?` error branch in `ServerBuilder::load_yaml`: the file
        // doesn't exist, `load_yaml_file` propagates an error, and the
        // builder returns it.
        let missing = std::path::Path::new("/nonexistent/llmposter/does-not-exist.yaml");
        let result = ServerBuilder::new().load_yaml(missing);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn should_return_error_when_load_yaml_dir_missing() {
        // Hits the `?` error branch in `ServerBuilder::load_yaml_dir`.
        let missing = std::path::Path::new("/nonexistent/llmposter/does-not-exist-dir");
        let result = ServerBuilder::new().load_yaml_dir(missing);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn should_return_error_on_invalid_fixture() {
        let result = ServerBuilder::new()
            .fixture(Fixture::new()) // no response or error
            .build()
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Fixture #1"));
    }

    #[test]
    fn should_format_rfc3339_unix_epoch() {
        assert_eq!(format_rfc3339_utc(0), "1970-01-01T00:00:00Z");
    }

    #[test]
    fn should_format_rfc3339_one_day() {
        assert_eq!(format_rfc3339_utc(86400), "1970-01-02T00:00:00Z");
    }

    #[test]
    fn should_format_rfc3339_valid_format() {
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let ts = format_rfc3339_utc(now_secs + 60);
        // Must be valid RFC 3339: YYYY-MM-DDTHH:MM:SSZ
        assert!(ts.ends_with('Z'));
        assert!(ts.contains('T'));
        assert_eq!(ts.len(), 20); // "YYYY-MM-DDTHH:MM:SSZ"
    }

    #[tokio::test]
    async fn should_report_healthy_when_no_error() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        assert!(server.check_error().await.is_ok());
    }

    /// Build a bare-bones `MockServer` wrapping a supplied oneshot receiver.
    /// Only used by the check_error unit tests below — it bypasses the listener
    /// entirely so we can exercise the three `try_recv` arms deterministically.
    fn mock_server_with_err_rx(err_rx: tokio::sync::oneshot::Receiver<String>) -> MockServer {
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });
        // A no-op task handle — `std::future::ready` avoids spawning an
        // empty async-block, which llvm-cov would otherwise treat as a
        // separately-instrumented (and unreachable) region.
        let handle = tokio::spawn(std::future::ready(()));
        MockServer {
            addr: "127.0.0.1:0".parse().unwrap(),
            _handle: handle,
            server_error: tokio::sync::Mutex::new(err_rx),
            state,
            #[cfg(feature = "oauth")]
            oauth_server: None,
        }
    }

    #[tokio::test]
    async fn should_report_error_when_server_task_sent_error() {
        // Simulates the `Ok(msg) => Err(msg)` arm in check_error: the server
        // task hit an error post-bind and sent it through the oneshot.
        let (tx, rx) = tokio::sync::oneshot::channel::<String>();
        tx.send("[llmposter] server error: boom".to_string())
            .unwrap();
        let server = mock_server_with_err_rx(rx);

        let result = server.check_error().await;
        assert!(
            result.is_err(),
            "expected Err after tx.send, got {:?}",
            result
        );
        let msg = result.unwrap_err();
        assert!(msg.contains("boom"), "unexpected error body: {}", msg);
    }

    #[tokio::test]
    async fn should_report_healthy_when_error_channel_closed_without_send() {
        // Simulates the `Closed` arm: the server task exited (or its sender
        // was dropped) without ever emitting an error. check_error should
        // treat this as healthy.
        let (tx, rx) = tokio::sync::oneshot::channel::<String>();
        drop(tx);
        let server = mock_server_with_err_rx(rx);

        assert!(server.check_error().await.is_ok());
    }

    #[tokio::test]
    async fn should_return_requested_status_code() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/200", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["code"], 200);
        assert_eq!(body["description"], "OK");
    }

    #[tokio::test]
    async fn should_return_404_status_from_code_route() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/404", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["code"], 404);
        assert_eq!(body["description"], "Not Found");
    }

    #[tokio::test]
    async fn should_return_500_status_from_code_route() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/500", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 500);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["code"], 500);
    }

    #[tokio::test]
    async fn should_add_location_header_on_redirect() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();
        let resp = client
            .get(format!("{}/code/301", server.url()))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 301);
        assert_eq!(resp.headers().get("location").unwrap(), "/");
    }

    #[tokio::test]
    async fn should_return_bad_request_for_invalid_status_code() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/999", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 400);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["code"], 400);
    }

    #[tokio::test]
    async fn should_return_empty_body_for_204() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/204", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 204);
        let body = resp.text().await.unwrap();
        assert!(body.is_empty(), "204 should have empty body, got: {}", body);
    }

    #[tokio::test]
    async fn should_return_empty_body_for_304() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/304", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 304);
        let body = resp.text().await.unwrap();
        assert!(body.is_empty(), "304 should have empty body, got: {}", body);
    }

    #[tokio::test]
    async fn should_return_empty_body_for_205() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/205", server.url()))
            .await
            .unwrap();
        assert_eq!(resp.status(), 205);
        let body = resp.text().await.unwrap();
        assert!(body.is_empty(), "205 should have empty body, got: {}", body);
    }

    #[tokio::test]
    async fn should_return_empty_body_for_1xx_status() {
        let server = ServerBuilder::new()
            .fixture(Fixture::new().respond_with_content("ok"))
            .build()
            .await
            .unwrap();
        let resp = reqwest::get(format!("{}/code/100", server.url()))
            .await
            .unwrap();
        // hyper may not forward 1xx as a final response — it returns 200 or the
        // status itself depending on the HTTP version. Just verify no panic.
        let _ = resp.text().await;
    }

    /// Build a `Weak<AppState>` whose `Arc` has already been dropped.
    /// Used to exercise the `state.upgrade() else { return; }` paths in the
    /// file watcher and SIGHUP handler without spinning up a real server.
    #[cfg(any(feature = "watch", unix))]
    fn dead_weak_state() -> std::sync::Weak<AppState> {
        let arc = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });
        let weak = Arc::downgrade(&arc);
        drop(arc);
        weak
    }

    #[cfg(feature = "watch")]
    #[tokio::test]
    async fn should_exit_file_watcher_thread_when_state_is_dropped() {
        // Hits the `Weak::upgrade() -> None` early-return in the watcher loop:
        // the background thread receives an event, fails to upgrade, and returns.
        let dir = std::env::temp_dir().join(format!(
            "llmposter_watcher_dead_weak_{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.yaml");
        std::fs::write(
            &file,
            "fixtures:\n  - match:\n      user_message: hi\n    response:\n      content: v1\n",
        )
        .unwrap();

        // Pass a dead Weak: the first event will fail to upgrade and the
        // watcher thread exits cleanly via the `else { return; }` branch.
        let handle = spawn_file_watcher(dead_weak_state(), vec![dir.clone()], false)
            .expect("watcher should spawn successfully");

        // Give the debouncer time to install its watch, then touch the file.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        std::fs::write(
            &file,
            "fixtures:\n  - match:\n      user_message: hi\n    response:\n      content: v2\n",
        )
        .unwrap();

        // Let the debouncer flush + watcher thread run the upgrade-None path.
        tokio::time::sleep(std::time::Duration::from_millis(600)).await;
        assert!(
            handle.is_finished(),
            "watcher thread should have exited via dead-weak upgrade path"
        );
        // `is_finished()` returns true for both clean exit and panic.
        // Joining propagates any panic so this test also guards against
        // regressions where the worker exits abnormally.
        handle.join().expect("watcher thread should exit cleanly");

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

    /// Drives the watcher loop body directly, proving the `Weak::upgrade()`
    /// check at the head of the loop returns immediately with a dead weak,
    /// without waiting for a filesystem event. Bypasses the real debouncer
    /// so the test never touches the OS file watcher API.
    #[cfg(feature = "watch")]
    #[test]
    fn should_return_from_watcher_loop_immediately_when_state_is_dead() {
        // `tx` stays alive so `rx` isn't Disconnected — this forces the exit
        // to come from the `state.upgrade().is_none()` early-return, not
        // from the channel closure path.
        let (_tx, rx) = std::sync::mpsc::channel::<
            Result<
                Vec<notify_debouncer_mini::DebouncedEvent>,
                notify_debouncer_mini::notify::Error,
            >,
        >();
        let start = std::time::Instant::now();
        watcher_loop(&dead_weak_state(), &[], false, &rx);
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(100),
            "dead-weak watcher_loop should return near-instantly, took {:?}",
            elapsed
        );
    }

    /// Exercises the `Ok(Err(notify::Error))` arm of `watcher_loop`.
    /// The loop logs the error and continues, so after we send a single
    /// synthetic notify error we drop the sender to force the
    /// `Disconnected` arm and unblock the loop.
    #[cfg(feature = "watch")]
    #[test]
    fn should_log_and_continue_on_watcher_notify_error() {
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });
        let weak = Arc::downgrade(&state);
        let (tx, rx) = std::sync::mpsc::channel::<
            Result<
                Vec<notify_debouncer_mini::DebouncedEvent>,
                notify_debouncer_mini::notify::Error,
            >,
        >();
        // Enqueue one synthetic notify error, then drop the sender so
        // the loop exits via the Disconnected arm on the next iteration.
        let err = notify_debouncer_mini::notify::Error::generic("synthetic test error");
        tx.send(Err(err)).expect("channel alive");
        drop(tx);
        let start = std::time::Instant::now();
        watcher_loop(&weak, &[], false, &rx);
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(200),
            "watcher_loop should drain the error + disconnect near-instantly, took {:?}",
            elapsed
        );
        drop(state);
    }

    /// Covers `log_watcher_setup_failure`'s eprintln + None return so
    /// the OS-level debouncer failure branch is exercised without
    /// actually inducing a notify::Error from the OS.
    #[cfg(feature = "watch")]
    #[test]
    fn should_log_and_return_none_on_watcher_setup_failure() {
        let err = notify_debouncer_mini::notify::Error::generic("synthetic");
        let result = log_watcher_setup_failure(err);
        assert!(result.is_none());
    }

    /// Covers `log_sighup_setup_failure`'s eprintln so the
    /// tokio-signal-setup error path is exercised without actually
    /// triggering a signal-handler install failure.
    #[cfg(unix)]
    #[test]
    fn should_log_sighup_setup_failure() {
        let err = std::io::Error::other("synthetic");
        log_sighup_setup_failure(err);
    }

    /// Covers `log_sighup_reload_panic` by synthesizing a real
    /// `tokio::task::JoinError` from a panicking spawn_blocking task.
    /// `JoinError` has no public constructor, so this is the only way
    /// to exercise the panic-logging branch.
    #[cfg(unix)]
    #[tokio::test]
    async fn should_log_sighup_reload_panic() {
        let handle = tokio::task::spawn_blocking(|| panic!("synthetic panic for test"));
        let err = handle
            .await
            .expect_err("spawn_blocking should propagate panic");
        log_sighup_reload_panic(err);
    }

    /// Drives the watcher loop body with a live weak and a silent channel
    /// so the `RecvTimeoutError::Timeout` arm fires at least once, then
    /// drops the state so the next iteration's top-of-loop upgrade check
    /// exits cleanly. Covers the `Timeout` branch which the other
    /// watcher_loop tests skip by exiting on the first iteration.
    #[cfg(feature = "watch")]
    #[test]
    fn should_loop_past_recv_timeout_when_state_is_alive() {
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });
        let weak = Arc::downgrade(&state);
        // Hold `tx` alive for the life of the spawned thread so
        // `recv_timeout` keeps returning Timeout instead of Disconnected
        // — the loop must iterate past the Timeout arm at least once.
        let (tx, rx) = std::sync::mpsc::channel::<
            Result<
                Vec<notify_debouncer_mini::DebouncedEvent>,
                notify_debouncer_mini::notify::Error,
            >,
        >();

        // Move `rx` + `weak` into a worker thread so the main thread can
        // drop `state` after the loop has started. `tx` stays on the
        // main thread to keep the channel alive across the drop.
        let worker = std::thread::spawn(move || {
            watcher_loop(&weak, &[], false, &rx);
        });

        // Wait long enough for at least one full recv_timeout cycle
        // (500ms) plus scheduler slack, then drop the strong reference.
        std::thread::sleep(std::time::Duration::from_millis(650));
        drop(state);

        // Worker must exit within another ~500ms (next top-of-loop check).
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(1200);
        while !worker.is_finished() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert!(
            worker.is_finished(),
            "watcher_loop should exit once state drops after hitting the Timeout arm"
        );
        worker.join().expect("watcher thread should exit cleanly");
        drop(tx);
    }

    /// Drives the watcher loop body with a live weak and then drops the
    /// sender mid-flight, proving the `RecvTimeoutError::Disconnected` arm
    /// unblocks and returns without waiting for any event.
    #[cfg(feature = "watch")]
    #[test]
    fn should_return_from_watcher_loop_when_sender_disconnects() {
        // Build a LIVE state so the first upgrade succeeds and we enter the
        // recv_timeout branch. Drop the sender so recv immediately returns
        // Disconnected.
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });
        let weak = Arc::downgrade(&state);
        let (tx, rx) = std::sync::mpsc::channel::<
            Result<
                Vec<notify_debouncer_mini::DebouncedEvent>,
                notify_debouncer_mini::notify::Error,
            >,
        >();
        drop(tx);
        let start = std::time::Instant::now();
        watcher_loop(&weak, &[], false, &rx);
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(100),
            "disconnected watcher_loop should return near-instantly, took {:?}",
            elapsed
        );
        drop(state);
    }

    #[tokio::test]
    async fn should_recover_from_poisoned_locks_in_mock_server_accessors() {
        // Poison every `RwLock` on `AppState` and confirm the accessors that
        // call `unwrap_or_else(|e| e.into_inner())` still return data instead
        // of panicking. This exercises the poison-recovery closures in
        // `get_requests`, `request_count`, `scenario_state`, `reset`, and
        // `swap_fixtures_unchecked`, which would otherwise only run if a
        // writer panicked mid-critical-section during real use.
        let state = Arc::new(AppState {
            fixtures: std::sync::RwLock::new(Vec::new()),
            id_gen: IdGenerator::new(),
            verbose: false,
            request_counter: AtomicU64::new(1),
            chaos_counter: AtomicU64::new(0),
            auth: None,
            scenarios: std::sync::RwLock::new(std::collections::HashMap::new()),
            captured_requests: std::sync::RwLock::new(std::collections::VecDeque::new()),
            capture_capacity: None,
        });

        // Poison all three RwLocks by panicking while holding a write guard.
        let s = state.clone();
        let _ = std::thread::spawn(move || {
            let _g = s.fixtures.write().unwrap();
            panic!("intentional poison for test");
        })
        .join();

        let s = state.clone();
        let _ = std::thread::spawn(move || {
            let _g = s.scenarios.write().unwrap();
            panic!("intentional poison for test");
        })
        .join();

        let s = state.clone();
        let _ = std::thread::spawn(move || {
            let _g = s.captured_requests.write().unwrap();
            panic!("intentional poison for test");
        })
        .join();

        assert!(state.fixtures.is_poisoned());
        assert!(state.scenarios.is_poisoned());
        assert!(state.captured_requests.is_poisoned());

        let (_tx, rx) = tokio::sync::oneshot::channel::<String>();
        let server = MockServer {
            addr: "127.0.0.1:0".parse().unwrap(),
            _handle: tokio::spawn(std::future::ready(())),
            server_error: tokio::sync::Mutex::new(rx),
            state: state.clone(),
            #[cfg(feature = "oauth")]
            oauth_server: None,
        };

        // get_requests -> captured_requests.read().unwrap_or_else(...)
        assert_eq!(server.get_requests().len(), 0);
        // request_count -> same lock
        assert_eq!(server.request_count(), 0);
        // scenario_state -> scenarios.read().unwrap_or_else(...)
        assert!(server.scenario_state("missing").is_none());
        // reset -> both scenarios.write() and captured_requests.write() poison paths
        server.reset();
        // set_fixtures -> swap_fixtures_unchecked -> fixtures.write().unwrap_or_else(...)
        server
            .set_fixtures(vec![Fixture::new().respond_with_content("after-poison")])
            .expect("poisoned-lock swap should still succeed");
    }

    #[tokio::test]
    async fn should_forward_serve_error_through_oneshot() {
        // Exercises the `Err` arm of `report_serve_result` directly: when
        // `axum::serve` returns an io error post-bind, the helper formats it,
        // logs to stderr, and pushes the message through the oneshot. This
        // mirrors what the spawned task does inside `ServerBuilder::build`.
        let (tx, rx) = tokio::sync::oneshot::channel::<String>();
        let err = std::io::Error::new(std::io::ErrorKind::ConnectionAborted, "listener gone");
        report_serve_result(Err(err), tx);

        let msg = rx.await.expect("sender should have forwarded the error");
        assert!(
            msg.contains("[llmposter] server error"),
            "unexpected framing: {}",
            msg
        );
        assert!(msg.contains("listener gone"), "missing cause: {}", msg);
    }

    #[tokio::test]
    async fn should_not_send_when_serve_returns_ok() {
        // The `Ok(())` path leaves the oneshot untouched so `check_error`
        // will observe `Closed` rather than an error once the task exits.
        let (tx, mut rx) = tokio::sync::oneshot::channel::<String>();
        report_serve_result(Ok(()), tx);

        // The sender is dropped when `report_serve_result` returns, so the
        // receiver should observe `Closed` on the next try_recv.
        let err = rx.try_recv().unwrap_err();
        assert_eq!(err, tokio::sync::oneshot::error::TryRecvError::Closed);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn should_exit_sighup_handler_when_state_is_dropped() {
        // Hits the `Weak::upgrade() -> None` early-return in the SIGHUP loop.
        // We install a handler with a dead Weak, then send SIGHUP to ourselves.
        // The handler receives the signal, fails to upgrade, and returns.
        let handle = spawn_sighup_handler(dead_weak_state(), vec![], false);

        // Give the handler a moment to install its signal listener.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // SAFETY: sending SIGHUP to our own PID is well-defined on Unix.
        // Any other SIGHUP handlers installed by concurrent tests will also
        // receive this signal; each handles its own state independently.
        unsafe {
            libc::kill(libc::getpid(), libc::SIGHUP);
        }

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(
            handle.is_finished(),
            "SIGHUP handler should have exited via dead-weak upgrade path"
        );
        // Await the tokio task to propagate any panic.
        handle.await.expect("SIGHUP handler should exit cleanly");
    }

    /// Verifies the SIGHUP handler task exits via the periodic interval poll
    /// — no signal needed. Without this poll, an idle test that never sends
    /// SIGHUP would leak the task for the rest of the process lifetime.
    #[cfg(unix)]
    #[tokio::test]
    async fn should_exit_sighup_handler_within_1s_of_state_drop() {
        let handle = spawn_sighup_handler(dead_weak_state(), vec![], false);

        // Poll up to 1.2s. No signal is sent — exit must come from the
        // shutdown_check.tick() arm of the tokio::select!.
        let start = std::time::Instant::now();
        while !handle.is_finished() && start.elapsed() < std::time::Duration::from_millis(1200) {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        assert!(
            handle.is_finished(),
            "SIGHUP handler should exit within 1.2s of a dead Weak<AppState>, no signal needed"
        );
        handle.await.expect("SIGHUP handler should exit cleanly");
    }
}