hf2q 0.1.1

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
//! OpenAI-compatible request/response types for the hf2q API server.
//!
//! Restored from git `fe54bc2~1:src/serve/schema.rs` (the commit preceding the
//! MLX divorce at `fe54bc2`) after engine-agnostic review confirmed the file
//! contains only wire-format types with no inference-engine dependencies. The
//! restore was extended in-place to cover the OpenAI parameter surface agreed
//! in ADR-005 Phase 2 party-mode session `adr_005_phase_2` (2026-04-23):
//! Tiers 1+2+3+4, `response_format`, `stream_options`, `logprobs` +
//! `top_logprobs`, `logit_bias`, `parallel_tool_calls`, reasoning-content
//! split, and the `hf2q_overflow_policy` per-request extension.
//!
//! All types here match the OpenAI API specification so that OpenAI SDKs,
//! Open WebUI, Continue, Cursor, and other clients can speak to hf2q without
//! modification. Fields outside the OpenAI surface that hf2q needs (timings,
//! overflow policy) use the `x_hf2q_*` / `hf2q_*` naming prefix so they
//! round-trip cleanly through strict clients.

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Error types (Decision #24 — OpenAI-compliant `{error: {...}}` envelope)
// ---------------------------------------------------------------------------

/// Top-level error wrapper matching the OpenAI `{"error": {...}}` format.
#[derive(Debug, Clone, Serialize)]
pub struct ApiError {
    pub error: ApiErrorBody,
    /// HTTP status code (not serialized in the JSON body).
    #[serde(skip)]
    pub status: StatusCode,
    /// Optional `Retry-After` header value (seconds). Populated on 429 / 503.
    #[serde(skip)]
    pub retry_after_seconds: Option<u64>,
}

/// The inner error object within the OpenAI error envelope.
///
/// Matches OpenAI's documented schema: `{message, type, param, code}`.
#[derive(Debug, Clone, Serialize)]
pub struct ApiErrorBody {
    pub message: String,
    #[serde(rename = "type")]
    pub error_type: String,
    pub param: Option<String>,
    pub code: Option<String>,
}

impl ApiError {
    fn bare(
        status: StatusCode,
        message: impl Into<String>,
        error_type: &str,
        code: Option<&str>,
        param: Option<String>,
    ) -> Self {
        Self {
            status,
            retry_after_seconds: None,
            error: ApiErrorBody {
                message: message.into(),
                error_type: error_type.into(),
                param,
                code: code.map(String::from),
            },
        }
    }

    /// Generic invalid request error (HTTP 400).
    pub fn invalid_request(message: impl Into<String>, param: Option<String>) -> Self {
        Self::bare(
            StatusCode::BAD_REQUEST,
            message,
            "invalid_request_error",
            None,
            param,
        )
    }

    /// Model not found error (HTTP 404).
    pub fn model_not_found(model_name: &str) -> Self {
        Self::bare(
            StatusCode::NOT_FOUND,
            format!("The model '{}' does not exist", model_name),
            "invalid_request_error",
            Some("model_not_found"),
            Some("model".into()),
        )
    }

    /// Model not loaded — used when a `/v1/models` entry is cached on disk but
    /// not the currently-loaded model. Phase 4 hot-swap replaces this with an
    /// auto-swap without a contract change (Decision #26).
    pub fn model_not_loaded(model_name: &str) -> Self {
        Self::bare(
            StatusCode::BAD_REQUEST,
            format!("The model '{}' is cached but not currently loaded. Start the server with `--model <path>` for this model.", model_name),
            "invalid_request_error",
            Some("model_not_loaded"),
            Some("model".into()),
        )
    }

    /// Context length exceeded error (HTTP 400). Used only when the overflow
    /// policy is `reject`; `truncate_left` and `summarize` handle it silently.
    pub fn context_length_exceeded(max_tokens: usize, actual_tokens: usize) -> Self {
        Self::bare(
            StatusCode::BAD_REQUEST,
            format!(
                "This model's maximum context length is {} tokens. However, your messages resulted in {} tokens.",
                max_tokens, actual_tokens
            ),
            "invalid_request_error",
            Some("context_length_exceeded"),
            Some("messages".into()),
        )
    }

    /// Queue full (HTTP 429) — serialized FIFO queue at hard cap.
    ///
    /// **ADR-005 Phase 2 Decision #2** — serialized FIFO queue under
    /// [`crate::serve::api::engine::EngineMode::SerialFifo`] (= the
    /// [`crate::serve::scheduler::SchedulerPolicy::FifoSerial`] scheduler).
    /// **ADR-005 Phase 2 Decision #19** — under FifoSerial (default at
    /// engine spawn unless overridden by `HF2Q_SCHEDULER` or
    /// `--scheduler`), `queue_full` fires when the bounded mpsc channel
    /// (`Engine::spawn(queue_capacity)`) is at hard cap.
    ///
    /// **ADR-040 Phase C C4** (SHIPPED 2026-05-23, cf. ADR-040 §6.1.9)
    /// added explicit `SchedulerPolicy` selection via the
    /// `HF2Q_SCHEDULER` env / `--scheduler` CLI flag. There are TWO
    /// distinct enums at play (and the docstring + test below pin
    /// both — cfa-iter-A5b MAJOR #1 fixed a pre-iter-A5b docstring
    /// bug that referenced a nonexistent variant on the wrong enum;
    /// the test below enforces the correct enum + variant pairing):
    /// - [`crate::serve::scheduler::SchedulerPolicy`] = `{ FifoSerial,
    ///   InflightBatched }` — the SCHEDULER POLICY enum, picks the
    ///   admission FSM.
    /// - [`crate::serve::api::engine::EngineMode`] = `{ SerialFifo,
    ///   SlotAware { max_slots } }` — the ENGINE MODE enum, picks
    ///   the worker_run runtime + per-model SlotAware seam.
    ///
    /// The per-policy semantics for this 429 are:
    /// - Under [`crate::serve::scheduler::SchedulerPolicy::FifoSerial`]
    ///   (default), `queue_full` fires at `queue_capacity` overflow per
    ///   Decision #19 — the legacy single-slot serial path.
    /// - Under [`crate::serve::scheduler::SchedulerPolicy::InflightBatched`]
    ///   (gated behind [`crate::serve::api::engine::EngineMode::SlotAware { max_slots }`]
    ///   at Phase C2c+ future), `queue_full` will fire when
    ///   `total_admissible` (= `queue_capacity` + `max_slots`) is
    ///   exhausted; admission carries a typed
    ///   [`crate::serve::scheduler::AdmitError::QueueFull`] with the
    ///   `queue_capacity` + `total_admissible` field pair (iter-1.5 F6).
    ///   The HTTP-layer mapping (this method) is unchanged at the wire
    ///   level — same status + same body shape + same Retry-After — so
    ///   ADR-040 §1.4 "client-invisibility" is preserved.
    ///
    /// `Retry-After` is populated with a conservative 1-second
    /// suggestion (Decision #19; preserved verbatim under both
    /// policies).
    pub fn queue_full() -> Self {
        let mut e = Self::bare(
            StatusCode::TOO_MANY_REQUESTS,
            "Server is at capacity. Too many pending requests.",
            "server_error",
            Some("queue_full"),
            None,
        );
        e.retry_after_seconds = Some(1);
        e
    }

    /// **ADR-040 §3.5 iter-A5** — per-slot KV budget exceeded (HTTP 429
    /// + `Retry-After: 1`).
    ///
    /// Fires when the scheduler's
    /// [`crate::serve::scheduler::AdmitError::SlotBudgetExceeded`]
    /// rejects an admit because the request's
    /// `AdmitRequest::kv_bytes_needed` exceeds the per-slot KV byte
    /// budget (`kv_cache_budget_bytes / max_slots`).  Distinct from
    /// [`Self::queue_full`] (transient — capacity will free as
    /// in-flight requests complete) because this is operator-actionable
    /// on the REQUEST: a single request asks for more KV than any
    /// single slot can hold; reducing `max_tokens` or shortening the
    /// prompt is the fix.
    ///
    /// The wire-level shape mirrors `queue_full` (429 + Retry-After: 1)
    /// per ADR-040 §3.5 ("per-slot OOM returns 429 to the admitting
    /// handler — Decision #19 contract preserved") so SDK clients
    /// treat both the same.  The `code` field is `"slot_budget_exceeded"`
    /// (distinct from `"queue_full"`) so observability + alerting can
    /// differentiate the two 429 emitters.
    ///
    /// The message embeds `needed_bytes` + `budget_bytes` from the
    /// upstream `AdmitError::SlotBudgetExceeded` so the operator-facing
    /// 429 names what was attempted vs what was permitted — same
    /// pattern as `MultiSeqError::SlotOom`'s
    /// `needed_bytes` / `budget_bytes` pair
    /// (`src/serve/multi_seq_kv.rs:265`).
    pub fn slot_budget_exceeded(needed_bytes: u64, budget_bytes: u64) -> Self {
        let mut e = Self::bare(
            StatusCode::TOO_MANY_REQUESTS,
            format!(
                "Per-slot KV cache budget exceeded for this request \
                 (needed_bytes={}, budget_bytes={}). Reduce `max_tokens` \
                 or send a shorter prompt; the per-slot KV budget is \
                 derived from `kv_cache_budget_bytes / max_slots` \
                 (ADR-040 §3.5).",
                needed_bytes, budget_bytes
            ),
            "server_error",
            Some("slot_budget_exceeded"),
            None,
        );
        e.retry_after_seconds = Some(1);
        e
    }

    /// Server is still warming up (HTTP 503). Emitted before `/readyz` flips to
    /// 200 (Decision #15, #16). Includes `Retry-After: 1`.
    pub fn not_ready() -> Self {
        let mut e = Self::bare(
            StatusCode::SERVICE_UNAVAILABLE,
            "Model is still warming up; please retry shortly.",
            "server_error",
            Some("not_ready"),
            None,
        );
        e.retry_after_seconds = Some(1);
        e
    }

    /// Generation error (HTTP 500) — Metal failure, decoder panic caught, etc.
    pub fn generation_error(detail: impl Into<String>) -> Self {
        Self::bare(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Generation failed: {}", detail.into()),
            "server_error",
            Some("generation_error"),
            None,
        )
    }

    /// Generic internal server error (HTTP 500).
    pub fn internal_error() -> Self {
        Self::bare(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error",
            "server_error",
            Some("internal_error"),
            None,
        )
    }

    /// Unauthorized (HTTP 401) — missing or invalid bearer token when auth is
    /// configured (Decision #8).
    pub fn unauthorized() -> Self {
        Self::bare(
            StatusCode::UNAUTHORIZED,
            "Missing or invalid authorization header.",
            "authentication_error",
            Some("invalid_api_key"),
            None,
        )
    }

    /// No mmproj configured (HTTP 400) — the request contains `image_url`
    /// content parts but the server was started without `--mmproj`.
    /// Lands in the 400 class (not 501) because the request is malformed
    /// against THIS server configuration: the client needs to either omit
    /// images or use a server instance that has a mmproj loaded.
    pub fn no_mmproj_loaded() -> Self {
        Self::bare(
            StatusCode::BAD_REQUEST,
            "Request includes image_url content parts but this server \
             was started without a multimodal projector. Start with \
             `--mmproj <path>` or send a text-only request.",
            "invalid_request_error",
            Some("no_mmproj_loaded"),
            Some("messages".into()),
        )
    }

    /// Grammar-rejection (HTTP 400) — a malformed JSON schema or GBNF grammar
    /// was supplied in `response_format` or `tools` (Decision #6).
    pub fn grammar_error(detail: impl Into<String>) -> Self {
        Self::bare(
            StatusCode::BAD_REQUEST,
            format!("Grammar compilation failed: {}", detail.into()),
            "invalid_request_error",
            Some("grammar_error"),
            Some("response_format".into()),
        )
    }

    /// Not found error (HTTP 404) — used for unmatched routes.
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::bare(
            StatusCode::NOT_FOUND,
            message,
            "invalid_request_error",
            None,
            None,
        )
    }

    /// Not implemented (HTTP 501) — the request is structurally valid
    /// but the SERVER cannot fulfil it because the underlying inference
    /// path is not yet implemented.  ADR-005 Phase 4 reopen iter-215
    /// Wedge-2: Qwen3.5/3.6 chat completions land here today
    /// (model loaded, /readyz / /v1/models / /metrics work, but the
    /// SERVE-side forward pass is Wedge-3 deferred follow-up).  The
    /// caller's request is well-formed; the SERVER's capability
    /// surface is the bottleneck — 501 is the correct HTTP class per
    /// RFC 7231 §6.6.2.
    ///
    /// **ADR-040 Phase C C3 mapping** (iter-2.5 M1 + iter-A3a closure):
    /// [`crate::serve::multi_seq_kv::MultiSeqError::CapabilityUnsupported`]
    /// is the canonical multi-seq KV cache "not yet implemented in
    /// this per-model impl" sentinel (e.g. `fork_seq` cross-slot copy
    /// under Phase A2c/A3c deferral). It is the upstream source of
    /// HTTP 501 emitted via this method — distinct from
    /// [`crate::serve::multi_seq_kv::MultiSeqError::SlotOom`] (429 +
    /// Retry-After) and
    /// [`crate::serve::multi_seq_kv::MultiSeqError::SlotOutOfRange`]
    /// (500 internal-defect). Helper [`Self::capability_unsupported`]
    /// is the typed seam for that upstream mapping; per-handler error
    /// converters call it directly so the operator-facing message
    /// names the unsupported capability.
    pub fn not_implemented(message: impl Into<String>) -> Self {
        Self::bare(
            StatusCode::NOT_IMPLEMENTED,
            message,
            "server_error",
            Some("not_implemented"),
            None,
        )
    }

    /// **ADR-040 Phase C C3** (iter-2.5 M1 + iter-A3a closure):
    /// HTTP 501 for the multi-seq KV cache
    /// [`crate::serve::multi_seq_kv::MultiSeqError::CapabilityUnsupported`]
    /// variant. Thin wrapper over [`Self::not_implemented`] that
    /// embeds the unsupported-capability label so operator-facing
    /// messages name exactly which trait method is the bottleneck
    /// (e.g. `"fork_seq cross-slot copy"`).
    ///
    /// Distinct from [`Self::queue_full`] (429 — capacity exhausted,
    /// transient) and [`Self::generation_error`] (500 — runtime
    /// fault). 501 is the correct HTTP class per RFC 7231 §6.6.2:
    /// the caller's request is well-formed; the SERVER's capability
    /// surface (the per-model `MultiSeqKvCache` impl in this case)
    /// is the bottleneck.
    ///
    /// The `code` field is `"capability_unsupported"` (distinct from
    /// `"not_implemented"`) so observability + alerting can
    /// differentiate "trait-method-not-yet-impled" from other 501
    /// emitters (e.g. iter-215 Wedge-2 Qwen3.5/3.6 wedge); the wire
    /// `status` + `error_type` are identical so OpenAI SDK clients
    /// treat both the same.
    pub fn capability_unsupported(capability: &str) -> Self {
        Self::bare(
            StatusCode::NOT_IMPLEMENTED,
            format!(
                "Capability not yet implemented: {capability} \
                 (ADR-040 §6 Phase C C3 — MultiSeqKvCache::* unimplemented per-model)"
            ),
            "server_error",
            Some("capability_unsupported"),
            None,
        )
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        use axum::http::{header, HeaderValue};

        let status = self.status;
        let retry_after = self.retry_after_seconds;
        let body = serde_json::to_string(&self).unwrap_or_else(|_| {
            r#"{"error":{"message":"Internal serialization error","type":"server_error","param":null,"code":null}}"#.into()
        });

        let mut response =
            (status, [(header::CONTENT_TYPE, "application/json")], body).into_response();

        if let Some(secs) = retry_after {
            if let Ok(val) = HeaderValue::from_str(&secs.to_string()) {
                response.headers_mut().insert(header::RETRY_AFTER, val);
            }
        }

        response
    }
}

// ---------------------------------------------------------------------------
// Health / Readyz
// ---------------------------------------------------------------------------

/// Response for `GET /health` — JSON liveness with model info (Decision #12).
#[derive(Debug, Clone, Serialize)]
pub struct HealthResponse {
    /// "ok" when the process is alive; "error" if a core component has failed.
    pub status: String,
    /// Currently-loaded model id (path basename or user-supplied alias).
    pub model: Option<String>,
    /// Backend name (`mlx-native` under ADR-008).
    pub backend: &'static str,
    /// Model context length in tokens.
    pub context_length: Option<usize>,
    /// Process uptime in seconds.
    pub uptime_seconds: u64,
}

/// Response for `GET /readyz` — k8s-style readiness (Decision #12, #16).
#[derive(Debug, Clone, Serialize)]
pub struct ReadyzResponse {
    pub ready: bool,
    pub detail: &'static str,
}

// ---------------------------------------------------------------------------
// Models (Decision #26)
// ---------------------------------------------------------------------------

/// A single model object in the OpenAI format.
///
/// Extended with hf2q-specific fields: `quant_type`, `context_length`,
/// `backend`, `loaded`. These survive round-tripping through OpenAI SDKs
/// because SDKs preserve unknown fields in the deserialized object.
///
/// ADR-018 C5: extended again with the unified `LoadInfo` snapshot fields
/// (`arch`, `max_context_length`, `provenance`, `moe_*`, `sliding_window`,
/// `kv_spill_active`, `quant_bpw`). Each new field is `Option<_>` and
/// serde-skip-if-none, so externally-produced cache-scanned entries that
/// have no live engine still serialize to a strict subset of the pre-C5
/// shape — downstream OpenAI-API-compatible clients keep working.
#[derive(Debug, Clone, Serialize)]
pub struct ModelObject {
    pub id: String,
    pub object: &'static str,
    pub created: i64,
    pub owned_by: &'static str,
    /// Maximum context length in tokens (non-standard, widely supported).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_length: Option<usize>,
    /// GGUF quant type (`Q4_K_M`, `Q6_K`, `Q8_0`, `F16`, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quant_type: Option<String>,
    /// Inference backend. Always `mlx-native` today.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backend: Option<&'static str>,
    /// Whether this model is the currently-loaded one. Phase 4 hot-swap will
    /// allow multiple `loaded: true` entries; Phase 2 is exactly one.
    pub loaded: bool,

    // ── ADR-018 C5 — `LoadInfo`-sourced fields (live-engine path only) ──
    //
    // Each field below is populated by the live-engine path
    // (`handlers.rs::list_models` reading `engine.info()`) and left `None`
    // by the cache-scan / embedding / mmproj paths that have no LoadInfo
    // snapshot. `serde(skip_serializing_if = "Option::is_none")` keeps the
    // wire format byte-identical to the pre-C5 shape for those callers.
    /// Raw GGUF `general.architecture` string, e.g. `"gemma4"`,
    /// `"qwen35"`, `"qwen35moe"`. Mirrors `LoadInfo::arch_str`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arch: Option<String>,
    /// Maximum context length declared by the GGUF
    /// (`{arch}.context_length`). Distinct from `context_length` (which
    /// historically reflects the cache-scanner-derived value); this field
    /// is the live-engine LoadInfo source of truth and is `Some` only on
    /// engine-backed entries.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_context_length: Option<u64>,
    /// Provenance label — `"hf2q"` for hf2q-emitted GGUFs, `"external"`
    /// otherwise. Derived from the `Provenance` enum on `LoadInfo`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<&'static str>,
    /// Total expert count for MoE models; `None` for dense and for
    /// non-engine-backed entries. Mirrors `LoadInfo.moe.n_experts`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moe_experts: Option<u32>,
    /// Routed experts per token; `None` for dense and for non-engine-
    /// backed entries. Mirrors `LoadInfo.moe.n_experts_per_tok`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moe_experts_per_tok: Option<u32>,
    /// Sliding-window size in tokens, when applicable. Gemma4 sets this;
    /// Qwen35 leaves it `None`. Mirrors `LoadInfo::sliding_window`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sliding_window: Option<u32>,
    /// `true` iff the engine has a KV-spill hook bound for this load.
    /// Mirrors `LoadInfo::kv_spill_active`. `None` for non-engine-backed
    /// entries (cache-scanner has no engine to ask).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kv_spill_active: Option<bool>,
    /// Parameter-weighted bits-per-weight, averaged across non-fp tensors.
    /// Mirrors `LoadInfo::quant_bpw`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quant_bpw: Option<f32>,
}

/// Response for `GET /v1/models`.
#[derive(Debug, Clone, Serialize)]
pub struct ModelListResponse {
    pub object: &'static str,
    pub data: Vec<ModelObject>,
}

// ---------------------------------------------------------------------------
// Chat Completions — request
// ---------------------------------------------------------------------------

/// A single message in the chat conversation.
///
/// `content` supports both the simple string format and the OpenAI Vision API
/// array format. `reasoning_content` (Decision #21) is the OpenAI-o1-style
/// split for thinking-model reasoning traces; it is separate from `content`
/// both on input (history echo-back) and output (model response).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChatMessage {
    pub role: String,
    /// Message content, either a plain string or an array of content parts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<MessageContent>,
    /// Reasoning-content (OpenAI-o1-style split; Decision #21). On request
    /// echo-back, clients send it as a sibling field to `content`. On
    /// response it carries the model's pre-answer reasoning trace,
    /// delimited by per-model boundary markers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    /// Tool calls made by an assistant message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCall>>,
    /// Tool call ID for a tool-role message (references the prior tool call).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// Optional name (for `system` / `user` messages in OpenAI).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// Message content: either a plain string or an array of content parts.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum MessageContent {
    /// Plain string content.
    Text(String),
    /// Array of content parts (for multimodal messages).
    Parts(Vec<ContentPart>),
}

impl MessageContent {
    /// Concatenate all text parts into a single string.
    pub fn text(&self) -> String {
        match self {
            MessageContent::Text(s) => s.clone(),
            MessageContent::Parts(parts) => parts
                .iter()
                .filter_map(|p| match p {
                    ContentPart::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join(""),
        }
    }

    /// Extract image URLs from multimodal content parts.
    pub fn image_urls(&self) -> Vec<&str> {
        match self {
            MessageContent::Text(_) => Vec::new(),
            MessageContent::Parts(parts) => parts
                .iter()
                .filter_map(|p| match p {
                    ContentPart::ImageUrl { image_url } => Some(image_url.url.as_str()),
                    _ => None,
                })
                .collect(),
        }
    }

    /// True if the message contains at least one image content part.
    pub fn has_images(&self) -> bool {
        match self {
            MessageContent::Text(_) => false,
            MessageContent::Parts(parts) => parts
                .iter()
                .any(|p| matches!(p, ContentPart::ImageUrl { .. })),
        }
    }

    /// `Some(text)` if non-empty, else `None`.
    pub fn as_text_opt(&self) -> Option<String> {
        let text = self.text();
        if text.is_empty() {
            None
        } else {
            Some(text)
        }
    }
}

/// A single content part within a multimodal message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ContentPart {
    /// Text content.
    #[serde(rename = "text")]
    Text { text: String },
    /// Image URL content (base64 data URL, file path, or HTTP URL).
    #[serde(rename = "image_url")]
    ImageUrl { image_url: ImageUrl },
}

/// Image URL within a content part.
///
/// Supported formats:
/// - `data:image/{format};base64,{data}` — inline base64 (Open WebUI default)
/// - `file:///path/to/image.jpg` — local file
/// - `/path/to/image.jpg` — local file (shorthand)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ImageUrl {
    pub url: String,
    /// Optional detail level (`auto` / `low` / `high`). hf2q accepts for
    /// compatibility but does not currently branch on it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// A tool call object (assistant-generated; grammar-constrained so the
/// `arguments` string is guaranteed well-formed JSON by construction).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCall {
    pub id: String,
    #[serde(rename = "type")]
    pub call_type: String,
    pub function: ToolCallFunction,
}

/// Function details within a tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCallFunction {
    pub name: String,
    /// Arguments as a JSON string (per OpenAI; the string contains a JSON
    /// document, not the parsed object).
    pub arguments: String,
}

/// A tool definition in the request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tool {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: ToolFunction,
}

/// Function definition within a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolFunction {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// JSON Schema describing the function's parameters. hf2q converts this
    /// to GBNF via the ported `json-schema-to-grammar` (Decision #6).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameters: Option<serde_json::Value>,
}

/// Stop sequence: OpenAI supports either a single string or array of strings.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum StopSequence {
    Single(String),
    Multiple(Vec<String>),
}

impl StopSequence {
    /// Convert to a `Vec<String>` regardless of variant.
    pub fn into_vec(self) -> Vec<String> {
        match self {
            StopSequence::Single(s) => vec![s],
            StopSequence::Multiple(v) => v,
        }
    }
}

/// `response_format` parameter (Decision #6; Tier 1 surface).
///
/// Three shapes are accepted:
///   `{"type": "text"}`         — unconstrained (default).
///   `{"type": "json_object"}`  — legacy "any valid JSON" constraint.
///   `{"type": "json_schema",
///     "json_schema": {"name": "...", "schema": {...}, "strict": true}}`
///                              — schema-constrained JSON via the ported
///                                 `json-schema-to-grammar` + GBNF sampler.
///
/// All three compile down to a grammar the sampler applies token-by-token.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ResponseFormat {
    #[serde(rename = "text")]
    Text,
    #[serde(rename = "json_object")]
    JsonObject,
    #[serde(rename = "json_schema")]
    JsonSchema { json_schema: JsonSchemaSpec },
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct JsonSchemaSpec {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    pub schema: serde_json::Value,
    /// If `true`, the schema must match exactly (OpenAI `strict: true`).
    /// hf2q treats `null`/`false`/absent as the same "not strict" mode.
    #[serde(default)]
    pub strict: Option<bool>,
}

/// `stream_options` parameter (Tier 2 surface).
///
/// Currently only `include_usage` is specified by OpenAI.
#[derive(Debug, Clone, Deserialize, PartialEq, Default)]
pub struct StreamOptions {
    #[serde(default)]
    pub include_usage: Option<bool>,
}

/// `logit_bias` parameter (Tier 4 surface) — raw OpenAI shape is
/// `{token_id_string: bias_float}`; we parse into a typed map.
pub type LogitBiasMap = std::collections::HashMap<String, f32>;

/// Per-request overflow-policy override (hf2q extension, Decision #23).
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum OverflowPolicy {
    /// Return HTTP 400 `context_length_exceeded` — classic behavior.
    Reject,
    /// Drop oldest non-system messages until the prompt fits.
    TruncateLeft,
    /// Summarize oldest non-system messages; replace in-place with a
    /// synthetic `system` message "[Summary of prior conversation]: ...".
    #[default]
    Summarize,
}

/// Request body for `POST /v1/chat/completions` — the full Phase 2a surface
/// (Tiers 1+2+3+4 per Decision #22).
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct ChatCompletionRequest {
    // --- Tier 1: core ---
    pub model: String,
    pub messages: Vec<ChatMessage>,
    #[serde(default)]
    pub stream: Option<bool>,
    #[serde(default)]
    pub max_tokens: Option<usize>,
    /// OpenAI's newer replacement for `max_tokens`. When both are set,
    /// `max_completion_tokens` wins.
    #[serde(default)]
    pub max_completion_tokens: Option<usize>,
    #[serde(default)]
    pub temperature: Option<f32>,
    #[serde(default)]
    pub stop: Option<StopSequence>,
    #[serde(default)]
    pub tools: Option<Vec<Tool>>,
    #[serde(default)]
    pub tool_choice: Option<serde_json::Value>,
    #[serde(default)]
    pub response_format: Option<ResponseFormat>,

    // --- Tier 2: important ---
    #[serde(default)]
    pub top_p: Option<f32>,
    #[serde(default)]
    pub seed: Option<u64>,
    #[serde(default)]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub presence_penalty: Option<f32>,
    #[serde(default)]
    pub stream_options: Option<StreamOptions>,

    // --- Tier 3: llama.cpp / ollama extensions ---
    #[serde(default)]
    pub top_k: Option<u32>,
    #[serde(default)]
    pub repetition_penalty: Option<f32>,
    #[serde(default)]
    pub min_p: Option<f32>,

    // --- Tier 4: power-user ---
    #[serde(default)]
    pub logprobs: Option<bool>,
    #[serde(default)]
    pub top_logprobs: Option<u32>,
    #[serde(default)]
    pub logit_bias: Option<LogitBiasMap>,
    #[serde(default)]
    pub parallel_tool_calls: Option<bool>,

    // --- hf2q extensions ---
    /// Per-request overflow policy override (Decision #23).
    #[serde(default)]
    pub hf2q_overflow_policy: Option<OverflowPolicy>,

    /// Per-request reasoning-mode override (ADR-005 Phase 2a iter-133
    /// Iter D, W67). When `Some(true)`, the chat-template render passes
    /// `enable_thinking=true` so reasoning-capable models actually emit a
    /// thinking trace (e.g. Gemma 4 emits `<|channel>thought\n…<channel|>`,
    /// Qwen 3.5/3.6 emits `<think>…</think>`). When `None` (default) or
    /// `Some(false)`, reasoning mode is OFF — Gemma 4's template seeds an
    /// empty channel block (`<|channel>thought\n<channel|>`) and the model
    /// proceeds straight to answer; Qwen's template skips the
    /// `<think>` enable hint. Open WebUI clients that target the panel UX
    /// should set this to `true` when the user toggles thinking on; the
    /// default-off keeps every legacy + non-thinking-aware caller's
    /// rendered prompt byte-identical.
    #[serde(default)]
    pub hf2q_enable_thinking: Option<bool>,

    /// Extra variables merged into the chat-template Jinja context
    /// (ADR-005 iter-229 Decision 4; llama.cpp-compatible name/shape).
    /// Merged AFTER the renderer's own values, so a kwarg wins every
    /// collision that survives validation — renderer-owned keys
    /// (`messages`, `tools`, `add_generation_prompt`, `bos_token`,
    /// `eos_token`, `raise_exception`) are rejected 400 naming the key;
    /// `enable_thinking` is deliberately overridable. Values reach Jinja
    /// verbatim (no type coercion). Canonical use:
    /// `{"preserve_thinking": true}` to make the Qwen 3.6 template
    /// replay prior-turn reasoning on pre-last-query assistant turns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_template_kwargs: Option<serde_json::Map<String, serde_json::Value>>,
}

// ---------------------------------------------------------------------------
// Chat Completions — response (non-streaming)
// ---------------------------------------------------------------------------

/// Extended timing information returned alongside chat completions (hf2q).
///
/// Serialized into `x_hf2q_timing`. Omitted when not populated.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TimingInfo {
    pub prefill_time_secs: f64,
    pub decode_time_secs: f64,
    pub total_time_secs: f64,
    /// Time from request start to the first sampled token (milliseconds).
    pub time_to_first_token_ms: f64,
    pub prefill_tokens_per_sec: f64,
    pub decode_tokens_per_sec: f64,
    /// Number of GPU command-buffer commits during the request. Useful for
    /// cross-run perf regression detection.
    pub gpu_sync_count: u64,
    /// Number of GPU dispatches (kernel launches) during the request.
    pub gpu_dispatch_count: u64,
}

/// Full chat completion response (non-streaming).
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionResponse {
    pub id: String,
    pub object: &'static str,
    pub created: i64,
    pub model: String,
    /// Optional OpenAI system fingerprint (sampler+engine identity); hf2q
    /// sets `hf2q-<short-git-sha>-<mlx-native>` or omits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_fingerprint: Option<String>,
    pub choices: Vec<ChatCompletionChoice>,
    pub usage: UsageStats,
    /// Extended timing information (hf2q-specific). Omitted when unavailable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x_hf2q_timing: Option<TimingInfo>,
}

/// A single choice in a non-streaming response.
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionChoice {
    pub index: usize,
    pub message: ChatMessage,
    pub finish_reason: String,
    /// Per-token logprobs; populated only when the request set `logprobs: true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<ChoiceLogprobs>,
}

/// Token usage statistics.
#[derive(Debug, Clone, Serialize)]
pub struct UsageStats {
    pub prompt_tokens: usize,
    pub completion_tokens: usize,
    pub total_tokens: usize,
    /// Details about prompt token processing (OpenAI-compatible).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_tokens_details: Option<PromptTokensDetails>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completion_tokens_details: Option<CompletionTokensDetails>,
}

/// Breakdown of prompt-token processing (OpenAI-compatible).
#[derive(Debug, Clone, Serialize)]
pub struct PromptTokensDetails {
    /// Number of prompt tokens served from the prompt cache (Decision #24).
    pub cached_tokens: usize,
}

/// Breakdown of completion-token processing (OpenAI-compatible).
#[derive(Debug, Clone, Serialize)]
pub struct CompletionTokensDetails {
    /// Number of reasoning tokens (the portion of the completion between the
    /// model's reasoning-open and reasoning-close markers; Decision #21).
    pub reasoning_tokens: usize,
}

// ---------------------------------------------------------------------------
// Logprobs — Tier 4
// ---------------------------------------------------------------------------

/// Top-level `logprobs` object on a chat-completion choice.
#[derive(Debug, Clone, Serialize)]
pub struct ChoiceLogprobs {
    pub content: Vec<TokenLogprob>,
}

/// Per-token logprob entry.
#[derive(Debug, Clone, Serialize)]
pub struct TokenLogprob {
    pub token: String,
    pub logprob: f32,
    /// Raw token bytes (UTF-8 byte values). Useful for tokens that straddle
    /// UTF-8 boundaries and thus don't cleanly fit `token`.
    pub bytes: Option<Vec<u8>>,
    /// Top-K alternatives at this position. Empty vec if `top_logprobs` was 0.
    pub top_logprobs: Vec<TopLogprobEntry>,
}

/// A single top-K alternative logprob entry.
#[derive(Debug, Clone, Serialize)]
pub struct TopLogprobEntry {
    pub token: String,
    pub logprob: f32,
    pub bytes: Option<Vec<u8>>,
}

// ---------------------------------------------------------------------------
// Chat Completions — streaming (SSE chunks)
// ---------------------------------------------------------------------------

/// A streaming chunk for SSE responses.
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionChunk {
    pub id: String,
    pub object: &'static str,
    pub created: i64,
    pub model: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_fingerprint: Option<String>,
    pub choices: Vec<ChunkChoice>,
    /// Usage stats. Included only in the final chunk when the request set
    /// `stream_options.include_usage: true` (Tier 2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<UsageStats>,
}

/// A single choice in a streaming chunk.
#[derive(Debug, Clone, Serialize)]
pub struct ChunkChoice {
    pub index: usize,
    pub delta: ChunkDelta,
    pub finish_reason: Option<String>,
    /// Per-token logprobs for this chunk's delta. Populated only when the
    /// request set `logprobs: true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<ChoiceLogprobs>,
}

/// The delta content in a streaming chunk (Decision #21 — reasoning split).
#[derive(Debug, Clone, Serialize)]
pub struct ChunkDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// OpenAI-o1-style reasoning delta, streamed separately from `content`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    /// Tool call deltas for streaming tool calls.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCallDelta>>,
}

/// A single tool call delta in a streaming chunk.
///
/// The first delta for a given index includes `id`, `type`, and
/// `function.name`. Subsequent deltas for the same index append to
/// `function.arguments`.
#[derive(Debug, Clone, Serialize)]
pub struct ToolCallDelta {
    pub index: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub call_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function: Option<ToolCallFunctionDelta>,
}

/// Partial function details within a streaming tool call delta.
#[derive(Debug, Clone, Serialize)]
pub struct ToolCallFunctionDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

// ---------------------------------------------------------------------------
// Tool choice (parsed enum)
// ---------------------------------------------------------------------------

/// Parsed `tool_choice` value from the request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolChoiceValue {
    /// "auto" or absent — the model decides.
    Auto,
    /// "none" — skip tool calling entirely.
    None,
    /// "required" — the model must emit a tool call.
    Required,
    /// Force a specific function by name.
    Function(String),
}

impl ToolChoiceValue {
    pub fn parse(value: Option<&serde_json::Value>) -> Self {
        match value {
            None => ToolChoiceValue::Auto,
            Some(serde_json::Value::String(s)) => match s.as_str() {
                "none" => ToolChoiceValue::None,
                "required" => ToolChoiceValue::Required,
                _ => ToolChoiceValue::Auto,
            },
            Some(serde_json::Value::Object(obj)) => {
                if let Some(func_obj) = obj.get("function") {
                    if let Some(name) = func_obj.get("name").and_then(|n| n.as_str()) {
                        return ToolChoiceValue::Function(name.to_string());
                    }
                }
                ToolChoiceValue::Auto
            }
            _ => ToolChoiceValue::Auto,
        }
    }
}

// ---------------------------------------------------------------------------
// Embeddings (Decision #4)
// ---------------------------------------------------------------------------

/// Input for the embeddings endpoint — accepts a single string or an array.
///
/// OpenAI also accepts `Vec<Vec<u32>>` (pre-tokenized inputs); hf2q rejects
/// that path with `invalid_request_error` until a concrete client asks for it.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum EmbeddingInput {
    Single(String),
    Multiple(Vec<String>),
}

impl EmbeddingInput {
    pub fn into_vec(self) -> Vec<String> {
        match self {
            EmbeddingInput::Single(s) => vec![s],
            EmbeddingInput::Multiple(v) => v,
        }
    }
}

/// Request body for `POST /v1/embeddings`.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct EmbeddingRequest {
    pub model: String,
    pub input: EmbeddingInput,
    /// Encoding format. hf2q supports `"float"` (default); `"base64"` returns
    /// 400 `invalid_request_error` until a concrete client needs it.
    #[serde(default)]
    pub encoding_format: Option<String>,
    /// OpenAI dimensions cap. hf2q treats as advisory — the returned vector
    /// is whatever the model produces; truncation is not performed silently.
    #[serde(default)]
    pub dimensions: Option<usize>,
    /// Optional user identifier (accepted, ignored — matches OpenAI behavior).
    #[serde(default)]
    pub user: Option<String>,
}

/// A single embedding object in the response. The `embedding` field
/// can be either a list of floats (`encoding_format="float"`) or a
/// base64-encoded string of little-endian F32 bytes (the OpenAI Python
/// SDK's *default* encoding — chosen to reduce JSON payload size).
/// Serialized as an untagged union so JSON output looks like OpenAI's:
///   { "object": "embedding", "embedding": [0.1, 0.2, ...], "index": 0 }
///   { "object": "embedding", "embedding": "base64string==", "index": 0 }
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum EmbeddingPayload {
    Float(Vec<f32>),
    Base64(String),
}

#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingObject {
    pub object: &'static str,
    pub embedding: EmbeddingPayload,
    pub index: usize,
}

/// Response for `POST /v1/embeddings`.
#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingResponse {
    pub object: &'static str,
    pub data: Vec<EmbeddingObject>,
    pub model: String,
    pub usage: EmbeddingUsage,
}

/// Token usage stats specific to the embeddings endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingUsage {
    pub prompt_tokens: usize,
    pub total_tokens: usize,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_api_error_serialization() {
        let err = ApiError::invalid_request("Something went wrong", None);
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["error"]["message"], "Something went wrong");
        assert_eq!(json["error"]["type"], "invalid_request_error");
        assert!(json["error"]["param"].is_null());
        assert!(json["error"]["code"].is_null());
    }

    #[test]
    fn test_api_error_with_param() {
        let err = ApiError::invalid_request("Bad field", Some("messages".into()));
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["error"]["param"], "messages");
    }

    #[test]
    fn test_model_not_found_error() {
        let err = ApiError::model_not_found("gpt-5");
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["error"]["code"], "model_not_found");
        assert!(json["error"]["message"].as_str().unwrap().contains("gpt-5"));
        assert_eq!(err.status, StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_model_not_loaded_error() {
        let err = ApiError::model_not_loaded("qwen3.6-27b");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert_eq!(err.error.code.as_deref(), Some("model_not_loaded"));
        assert!(err.error.message.contains("qwen3.6-27b"));
        assert_eq!(err.error.param.as_deref(), Some("model"));
    }

    #[test]
    fn test_context_length_exceeded_error() {
        let err = ApiError::context_length_exceeded(8192, 9000);
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["error"]["code"], "context_length_exceeded");
        let msg = json["error"]["message"].as_str().unwrap();
        assert!(msg.contains("8192"));
        assert!(msg.contains("9000"));
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_queue_full_error_is_429_with_retry_after() {
        let err = ApiError::queue_full();
        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(
            response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok()),
            Some("1")
        );
    }

    #[test]
    fn test_not_ready_is_503_with_retry_after() {
        let err = ApiError::not_ready();
        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(
            response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok()),
            Some("1")
        );
    }

    #[test]
    fn test_unauthorized_error() {
        let err = ApiError::unauthorized();
        assert_eq!(err.status, StatusCode::UNAUTHORIZED);
        assert_eq!(err.error.error_type, "authentication_error");
    }

    #[test]
    fn test_grammar_error() {
        let err = ApiError::grammar_error("unclosed brace at pos 42");
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert_eq!(json["error"]["code"], "grammar_error");
        assert_eq!(json["error"]["param"], "response_format");
        assert!(json["error"]["message"]
            .as_str()
            .unwrap()
            .contains("unclosed brace at pos 42"));
    }

    #[test]
    fn test_generation_error() {
        let err = ApiError::generation_error("Metal command buffer error");
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["error"]["code"], "generation_error");
        assert!(json["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Metal command buffer error"));
        assert_eq!(err.status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_internal_error() {
        let err = ApiError::internal_error();
        assert_eq!(err.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.error.code, Some("internal_error".into()));
    }

    #[test]
    fn test_model_list_response_serialization() {
        // ADR-018 C5: every new `LoadInfo`-sourced field is `None` here so
        // the serialized shape mirrors the pre-C5 cache-scanned entry shape
        // exactly (the eight new keys are skipped via
        // `#[serde(skip_serializing_if = "Option::is_none")]`).
        let resp = ModelListResponse {
            object: "list",
            data: vec![ModelObject {
                id: "test-model".into(),
                object: "model",
                created: 1234567890,
                owned_by: "hf2q",
                context_length: Some(262144),
                quant_type: Some("Q4_K_M".into()),
                backend: Some("mlx-native"),
                loaded: true,
                arch: None,
                max_context_length: None,
                provenance: None,
                moe_experts: None,
                moe_experts_per_tok: None,
                sliding_window: None,
                kv_spill_active: None,
                quant_bpw: None,
            }],
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["object"], "list");
        assert_eq!(json["data"][0]["id"], "test-model");
        assert_eq!(json["data"][0]["object"], "model");
        assert_eq!(json["data"][0]["created"], 1234567890);
        assert_eq!(json["data"][0]["owned_by"], "hf2q");
        assert_eq!(json["data"][0]["context_length"], 262144);
        assert_eq!(json["data"][0]["quant_type"], "Q4_K_M");
        assert_eq!(json["data"][0]["backend"], "mlx-native");
        assert_eq!(json["data"][0]["loaded"], true);

        // Backward-compat pin: with every C5 field `None`, the serialized
        // wire shape MUST NOT include any of the new keys.
        let entry = &json["data"][0];
        assert!(entry.get("arch").is_none(), "arch must be skipped");
        assert!(
            entry.get("max_context_length").is_none(),
            "max_context_length must be skipped"
        );
        assert!(
            entry.get("provenance").is_none(),
            "provenance must be skipped"
        );
        assert!(
            entry.get("moe_experts").is_none(),
            "moe_experts must be skipped"
        );
        assert!(
            entry.get("moe_experts_per_tok").is_none(),
            "moe_experts_per_tok must be skipped"
        );
        assert!(
            entry.get("sliding_window").is_none(),
            "sliding_window must be skipped"
        );
        assert!(
            entry.get("kv_spill_active").is_none(),
            "kv_spill_active must be skipped"
        );
        assert!(
            entry.get("quant_bpw").is_none(),
            "quant_bpw must be skipped"
        );
    }

    #[test]
    fn test_model_object_with_load_info_fields() {
        // ADR-018 C5: when the live-engine path populates the new fields,
        // they appear in the wire format alongside the legacy fields.
        let obj = ModelObject {
            id: "Qwen3.6-27B-A3B-DWQ46-MoE".into(),
            object: "model",
            created: 1700000000,
            owned_by: "hf2q",
            context_length: Some(262_144),
            quant_type: Some("Q4_K".into()),
            backend: Some("mlx-native"),
            loaded: true,
            arch: Some("qwen35moe".into()),
            max_context_length: Some(262_144),
            provenance: Some("hf2q"),
            moe_experts: Some(128),
            moe_experts_per_tok: Some(8),
            sliding_window: None,
            kv_spill_active: Some(false),
            quant_bpw: Some(4.55),
        };
        let json = serde_json::to_value(&obj).unwrap();
        assert_eq!(json["arch"], "qwen35moe");
        assert_eq!(json["max_context_length"], 262_144);
        assert_eq!(json["provenance"], "hf2q");
        assert_eq!(json["moe_experts"], 128);
        assert_eq!(json["moe_experts_per_tok"], 8);
        assert!(
            json.get("sliding_window").is_none(),
            "sliding_window=None must be skipped"
        );
        assert_eq!(json["kv_spill_active"], false);
        // Float comparison via approximate equality on the JSON number's f64.
        let bpw = json["quant_bpw"].as_f64().expect("quant_bpw f64");
        assert!(
            (bpw - 4.55_f64).abs() < 1e-3,
            "quant_bpw expected ≈4.55, got {bpw}"
        );
    }

    #[test]
    fn test_health_response_serialization() {
        let resp = HealthResponse {
            status: "ok".into(),
            model: Some("gemma4-26b".into()),
            backend: "mlx-native",
            context_length: Some(262144),
            uptime_seconds: 42,
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["status"], "ok");
        assert_eq!(json["model"], "gemma4-26b");
        assert_eq!(json["backend"], "mlx-native");
        assert_eq!(json["uptime_seconds"], 42);
    }

    #[test]
    fn test_readyz_response_serialization() {
        let resp = ReadyzResponse {
            ready: false,
            detail: "warming up",
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["ready"], false);
        assert_eq!(json["detail"], "warming up");
    }

    #[test]
    fn test_chat_completion_response_serialization() {
        let resp = ChatCompletionResponse {
            id: "chatcmpl-123".into(),
            object: "chat.completion",
            created: 1700000000,
            model: "test-model".into(),
            system_fingerprint: Some("hf2q-deadbeef-mlx-native".into()),
            choices: vec![ChatCompletionChoice {
                index: 0,
                message: ChatMessage {
                    role: "assistant".into(),
                    content: Some(MessageContent::Text("Hello!".into())),
                    reasoning_content: None,
                    tool_calls: None,
                    tool_call_id: None,
                    name: None,
                },
                finish_reason: "stop".into(),
                logprobs: None,
            }],
            usage: UsageStats {
                prompt_tokens: 10,
                completion_tokens: 5,
                total_tokens: 15,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            },
            x_hf2q_timing: None,
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["id"], "chatcmpl-123");
        assert_eq!(json["object"], "chat.completion");
        assert_eq!(json["system_fingerprint"], "hf2q-deadbeef-mlx-native");
        assert_eq!(json["choices"][0]["message"]["role"], "assistant");
        assert_eq!(json["choices"][0]["message"]["content"], "Hello!");
        assert_eq!(json["choices"][0]["finish_reason"], "stop");
        assert_eq!(json["usage"]["prompt_tokens"], 10);
        assert_eq!(json["usage"]["completion_tokens"], 5);
        assert_eq!(json["usage"]["total_tokens"], 15);
    }

    #[test]
    fn test_chat_completion_request_all_tiers_deserialize() {
        let json = r#"{
            "model": "gemma4-26b",
            "messages": [{"role": "user", "content": "hi"}],
            "stream": true,
            "max_tokens": 100,
            "max_completion_tokens": 200,
            "temperature": 0.7,
            "stop": "END",
            "response_format": {"type": "json_object"},
            "top_p": 0.9,
            "seed": 42,
            "frequency_penalty": 0.1,
            "presence_penalty": 0.2,
            "stream_options": {"include_usage": true},
            "top_k": 40,
            "repetition_penalty": 1.05,
            "min_p": 0.05,
            "logprobs": true,
            "top_logprobs": 5,
            "logit_bias": {"1234": -100.0, "5678": 100.0},
            "parallel_tool_calls": false,
            "hf2q_overflow_policy": "summarize"
        }"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.model, "gemma4-26b");
        assert_eq!(req.max_tokens, Some(100));
        assert_eq!(req.max_completion_tokens, Some(200));
        assert_eq!(req.temperature, Some(0.7));
        assert!(matches!(
            req.response_format,
            Some(ResponseFormat::JsonObject)
        ));
        assert_eq!(req.top_p, Some(0.9));
        assert_eq!(req.seed, Some(42));
        assert_eq!(req.frequency_penalty, Some(0.1));
        assert_eq!(req.presence_penalty, Some(0.2));
        assert_eq!(
            req.stream_options.as_ref().unwrap().include_usage,
            Some(true)
        );
        assert_eq!(req.top_k, Some(40));
        assert_eq!(req.repetition_penalty, Some(1.05));
        assert_eq!(req.min_p, Some(0.05));
        assert_eq!(req.logprobs, Some(true));
        assert_eq!(req.top_logprobs, Some(5));
        assert_eq!(req.logit_bias.as_ref().unwrap().len(), 2);
        assert_eq!(req.parallel_tool_calls, Some(false));
        assert_eq!(req.hf2q_overflow_policy, Some(OverflowPolicy::Summarize));
    }

    #[test]
    fn test_response_format_json_schema_deserialize() {
        let json = r#"{
            "model": "m",
            "messages": [{"role": "user", "content": "hi"}],
            "response_format": {
                "type": "json_schema",
                "json_schema": {
                    "name": "answer",
                    "description": "A typed answer",
                    "schema": {"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]},
                    "strict": true
                }
            }
        }"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        match req.response_format {
            Some(ResponseFormat::JsonSchema { json_schema }) => {
                assert_eq!(json_schema.name, "answer");
                assert_eq!(json_schema.description.as_deref(), Some("A typed answer"));
                assert_eq!(json_schema.strict, Some(true));
                assert!(json_schema.schema.is_object());
            }
            other => panic!("expected JsonSchema, got {:?}", other),
        }
    }

    #[test]
    fn test_chat_completion_request_minimal() {
        let json = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert!(req.stream.is_none());
        assert!(req.temperature.is_none());
        assert!(req.top_p.is_none());
        assert!(req.max_tokens.is_none());
        assert!(req.max_completion_tokens.is_none());
        assert!(req.stop.is_none());
        assert!(req.response_format.is_none());
        assert!(req.seed.is_none());
        assert!(req.top_k.is_none());
        assert!(req.logprobs.is_none());
        assert!(req.hf2q_overflow_policy.is_none());
    }

    #[test]
    fn test_stop_sequence_single() {
        let json = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stop":"END"}"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        let stops = req.stop.unwrap().into_vec();
        assert_eq!(stops, vec!["END"]);
    }

    #[test]
    fn test_stop_sequence_multiple() {
        let json = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stop":["A","B"]}"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        let stops = req.stop.unwrap().into_vec();
        assert_eq!(stops, vec!["A", "B"]);
    }

    #[test]
    fn test_final_chunk_with_usage() {
        let chunk = ChatCompletionChunk {
            id: "chatcmpl-789".into(),
            object: "chat.completion.chunk",
            created: 1700000000,
            model: "test-model".into(),
            system_fingerprint: None,
            choices: vec![ChunkChoice {
                index: 0,
                delta: ChunkDelta {
                    role: None,
                    content: None,
                    reasoning_content: None,
                    tool_calls: None,
                },
                finish_reason: Some("stop".into()),
                logprobs: None,
            }],
            usage: Some(UsageStats {
                prompt_tokens: 10,
                completion_tokens: 20,
                total_tokens: 30,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            }),
        };
        let json = serde_json::to_value(&chunk).unwrap();
        assert_eq!(json["choices"][0]["finish_reason"], "stop");
        assert_eq!(json["usage"]["total_tokens"], 30);
    }

    #[test]
    fn test_tool_choice_parse_auto() {
        assert_eq!(ToolChoiceValue::parse(None), ToolChoiceValue::Auto);
        let val = serde_json::json!("auto");
        assert_eq!(ToolChoiceValue::parse(Some(&val)), ToolChoiceValue::Auto);
    }

    #[test]
    fn test_tool_choice_parse_none() {
        let val = serde_json::json!("none");
        assert_eq!(ToolChoiceValue::parse(Some(&val)), ToolChoiceValue::None);
    }

    #[test]
    fn test_tool_choice_parse_required() {
        let val = serde_json::json!("required");
        assert_eq!(
            ToolChoiceValue::parse(Some(&val)),
            ToolChoiceValue::Required
        );
    }

    #[test]
    fn test_tool_choice_parse_forced_function() {
        let val = serde_json::json!({"type": "function", "function": {"name": "get_weather"}});
        match ToolChoiceValue::parse(Some(&val)) {
            ToolChoiceValue::Function(name) => assert_eq!(name, "get_weather"),
            other => panic!("Expected Function, got {:?}", other),
        }
    }

    #[test]
    fn test_tool_call_delta_serialization() {
        let delta = ToolCallDelta {
            index: 0,
            id: Some("call_abc123".to_string()),
            call_type: Some("function".to_string()),
            function: Some(ToolCallFunctionDelta {
                name: Some("get_weather".to_string()),
                arguments: None,
            }),
        };
        let json = serde_json::to_value(&delta).unwrap();
        assert_eq!(json["index"], 0);
        assert_eq!(json["id"], "call_abc123");
        assert_eq!(json["type"], "function");
        assert_eq!(json["function"]["name"], "get_weather");
        assert!(json["function"].get("arguments").is_none());
    }

    #[test]
    fn test_chat_message_with_tool_call_id() {
        let json = r#"{"role":"tool","content":"sunny","tool_call_id":"call_123"}"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        assert_eq!(msg.role, "tool");
        assert_eq!(
            msg.content.as_ref().map(|c| c.text()).as_deref(),
            Some("sunny")
        );
        assert_eq!(msg.tool_call_id.as_deref(), Some("call_123"));
    }

    #[test]
    fn test_chat_message_reasoning_content_round_trip() {
        let msg = ChatMessage {
            role: "assistant".into(),
            content: Some(MessageContent::Text("final answer".into())),
            reasoning_content: Some("let me think step by step...".into()),
            tool_calls: None,
            tool_call_id: None,
            name: None,
        };
        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["reasoning_content"], "let me think step by step...");
        assert_eq!(json["content"], "final answer");
        let round_trip: ChatMessage = serde_json::from_value(json).unwrap();
        assert_eq!(round_trip, msg);
    }

    #[test]
    fn test_chunk_delta_with_reasoning_only() {
        let delta = ChunkDelta {
            role: None,
            content: None,
            reasoning_content: Some("wait...".into()),
            tool_calls: None,
        };
        let json = serde_json::to_value(&delta).unwrap();
        assert!(json.get("content").is_none());
        assert_eq!(json["reasoning_content"], "wait...");
    }

    #[test]
    fn test_embedding_input_single_string() {
        let json = r#""hello world""#;
        let input: EmbeddingInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.into_vec(), vec!["hello world"]);
    }

    #[test]
    fn test_embedding_input_array() {
        let json = r#"["hello", "world"]"#;
        let input: EmbeddingInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.into_vec(), vec!["hello", "world"]);
    }

    #[test]
    fn test_embedding_request_deserialize() {
        let json = r#"{"model": "gemma4", "input": "test input"}"#;
        let req: EmbeddingRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.model, "gemma4");
        assert!(matches!(req.input, EmbeddingInput::Single(_)));
        assert!(req.encoding_format.is_none());
        assert!(req.dimensions.is_none());
    }

    #[test]
    fn test_embedding_response_schema() {
        let resp = EmbeddingResponse {
            object: "list",
            data: vec![
                EmbeddingObject {
                    object: "embedding",
                    embedding: EmbeddingPayload::Float(vec![0.1, 0.2]),
                    index: 0,
                },
                EmbeddingObject {
                    object: "embedding",
                    embedding: EmbeddingPayload::Float(vec![0.3, 0.4]),
                    index: 1,
                },
            ],
            model: "test".to_string(),
            usage: EmbeddingUsage {
                prompt_tokens: 10,
                total_tokens: 10,
            },
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["object"], "list");
        assert_eq!(json["data"].as_array().unwrap().len(), 2);
        assert_eq!(json["data"][0]["object"], "embedding");
        assert_eq!(json["data"][0]["index"], 0);
        assert_eq!(json["data"][1]["index"], 1);
        assert_eq!(json["usage"]["prompt_tokens"], 10);
        assert_eq!(json["usage"]["total_tokens"], 10);
    }

    #[test]
    fn test_chat_request_with_tools_deserialize() {
        let json = r#"{
            "model": "test",
            "messages": [{"role": "user", "content": "What's the weather?"}],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get weather",
                        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
                    }
                }
            ],
            "tool_choice": "auto"
        }"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert!(req.tools.is_some());
        let tools = req.tools.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "get_weather");
        assert!(req.tool_choice.is_some());
    }

    #[test]
    fn test_overflow_policy_deserialize_each_variant() {
        for (raw, expected) in [
            ("\"reject\"", OverflowPolicy::Reject),
            ("\"truncate_left\"", OverflowPolicy::TruncateLeft),
            ("\"summarize\"", OverflowPolicy::Summarize),
        ] {
            let p: OverflowPolicy = serde_json::from_str(raw).unwrap();
            assert_eq!(p, expected);
        }
    }

    #[test]
    fn test_overflow_policy_default_is_summarize() {
        // Decision #23 — `summarize` is the default. If this test breaks on a
        // future refactor, the docs + ADR must change in lockstep.
        assert_eq!(OverflowPolicy::default(), OverflowPolicy::Summarize);
    }

    #[test]
    fn test_message_content_text_string() {
        let json = r#"{"role":"user","content":"Hello"}"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        assert_eq!(msg.content.as_ref().unwrap().text(), "Hello");
        assert!(!msg.content.as_ref().unwrap().has_images());
        assert!(msg.content.as_ref().unwrap().image_urls().is_empty());
    }

    #[test]
    fn test_message_content_null() {
        let json = r#"{"role":"assistant","content":null}"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        assert!(msg.content.is_none());
    }

    #[test]
    fn test_message_content_vision_array() {
        let json = r#"{
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,abc123"}}
            ]
        }"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        let content = msg.content.as_ref().unwrap();
        assert_eq!(content.text(), "What's in this image?");
        assert!(content.has_images());
        let urls = content.image_urls();
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0], "data:image/png;base64,abc123");
    }

    #[test]
    fn test_message_content_multiple_images() {
        let json = r#"{
            "role": "user",
            "content": [
                {"type": "text", "text": "Compare these:"},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,img1"}},
                {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,img2"}}
            ]
        }"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        let content = msg.content.as_ref().unwrap();
        assert_eq!(content.text(), "Compare these:");
        let urls = content.image_urls();
        assert_eq!(urls.len(), 2);
        assert_eq!(urls[0], "data:image/png;base64,img1");
        assert_eq!(urls[1], "data:image/jpeg;base64,img2");
    }

    #[test]
    fn test_message_content_image_url_with_detail() {
        let json = r#"{
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": "file:///tmp/test.png", "detail": "high"}}
            ]
        }"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        let content = msg.content.as_ref().unwrap();
        assert!(content.has_images());
        assert_eq!(content.image_urls()[0], "file:///tmp/test.png");
    }

    #[test]
    fn test_message_content_text_only_array() {
        let json = r#"{
            "role": "user",
            "content": [
                {"type": "text", "text": "First part"},
                {"type": "text", "text": " second part"}
            ]
        }"#;
        let msg: ChatMessage = serde_json::from_str(json).unwrap();
        let content = msg.content.as_ref().unwrap();
        assert_eq!(content.text(), "First part second part");
        assert!(!content.has_images());
    }

    #[test]
    fn test_message_content_as_text_opt() {
        let content = MessageContent::Text("hello".to_string());
        assert_eq!(content.as_text_opt(), Some("hello".to_string()));

        let content = MessageContent::Text("".to_string());
        assert_eq!(content.as_text_opt(), None);
    }

    #[test]
    fn test_message_content_serialization_round_trip_text() {
        let msg = ChatMessage {
            role: "user".into(),
            content: Some(MessageContent::Text("Hello".into())),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
            name: None,
        };
        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["content"], "Hello");
    }

    #[test]
    fn test_message_content_serialization_round_trip_parts() {
        let msg = ChatMessage {
            role: "user".into(),
            content: Some(MessageContent::Parts(vec![
                ContentPart::Text {
                    text: "Look at this:".into(),
                },
                ContentPart::ImageUrl {
                    image_url: ImageUrl {
                        url: "data:image/png;base64,abc".into(),
                        detail: None,
                    },
                },
            ])),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
            name: None,
        };
        let json = serde_json::to_value(&msg).unwrap();
        assert!(json["content"].is_array());
        assert_eq!(json["content"][0]["type"], "text");
        assert_eq!(json["content"][0]["text"], "Look at this:");
        assert_eq!(json["content"][1]["type"], "image_url");
        assert_eq!(
            json["content"][1]["image_url"]["url"],
            "data:image/png;base64,abc"
        );
    }

    #[test]
    fn test_logprobs_serialization() {
        let lp = ChoiceLogprobs {
            content: vec![TokenLogprob {
                token: "Hello".into(),
                logprob: -0.5,
                bytes: Some(vec![72, 101, 108, 108, 111]),
                top_logprobs: vec![TopLogprobEntry {
                    token: "Hi".into(),
                    logprob: -1.2,
                    bytes: Some(vec![72, 105]),
                }],
            }],
        };
        let json = serde_json::to_value(&lp).unwrap();
        assert_eq!(json["content"][0]["token"], "Hello");
        assert!((json["content"][0]["logprob"].as_f64().unwrap() - -0.5).abs() < 1e-6);
        assert_eq!(json["content"][0]["top_logprobs"][0]["token"], "Hi");
    }

    // ───────────────────────────────────────────────────────────────────
    // ADR-040 §6 Phase C C3 — Decision #2 docstring + CapabilityUnsupported
    // → HTTP 501 mapping tests
    // ───────────────────────────────────────────────────────────────────

    /// **ADR-040 C3** — the `queue_full()` docstring now names
    /// `SchedulerPolicy` (the C4 SHIPPED operator surface from
    /// ADR-040 §6.1.9) alongside Decision #2. Pinning the docstring
    /// content as a test catches future drift — a `pub fn queue_full`
    /// without `SchedulerPolicy` in the surrounding doc-block is a
    /// regression on the C3 documentation goal.
    #[test]
    fn c3_schema_queue_full_docstring_names_scheduler_policy() {
        // We pin the docstring at compile-time via the source file —
        // the std::env! var CARGO_MANIFEST_DIR + the known relative
        // path is the load-bearing identity here. include_str! pulls
        // the schema.rs source into this test binary as a string
        // constant so the test is self-contained (no fs I/O at test
        // time).
        let source = include_str!("schema.rs");

        // Find the queue_full doc block + body. The doc block is the
        // run of `///` lines immediately preceding `pub fn queue_full`.
        let queue_full_pos = source
            .find("pub fn queue_full() -> Self")
            .expect("source must contain `pub fn queue_full() -> Self`");

        // Walk backwards collecting lines until we hit a non-`///` /
        // non-blank line — that's the doc block.
        let preamble = &source[..queue_full_pos];
        let docblock_lines: Vec<&str> = preamble
            .lines()
            .rev()
            .take_while(|line| {
                let trimmed = line.trim_start();
                trimmed.starts_with("///") || trimmed.is_empty()
            })
            .collect();
        let docblock = docblock_lines
            .into_iter()
            .rev()
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            docblock.contains("SchedulerPolicy"),
            "ADR-040 C3: the queue_full() docstring MUST name \
             `SchedulerPolicy` (per ADR-040 §6.1.9 C4 SHIPPED). \
             Current doc block:\n{docblock}"
        );
        assert!(
            docblock.contains("Decision #2"),
            "ADR-040 C3: the queue_full() docstring MUST cite \
             ADR-005 Decision #2 (the carve-out this scheduler \
             selection sits alongside). Current doc block:\n{docblock}"
        );
        assert!(
            docblock.contains("FifoSerial") && docblock.contains("InflightBatched"),
            "ADR-040 C3 (iter-A5b MAJOR #1 fix): the queue_full() \
             docstring MUST name BOTH real `SchedulerPolicy` variants \
             — `FifoSerial` (default under Decision #19) and \
             `InflightBatched` (the real Phase C2c+ scheduler-policy \
             enum variant). The doc must NOT name a nonexistent \
             `SchedulerPolicy::SlotAware` variant. Current doc \
             block:\n{docblock}"
        );
        // cfa-iter-A5b MAJOR #1 regression pin: the docstring MUST
        // also name the SEPARATE `EngineMode::SlotAware` enum (engine
        // mode + max_slots, distinct from the scheduler policy
        // surface) so operators don't confuse the two enums.
        assert!(
            docblock.contains("EngineMode::SlotAware"),
            "ADR-040 C3 (iter-A5b MAJOR #1 fix): the queue_full() \
             docstring MUST name `EngineMode::SlotAware` as the \
             engine-mode enum variant gating the InflightBatched \
             runtime (distinct from the SchedulerPolicy variant). \
             Current doc block:\n{docblock}"
        );
        // cfa-iter-A5b MAJOR #1 regression pin: assert the docstring
        // does NOT erroneously refer to a `SchedulerPolicy::SlotAware`
        // variant — there is no such variant; that string is the
        // pre-iter-A5b vaporware the codex review surfaced.
        assert!(
            !docblock.contains("SchedulerPolicy::SlotAware"),
            "ADR-040 C3 (iter-A5b MAJOR #1 fix): the queue_full() \
             docstring MUST NOT reference `SchedulerPolicy::SlotAware` \
             — that variant does not exist on the SchedulerPolicy enum \
             (variants are `FifoSerial` + `InflightBatched`). \
             SlotAware lives on the SEPARATE `EngineMode` enum. \
             Current doc block:\n{docblock}"
        );
        assert!(
            docblock.contains("ADR-040"),
            "ADR-040 C3: the queue_full() docstring MUST reference \
             ADR-040 so operators searching for the scheduler-policy \
             surface land on this method. Current doc block:\n{docblock}"
        );
    }

    /// **ADR-040 C3** — the
    /// [`crate::serve::multi_seq_kv::MultiSeqError::CapabilityUnsupported`]
    /// variant maps to HTTP 501 Not Implemented via
    /// [`ApiError::capability_unsupported`]. Pins both the status code
    /// + the `code` field + the response shape (status code on the
    /// rendered Response, not just on the struct).
    /// **ADR-040 §3.5 iter-A5** — the per-slot KV budget exceeded
    /// helper maps to HTTP 429 + `Retry-After: 1`, mirrors the
    /// `queue_full` wire shape, embeds the needed/budget byte pair in
    /// the body, and surfaces a distinct `slot_budget_exceeded` code
    /// for observability.
    #[test]
    fn c3_schema_slot_budget_exceeded_returns_429_with_retry_after() {
        let needed = 5 * 1024 * 1024u64;
        let budget = 4 * 1024 * 1024u64;
        let err = ApiError::slot_budget_exceeded(needed, budget);

        // Struct-level assertions.
        assert_eq!(
            err.status,
            StatusCode::TOO_MANY_REQUESTS,
            "ADR-040 §3.5 A5: SlotBudgetExceeded MUST map to HTTP 429 \
             (per Decision #19, parallel to queue_full)"
        );
        assert_eq!(
            err.error.error_type, "server_error",
            "ADR-040 §3.5 A5: error_type follows queue_full convention \
             (server_error class)"
        );
        assert_eq!(
            err.error.code.as_deref(),
            Some("slot_budget_exceeded"),
            "ADR-040 §3.5 A5: code MUST be `slot_budget_exceeded` \
             (distinct from queue_full so observability + alerting \
             can differentiate the two 429 emitters)"
        );
        assert_eq!(
            err.retry_after_seconds,
            Some(1),
            "ADR-040 §3.5 A5: Retry-After: 1 mirrors queue_full \
             (Decision #19 wire-level contract preserved)"
        );

        // Message MUST name the actionable diagnostic (max_tokens or
        // prompt) + cite ADR-040.
        assert!(
            err.error.message.contains(&needed.to_string()),
            "ADR-040 §3.5 A5: message MUST embed needed_bytes verbatim. \
             Got: {}",
            err.error.message
        );
        assert!(
            err.error.message.contains(&budget.to_string()),
            "ADR-040 §3.5 A5: message MUST embed budget_bytes verbatim. \
             Got: {}",
            err.error.message
        );
        assert!(
            err.error.message.contains("max_tokens"),
            "ADR-040 §3.5 A5: message MUST cite max_tokens as a \
             remediation lever so the operator knows what to change. \
             Got: {}",
            err.error.message
        );
        assert!(
            err.error.message.contains("prompt"),
            "ADR-040 §3.5 A5: message MUST cite the prompt-shortening \
             remediation. Got: {}",
            err.error.message
        );
        assert!(
            err.error.message.contains("ADR-040"),
            "ADR-040 §3.5 A5: message MUST cite ADR-040 §3.5 so \
             operators can find the canonical documentation. Got: {}",
            err.error.message
        );

        // Wire-level Response: this is the load-bearing contract for
        // SDK clients (must be byte-shape-compatible with queue_full).
        let response = err.into_response();
        assert_eq!(
            response.status(),
            StatusCode::TOO_MANY_REQUESTS,
            "ADR-040 §3.5 A5: rendered Response status MUST be 429"
        );
        assert_eq!(
            response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok()),
            Some("1"),
            "ADR-040 §3.5 A5: rendered Response MUST carry \
             Retry-After: 1 (Decision #19)"
        );
    }

    #[test]
    fn c3_schema_capability_unsupported_maps_to_501() {
        let err = ApiError::capability_unsupported(
            "fork_seq cross-slot copy (Qwen35 HybridKvCache; deferred to Phase A2c)",
        );
        // Struct-level assertions
        assert_eq!(
            err.status,
            StatusCode::NOT_IMPLEMENTED,
            "ADR-040 C3: MultiSeqError::CapabilityUnsupported MUST \
             map to HTTP 501 Not Implemented (distinct from \
             SlotOom→429 and SlotOutOfRange→500)"
        );
        assert_eq!(
            err.error.error_type, "server_error",
            "ADR-040 C3: error_type follows the iter-215 Wedge-2 \
             `not_implemented` convention (server_error class)"
        );
        assert_eq!(
            err.error.code.as_deref(),
            Some("capability_unsupported"),
            "ADR-040 C3: the `code` field MUST be \
             `capability_unsupported` so observability + alerting \
             can differentiate from other 501 emitters"
        );
        // Message MUST name the unsupported capability + cite ADR-040.
        assert!(
            err.error.message.contains("fork_seq cross-slot copy"),
            "ADR-040 C3: the rendered message MUST name the \
             unsupported capability so operators know which trait \
             method is the bottleneck. Got: {}",
            err.error.message
        );
        assert!(
            err.error.message.contains("ADR-040"),
            "ADR-040 C3: the rendered message MUST cite ADR-040 \
             §6 Phase C C3 so the operator can find the canonical \
             documentation. Got: {}",
            err.error.message
        );
        // Wire-level Response assertion: this is the load-bearing
        // contract for SDK clients.
        let response = err.into_response();
        assert_eq!(
            response.status(),
            StatusCode::NOT_IMPLEMENTED,
            "ADR-040 C3: the rendered HTTP Response status MUST be \
             501 Not Implemented (RFC 7231 §6.6.2 — caller's request \
             is well-formed; the server's capability surface is the \
             bottleneck)"
        );
        // 501 is NOT a transient error — Retry-After must NOT be set
        // (unlike 429 queue_full which carries Retry-After: 1).
        assert!(
            response.headers().get("retry-after").is_none(),
            "ADR-040 C3: 501 Not Implemented is NOT transient — the \
             unsupported capability requires a future iter to ship; \
             no Retry-After should be emitted (unlike 429 queue_full)"
        );
    }
}