Skip to main content

infr_server/
lib.rs

1//! OpenAI-compatible HTTP server (axum + SSE). Talks only to `infr-engine` — never the GPU.
2//!
3//! Reference for the wire mapping (streaming, `reasoning_content`, tool_calls): the working
4//! shim at `~/Projects/scratch/dgemma-openai-server.py`. See docs/plan.md "server".
5//!
6//! Routes (`auth` = gated by `serve.api_key` when one is configured — see `auth_gate`):
7//!   GET  /health                -> 200 OK                                              (open)
8//!   GET  /v1/models             -> { object: "list", data: [{ id, object, owned_by }] } (auth)
9//!   GET  /metrics               -> Prometheus text exposition (see `metrics`)          (auth)
10//!   GET  /status                -> JSON: per-model backend, device, ctx, slots, memory (auth)
11//!   POST /v1/chat/completions   -> chat.completion | SSE chat.completion.chunk stream   (auth)
12//!
13//! Two process-level limits bound one request's hold on a `--parallel` slot: `serve.max_tokens_cap`
14//! (tokens — see `clamp_max_tokens`) and `serve.request_timeout_secs` (wall clock — see
15//! `request_timeout`). Both are `serve.*` config, never read from the environment here.
16//!
17//! Delta mapping:
18//!   `Delta::Reasoning`  -> `delta.reasoning_content`
19//!   `Delta::Content`    -> `delta.content`
20//!   `Delta::ToolCall`   -> `delta.tool_calls[]`  (finish_reason "tool_calls")
21
22use std::{
23    convert::Infallible,
24    net::SocketAddr,
25    sync::{
26        atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
27        Arc,
28    },
29    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
30};
31
32use axum::{
33    extract::{rejection::JsonRejection, Request, State},
34    http::{HeaderMap, StatusCode},
35    middleware::{self, Next},
36    response::{
37        sse::{Event, Sse},
38        IntoResponse, Response,
39    },
40    routing::{get, post},
41    Json, Router,
42};
43use infr_core::config::Config;
44use infr_engine::{ChatMessage, Delta, ToolCall};
45use serde::{Deserialize, Serialize};
46use subtle::ConstantTimeEq;
47use tokio::sync::Semaphore;
48
49mod metrics;
50mod status;
51
52pub use status::{DeviceMemory, GeneratorStatus};
53
54/// Why generation ended — the OpenAI `finish_reason`. The generator reports it; the handlers
55/// serialize it (a tool call still overrides to [`Finish::ToolCalls`] at the wire layer).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Finish {
58    /// EOS, or a `stop` sequence fired.
59    Stop,
60    /// The `max_tokens` / `max_completion_tokens` budget was exhausted.
61    Length,
62    /// A tool call was emitted.
63    ToolCalls,
64}
65
66impl Finish {
67    pub fn as_str(self) -> &'static str {
68        match self {
69            Finish::Stop => "stop",
70            Finish::Length => "length",
71            Finish::ToolCalls => "tool_calls",
72        }
73    }
74}
75
76/// Generation backend the server drives — it never knows the model/GPU underneath. Implemented by
77/// the CLI's per-arch adapters (`infr-cli`'s `ParallelGenerator` over `infr_llama::ParallelSeam` for
78/// the Vulkan seam; `SeamGenerator` wraps any `infr_llama::ChatModel` for the rest, including
79/// `DiffusionGemmaChat` — see `docs/diffusion-gemma.md`).
80///
81/// [`GenParams`] carries the request's PER-REQUEST sampling config (temperature/top_p/top_k/seed/
82/// penalties/stop/max_tokens). Every field is an `Option` whose `None` means "inherit the process
83/// default" — so a request that sends nothing generates EXACTLY as it did before this existed.
84///
85/// **`&self`, `Send + Sync`.** This is the whole concurrency contract: the server calls `chat` from
86/// N request tasks at once and the generator is responsible for its own slot allocation and GPU
87/// turn-taking. It used to be `&mut self` behind an `Arc<Mutex<_>>` the handlers held for an ENTIRE
88/// generation, which meant request #2 waited for request #1 to finish — head-of-line blocking, no
89/// parallelism. An implementation that genuinely cannot run concurrently (CPU / Metal / diffusion
90/// today) keeps an internal `Mutex` and is served with `--parallel 1`, which is honest rather than
91/// silently serialising a server the user asked to parallelise.
92pub trait ChatGenerator: Send + Sync {
93    /// Run one chat turn.
94    ///
95    /// * `tools` is the request's `tools` array as a borrowed [`serde_json::Value`] — passed by
96    ///   reference so the generator parses the ONE it was already given instead of a
97    ///   `Value`→string→`Value` round-trip (see audit finding 6).
98    /// * `cancel` is a PER-REQUEST abort latch. The server sets it when the client hangs up
99    ///   (streaming or not) or the request deadline fires; the generator must poll it in its
100    ///   prefill AND decode loops and stop promptly so the GPU slot is freed rather than held to
101    ///   `max_tokens`. An `Arc` so the generator can keep it for the whole call — a deadline that
102    ///   fires during prefill comes before any piece, so a copy made from a streaming callback is
103    ///   too late. It is ORed with the process-wide shutdown latch, never a replacement for it.
104    /// * Returns a [`ChatOutcome`] carrying the finish reason AND the real prompt/completion token
105    ///   counts so the handler can populate `usage` truthfully.
106    /// * A request whose prompt does not fit the context should fail with a
107    ///   [`ContextLengthExceeded`] error. The server answers it as a `400` on a non-streaming
108    ///   request and as a terminal SSE error frame carrying the same typed error on a streaming one
109    ///   (the `200` is already sent by then), so the client can act on it rather than retry it.
110    fn chat(
111        &self,
112        messages: &[ChatMessage],
113        tools: Option<&serde_json::Value>,
114        tool_choice: Option<&str>,
115        params: &GenParams,
116        cancel: &Arc<AtomicBool>,
117        on_delta: &mut dyn FnMut(Delta),
118    ) -> anyhow::Result<ChatOutcome>;
119
120    /// Where this generator runs and how much room it has, read fresh on each call, for
121    /// `GET /status` and the device gauges in `/metrics`. Report `None` for what the backend
122    /// cannot see rather than a placeholder. It must not wait on a generation: both routes call it
123    /// while requests are running.
124    fn status(&self) -> GeneratorStatus;
125}
126
127/// What one [`ChatGenerator::chat`] call produced: why it ended, plus the real token counts the
128/// handler needs for a truthful `usage` block (`total = prompt + completion`). Counts are what the
129/// generator actually tokenized/emitted — never a `content.len()/4` estimate.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct ChatOutcome {
132    pub finish: Finish,
133    /// The WHOLE prompt, including any part served from a KV prefix cache — OpenAI's
134    /// `usage.prompt_tokens`, which clients budget context and cost from.
135    pub prompt_tokens: u32,
136    pub completion_tokens: u32,
137    /// How many of `prompt_tokens` were reused from a KV prefix cache rather than prefilled
138    /// (`usage.prompt_tokens_details.cached_tokens`). `0` for a generator with no prefix cache.
139    pub cached_tokens: u32,
140}
141
142/// The request's prompt does not fit the model's context. A [`ChatGenerator`] returns it (as the
143/// `anyhow` error) so the server can answer `400` with OpenAI's `context_length_exceeded` code:
144/// OpenAI clients retry a `5xx` unchanged, but treat this code as final and shorten the
145/// conversation instead.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct ContextLengthExceeded {
148    /// What the client is told: which counts did not fit.
149    pub message: String,
150}
151
152impl std::fmt::Display for ContextLengthExceeded {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.write_str(&self.message)
155    }
156}
157
158impl std::error::Error for ContextLengthExceeded {}
159
160// ---------------------------------------------------------------------------
161// Request DTOs
162// ---------------------------------------------------------------------------
163
164/// Top-level chat completion request (OpenAI wire format).
165///
166/// Unknown fields are IGNORED (no `deny_unknown_fields`) — an OpenAI client sending `n`, `user`,
167/// `logit_bias`, … must not 400. Known-but-invalid VALUES do 400, via [`GenParams::from_request`].
168#[derive(Debug, Deserialize)]
169pub struct ChatRequest {
170    pub model: String,
171    pub messages: Vec<ChatMessageDto>,
172    #[serde(default)]
173    pub stream: bool,
174    #[serde(default)]
175    pub tools: Option<serde_json::Value>,
176    /// OpenAI `tool_choice`: `"auto"` | `"required"` | `"none"` | `{"type":"function","function":
177    /// {"name":..}}`. Normalised to a string (the function name for a named choice) by `tool_choice_str`.
178    #[serde(default)]
179    pub tool_choice: Option<serde_json::Value>,
180    /// `-1` means "not set": the server's default reply budget (`sampling.max_new`), NOT
181    /// llama.cpp's `n_predict: -1` "until the context is full" — an unbounded reply is what the
182    /// default budget exists to prevent.
183    #[serde(default, deserialize_with = "minus_one_is_unset")]
184    pub max_tokens: Option<u32>,
185    /// OpenAI's rename of `max_tokens`. Preferred when both are present.
186    #[serde(default, deserialize_with = "minus_one_is_unset")]
187    pub max_completion_tokens: Option<u32>,
188    #[serde(default)]
189    pub temperature: Option<f32>,
190    #[serde(default)]
191    pub top_p: Option<f32>,
192    /// Not in the OpenAI schema; llama.cpp/vLLM/Ollama all accept it and so do we.
193    #[serde(default)]
194    pub top_k: Option<i64>,
195    #[serde(default, deserialize_with = "minus_one_is_unset")]
196    pub seed: Option<u64>,
197    /// `"\n"` or `["\n", "END"]` (OpenAI: up to 4).
198    #[serde(default)]
199    pub stop: Option<serde_json::Value>,
200    #[serde(default)]
201    pub presence_penalty: Option<f32>,
202    #[serde(default)]
203    pub frequency_penalty: Option<f32>,
204    /// llama.cpp extension (1.0 = off).
205    #[serde(default)]
206    pub repeat_penalty: Option<f32>,
207    /// OpenAI `stream_options`; only `include_usage` is read.
208    #[serde(default)]
209    pub stream_options: Option<StreamOptions>,
210}
211
212/// OpenAI `stream_options`. With `include_usage`, a streamed reply ends with one extra chunk that
213/// carries `usage` and an empty `choices` array, just before `[DONE]`.
214#[derive(Debug, Default, Deserialize)]
215pub struct StreamOptions {
216    #[serde(default)]
217    pub include_usage: bool,
218}
219
220/// An optional integer field where `-1` means "not set". llama.cpp-style clients send `-1` for
221/// `seed` (random) and `max_tokens` (no explicit budget); refusing it as a negative number would
222/// turn those requests into a `400`. Any other negative value is still an error.
223fn minus_one_is_unset<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
224where
225    D: serde::Deserializer<'de>,
226    T: TryFrom<u64>,
227{
228    use serde::de::Error;
229    match Option::<i128>::deserialize(d)? {
230        None | Some(-1) => Ok(None),
231        Some(v) => u64::try_from(v)
232            .ok()
233            .and_then(|v| T::try_from(v).ok())
234            .map(Some)
235            .ok_or_else(|| D::Error::custom(format!("{v} is out of range (use -1 for unset)"))),
236    }
237}
238
239/// The validated, per-request generation config handed to [`ChatGenerator::chat`]. `None` fields
240/// mean "the request didn't say" — the generator leaves the process default (`INFR_TEMP` /
241/// `INFR_TOP_K` / `INFR_TOP_P` / `INFR_MAX_NEW`) in charge for exactly those.
242#[derive(Debug, Clone, Default, PartialEq)]
243pub struct GenParams {
244    pub max_tokens: Option<u32>,
245    pub temperature: Option<f32>,
246    pub top_p: Option<f32>,
247    pub top_k: Option<usize>,
248    pub seed: Option<u64>,
249    pub presence_penalty: Option<f32>,
250    pub frequency_penalty: Option<f32>,
251    pub repeat_penalty: Option<f32>,
252    /// Already normalised: empty strings dropped (an empty stop would fire on the first token).
253    pub stop: Vec<String>,
254}
255
256/// An OpenAI-shaped 400: `{"error":{"message":..,"type":"invalid_request_error","param":..}}`.
257#[derive(Debug, Clone, PartialEq)]
258pub struct ParamError {
259    pub param: &'static str,
260    pub message: String,
261}
262
263impl GenParams {
264    /// Validate + normalise the request's sampling fields. Out-of-range values are a 400, NEVER a
265    /// silent clamp and never a panic (OpenAI's own ranges: temperature 0..2, top_p 0..1,
266    /// presence/frequency -2..2, at most 4 stop sequences).
267    pub fn from_request(req: &ChatRequest) -> Result<Self, ParamError> {
268        let rng = |param: &'static str,
269                   v: Option<f32>,
270                   lo: f32,
271                   hi: f32|
272         -> Result<Option<f32>, ParamError> {
273            match v {
274                Some(x) if !x.is_finite() || x < lo || x > hi => Err(ParamError {
275                    param,
276                    message: format!("{param} must be between {lo} and {hi}, got {x}"),
277                }),
278                other => Ok(other),
279            }
280        };
281
282        let top_k = match req.top_k {
283            // 0 = "no top-k" in llama.cpp; negative is meaningless.
284            Some(k) if k < 0 => {
285                return Err(ParamError {
286                    param: "top_k",
287                    message: format!("top_k must be >= 0, got {k}"),
288                })
289            }
290            Some(k) => Some(k as usize),
291            None => None,
292        };
293
294        let stop = match &req.stop {
295            None | Some(serde_json::Value::Null) => Vec::new(),
296            Some(serde_json::Value::String(s)) => vec![s.clone()],
297            Some(serde_json::Value::Array(a)) => {
298                let mut v = Vec::with_capacity(a.len());
299                for item in a {
300                    match item.as_str() {
301                        Some(s) => v.push(s.to_string()),
302                        None => {
303                            return Err(ParamError {
304                                param: "stop",
305                                message: "stop must be a string or an array of strings".into(),
306                            })
307                        }
308                    }
309                }
310                v
311            }
312            Some(_) => {
313                return Err(ParamError {
314                    param: "stop",
315                    message: "stop must be a string or an array of strings".into(),
316                })
317            }
318        };
319        if stop.len() > 4 {
320            return Err(ParamError {
321                param: "stop",
322                message: format!("at most 4 stop sequences are supported, got {}", stop.len()),
323            });
324        }
325        // An empty stop string would match at every position — drop it rather than dead-stop.
326        let stop: Vec<String> = stop.into_iter().filter(|s| !s.is_empty()).collect();
327
328        if let Some(p) = req.repeat_penalty {
329            if !p.is_finite() || p <= 0.0 {
330                return Err(ParamError {
331                    param: "repeat_penalty",
332                    message: format!("repeat_penalty must be > 0, got {p}"),
333                });
334            }
335        }
336
337        Ok(Self {
338            // OpenAI renamed `max_tokens` -> `max_completion_tokens`; the new name wins.
339            max_tokens: req.max_completion_tokens.or(req.max_tokens),
340            temperature: rng("temperature", req.temperature, 0.0, 2.0)?,
341            top_p: rng("top_p", req.top_p, 0.0, 1.0)?,
342            top_k,
343            seed: req.seed,
344            presence_penalty: rng("presence_penalty", req.presence_penalty, -2.0, 2.0)?,
345            frequency_penalty: rng("frequency_penalty", req.frequency_penalty, -2.0, 2.0)?,
346            repeat_penalty: req.repeat_penalty,
347            stop,
348        })
349    }
350}
351
352// ---------------------------------------------------------------------------
353// Stop sequences
354// ---------------------------------------------------------------------------
355
356/// Incremental stop-sequence matcher over the DECODED text stream.
357///
358/// The hard part is that a stop string need not align with token boundaries: `"\n\n"` may arrive as
359/// `"\n"` + `"\n"`, and `"END"` as `"E"` + `"ND"`. Two rules make that work:
360///
361/// 1. **Match on the accumulated tail**, not on the individual piece — so a split stop still fires.
362/// 2. **Hold back** the longest suffix of the emitted text that is a PREFIX of some stop string.
363///    Streaming clients must never see `"E"` from a token that turns out to begin `"END"`; if the
364///    next piece completes the stop, that `"E"` was never ours to send. The hold-back is bounded by
365///    `longest_stop - 1` bytes, so at most 3-4 bytes of latency in practice.
366///
367/// On a hit, the text BEFORE the stop string is emitted and the stop string itself is discarded
368/// (OpenAI does not include it in the completion).
369#[derive(Debug, Default)]
370pub struct StopMatcher {
371    stops: Vec<String>,
372    /// Text seen but not yet emitted (a possible stop prefix).
373    held: String,
374    hit: bool,
375}
376
377impl StopMatcher {
378    pub fn new(stops: Vec<String>) -> Self {
379        Self {
380            stops: stops.into_iter().filter(|s| !s.is_empty()).collect(),
381            held: String::new(),
382            hit: false,
383        }
384    }
385
386    pub fn is_active(&self) -> bool {
387        !self.stops.is_empty()
388    }
389
390    /// A stop sequence has fired: generation must halt and no further text may be emitted.
391    pub fn hit(&self) -> bool {
392        self.hit
393    }
394
395    /// Feed one decoded piece; returns the text that is now SAFE to emit (possibly empty).
396    pub fn push(&mut self, piece: &str) -> String {
397        if self.hit {
398            return String::new();
399        }
400        if self.stops.is_empty() {
401            return piece.to_string();
402        }
403        self.held.push_str(piece);
404
405        // 1. Full match anywhere in the held tail -> emit the head, drop the stop and the rest.
406        if let Some(cut) = self
407            .stops
408            .iter()
409            .filter_map(|s| self.held.find(s.as_str()))
410            .min()
411        {
412            self.hit = true;
413            let out = self.held[..cut].to_string();
414            self.held.clear();
415            return out;
416        }
417
418        // 2. No match: hold back the longest suffix that could still BECOME one.
419        let hold = self.longest_partial_suffix();
420        let split = self.held.len() - hold;
421        let out = self.held[..split].to_string();
422        self.held.drain(..split);
423        out
424    }
425
426    /// End of generation with no stop hit: whatever is still held was never a stop, so emit it.
427    pub fn flush(&mut self) -> String {
428        if self.hit {
429            return String::new();
430        }
431        std::mem::take(&mut self.held)
432    }
433
434    /// Length (bytes) of the longest suffix of `held` that is a proper prefix of some stop string.
435    /// Always lands on a char boundary: a suffix of `held` equal to `stop[..n]` starts at `stop`'s
436    /// first byte, which is a UTF-8 lead byte.
437    fn longest_partial_suffix(&self) -> usize {
438        let max = self
439            .stops
440            .iter()
441            .map(|s| s.len())
442            .max()
443            .unwrap_or(0)
444            .saturating_sub(1)
445            .min(self.held.len());
446        for n in (1..=max).rev() {
447            let start = self.held.len() - n;
448            if !self.held.is_char_boundary(start) {
449                continue;
450            }
451            let tail = &self.held[start..];
452            if self
453                .stops
454                .iter()
455                .any(|s| s.as_bytes().starts_with(tail.as_bytes()))
456            {
457                return n;
458            }
459        }
460        0
461    }
462}
463
464/// Normalise OpenAI `tool_choice` to a string the generator understands: `"auto"`/`"required"`/
465/// `"none"` pass through; a `{"type":"function","function":{"name":N}}` object becomes `N`.
466///
467/// The caller has already handled ABSENT/`null` (that is "no choice" → `Ok(None)` at the call site).
468/// This function is only reached for a PRESENT value, so an object that lacks a usable
469/// `function.name` — or any non-string/non-object shape — is a MALFORMED forced-tool request and is
470/// a 400 ([`ParamError`]), NOT a silent downgrade to "auto" (audit finding 6).
471fn tool_choice_str(v: &serde_json::Value) -> Result<Option<String>, ParamError> {
472    match v {
473        serde_json::Value::String(s) => Ok(Some(s.clone())),
474        serde_json::Value::Object(_) => v
475            .get("function")
476            .and_then(|f| f.get("name"))
477            .and_then(|n| n.as_str())
478            .map(|s| Some(s.to_owned()))
479            .ok_or_else(|| ParamError {
480                param: "tool_choice",
481                message: "tool_choice object must have a string `function.name`".into(),
482            }),
483        _ => Err(ParamError {
484            param: "tool_choice",
485            message: "tool_choice must be \"auto\"/\"required\"/\"none\" or a function object"
486                .into(),
487        }),
488    }
489}
490
491/// The three `tool_choice` values that are POLICIES rather than tool names.
492const TOOL_CHOICE_POLICIES: [&str; 3] = ["auto", "none", "required"];
493
494/// Cross-check a normalised `tool_choice` against the request's `tools`, which
495/// [`tool_choice_str`] cannot do on its own — it never sees `tools`.
496///
497/// Two holes this closes, both of which used to produce ordinary unconstrained assistant text
498/// (backlog B22). `OaiRenderer::tool_constraint` returns `Ok(None)` the moment `tools` is absent,
499/// without ever looking at `tool_choice`, and `run_chat` reads that `None` as "no constraint
500/// wanted":
501///
502/// - **A forced choice with no `tools`.** `"tool_choice":"required"` and no tools is a request the
503///   server cannot honour — there is nothing to call — so it is a 400 rather than a silent
504///   downgrade to free text. `"none"` is exempt: it asks for no tool call, which is satisfiable
505///   with no tools, and `"auto"` means "your discretion".
506/// - **A name that is not in `tools`.** A misspelled function name reached the generator as a
507///   forced choice and then vanished. With `tools` present it is worse than nothing: the name
508///   filter behind `OaiRenderer::tool_constraint` yields an empty array and
509///   `forced_tool_call_grammar` builds `{"anyOf": []}`, a grammar that matches no output at all.
510///
511/// Same policy as the existing malformed-object 400s: a forced tool call the server cannot deliver
512/// is an error, never a quiet fallback to "auto" (audit finding 6).
513fn validate_tool_choice(
514    tool_choice: Option<&str>,
515    tools: Option<&serde_json::Value>,
516) -> Result<(), ParamError> {
517    let Some(choice) = tool_choice else {
518        return Ok(());
519    };
520    if TOOL_CHOICE_POLICIES.contains(&choice) && choice != "required" {
521        return Ok(());
522    }
523    // `tools` may be absent, `null`, or an empty array — all "no tools offered".
524    let names: Vec<&str> = tools
525        .and_then(|t| t.as_array())
526        .map(|a| {
527            a.iter()
528                .filter_map(|t| t.get("function")?.get("name")?.as_str())
529                .collect()
530        })
531        .unwrap_or_default();
532    if names.is_empty() {
533        return Err(ParamError {
534            param: "tool_choice",
535            message: format!(
536                "tool_choice {choice:?} requires a non-empty `tools` array; none was supplied"
537            ),
538        });
539    }
540    if choice == "required" || names.contains(&choice) {
541        return Ok(());
542    }
543    Err(ParamError {
544        param: "tool_choice",
545        message: format!(
546            "tool_choice {choice:?} names no tool in `tools` (have: {})",
547            names.join(", ")
548        ),
549    })
550}
551
552/// A single chat message.  `content` may be a JSON string or a content-part array.
553#[derive(Debug, Deserialize, Serialize)]
554pub struct ChatMessageDto {
555    pub role: String,
556    #[serde(default)]
557    pub content: Option<serde_json::Value>,
558    /// Assistant's prior tool calls (OpenAI `[{id,type,function:{name,arguments}}]`), replayed on the
559    /// next turn so the model sees its own calls.
560    #[serde(default)]
561    pub tool_calls: Option<serde_json::Value>,
562    #[serde(default)]
563    pub tool_call_id: Option<String>,
564    #[serde(default)]
565    pub name: Option<String>,
566}
567
568// ---------------------------------------------------------------------------
569// Response DTOs — /v1/models
570// ---------------------------------------------------------------------------
571
572#[derive(Debug, Serialize)]
573pub struct ModelsResponse {
574    pub object: &'static str,
575    pub data: Vec<ModelCard>,
576}
577
578#[derive(Debug, Serialize)]
579pub struct ModelCard {
580    pub id: String,
581    pub object: &'static str,
582    pub owned_by: &'static str,
583}
584
585// ---------------------------------------------------------------------------
586// Response DTOs — /v1/chat/completions  (non-streaming)
587// ---------------------------------------------------------------------------
588
589#[derive(Debug, Serialize)]
590pub struct ChatCompletionResponse {
591    pub id: String,
592    pub object: &'static str,
593    pub created: i64,
594    pub model: String,
595    pub choices: Vec<CompletionChoice>,
596    pub usage: UsageInfo,
597}
598
599#[derive(Debug, Serialize)]
600pub struct CompletionChoice {
601    pub index: u32,
602    pub message: AssistantMessage,
603    pub finish_reason: String,
604}
605
606#[derive(Debug, Serialize)]
607pub struct AssistantMessage {
608    pub role: &'static str,
609    pub content: Option<String>,
610    #[serde(skip_serializing_if = "Option::is_none")]
611    pub reasoning_content: Option<String>,
612    #[serde(skip_serializing_if = "Option::is_none")]
613    pub tool_calls: Option<Vec<OAIToolCall>>,
614}
615
616/// OpenAI-shaped tool call (used in both streaming and non-streaming responses).
617#[derive(Debug, Clone, Serialize)]
618pub struct OAIToolCall {
619    pub index: usize,
620    pub id: String,
621    #[serde(rename = "type")]
622    pub kind: &'static str,
623    pub function: OAIFunction,
624}
625
626#[derive(Debug, Clone, Serialize)]
627pub struct OAIFunction {
628    pub name: String,
629    pub arguments: String,
630}
631
632#[derive(Debug, Serialize)]
633pub struct UsageInfo {
634    pub prompt_tokens: u32,
635    pub completion_tokens: u32,
636    pub total_tokens: u32,
637    pub prompt_tokens_details: PromptTokensDetails,
638}
639
640#[derive(Debug, Serialize)]
641pub struct PromptTokensDetails {
642    pub cached_tokens: u32,
643}
644
645impl UsageInfo {
646    /// The `usage` block for one finished generation — shared by the non-streaming body and the
647    /// streamed `include_usage` chunk, so the two cannot report different numbers.
648    pub fn from_outcome(outcome: &ChatOutcome) -> Self {
649        Self {
650            prompt_tokens: outcome.prompt_tokens,
651            completion_tokens: outcome.completion_tokens,
652            total_tokens: outcome
653                .prompt_tokens
654                .saturating_add(outcome.completion_tokens),
655            prompt_tokens_details: PromptTokensDetails {
656                cached_tokens: outcome.cached_tokens,
657            },
658        }
659    }
660}
661
662// ---------------------------------------------------------------------------
663// Response DTOs — /v1/chat/completions  (streaming chunks)
664// ---------------------------------------------------------------------------
665
666#[derive(Debug, Serialize)]
667pub struct ChatCompletionChunk {
668    pub id: String,
669    pub object: &'static str,
670    pub created: i64,
671    pub model: String,
672    pub choices: Vec<ChunkChoice>,
673    /// Only on the final `stream_options.include_usage` chunk.
674    #[serde(skip_serializing_if = "Option::is_none")]
675    pub usage: Option<UsageInfo>,
676}
677
678#[derive(Debug, Serialize)]
679pub struct ChunkChoice {
680    pub index: u32,
681    pub delta: DeltaPayload,
682    pub finish_reason: Option<String>,
683}
684
685/// The `delta` field inside a streaming chunk.  Fields absent when `None`.
686#[derive(Debug, Default, Serialize)]
687pub struct DeltaPayload {
688    #[serde(skip_serializing_if = "Option::is_none")]
689    pub role: Option<String>,
690    #[serde(skip_serializing_if = "Option::is_none")]
691    pub content: Option<String>,
692    #[serde(skip_serializing_if = "Option::is_none")]
693    pub reasoning_content: Option<String>,
694    #[serde(skip_serializing_if = "Option::is_none")]
695    pub tool_calls: Option<Vec<OAIToolCall>>,
696}
697
698// ---------------------------------------------------------------------------
699// Observability
700// ---------------------------------------------------------------------------
701
702/// Per-request id: a process-monotonic counter, NOT a timestamp.
703///
704/// It is deliberately not derived from the wall clock. Two requests admitted in the same
705/// millisecond (routine under `--parallel N`) would collide on a `now()`-based id, and the whole
706/// value of the id is that the arrival line and the completion line for ONE request can be joined
707/// in a log that has N of them interleaved. It is also NOT the wire `id` ([`make_id`]): that one is
708/// a client-facing `chatcmpl-…` string, and pinning a log key to a wire format is how the log
709/// breaks when the wire format moves.
710static REQ_SEQ: AtomicU64 = AtomicU64::new(1);
711
712fn next_req_id() -> u64 {
713    REQ_SEQ.fetch_add(1, Ordering::Relaxed)
714}
715
716/// The server-wide counters behind the periodic throughput line, and the two gauges behind
717/// `active`/`queued`.
718///
719/// **Everything here is an atomic and nothing here is a lock.** The only counter touched from
720/// inside a generation is [`Self::bump_gen`], one relaxed `fetch_add` per emitted delta — the
721/// decode loop must not acquire anything, because it is holding the GPU baton for every other
722/// sequence behind it (the same reason the SSE channel is unbounded).
723///
724/// The four `interval_*` counters are DRAINED (swapped to zero) by each report, which is what makes
725/// the reported numbers cover the interval rather than the process lifetime. The periodic line
726/// never reads a cumulative total: a total nobody drains is the thing that silently turns a rate
727/// into an average-since-boot. The lifetime counters in [`Self::lifetime`] exist for `/metrics`
728/// only, where the scraper takes the rate itself.
729#[derive(Debug, Default)]
730struct ServeStats {
731    /// Prompt tokens PREFILLED in this interval. Folded once per request, at completion — the real
732    /// count from [`ChatOutcome`], which is not knowable before the generator has tokenized.
733    interval_prompt_tokens: AtomicU64,
734    /// Tokens GENERATED in this interval, live. Incremented per delta while a generation runs (so a
735    /// long request shows up in the intervals it spans, not only in the one it ends in) and
736    /// RECONCILED at completion against `ChatOutcome::completion_tokens`, which is authoritative:
737    /// a delta is a text piece and is only approximately a token (a think-tag boundary can split
738    /// or merge one). The correction is signed, hence `i64`.
739    interval_gen_tokens: AtomicI64,
740    /// Requests that COMPLETED in this interval (success or failure).
741    interval_completed: AtomicU64,
742    /// Requests that FAILED in this interval — a subset of `interval_completed`.
743    interval_failed: AtomicU64,
744    /// Gauge: requests generating right now (holding a slot permit).
745    active: AtomicU64,
746    /// Gauge: requests admitted by the handler but still waiting for a slot permit.
747    queued: AtomicU64,
748    /// Which interval is currently open. Incremented by every [`Self::drain`].
749    ///
750    /// A completion's correction is only meaningful against the deltas it corrects, and those
751    /// deltas may already have been drained and REPORTED. Stamping each request's live count with
752    /// the window it landed in is what lets [`Self::fold_completion`] tell "still correctable" from
753    /// "already published" (backlog B24).
754    window: AtomicU64,
755    /// Never-drained counters behind `/metrics`.
756    lifetime: metrics::Lifetime,
757}
758
759impl ServeStats {
760    /// One decoded piece. The ONE call on the hot path — a single relaxed add.
761    fn bump_gen(&self, n: i64) {
762        self.interval_gen_tokens.fetch_add(n, Ordering::Relaxed);
763    }
764
765    /// The interval currently accepting tokens.
766    fn window(&self) -> u64 {
767        self.window.load(Ordering::Relaxed)
768    }
769
770    /// Fold one finished request's exact tallies in, once.
771    ///
772    /// **The correction is clamped to what this request still has in the OPEN window.** Deltas are
773    /// only an estimate of tokens (a think-tag boundary can split or merge one), so completion
774    /// reconciles against `ChatOutcome`'s authoritative count. But a retraction cannot reach a
775    /// window that has already been drained and logged, and subtracting it from the current one
776    /// takes the tokens out of whatever OTHER request is generating now — which is how a −1 from
777    /// request A turned request B's three real tokens into two (B24, proved).
778    ///
779    /// So a negative correction is applied only against `rec.deltas_in_window`, and only while
780    /// `rec.window` is still open. Anything older stays as it was reported: an interval line is a
781    /// statement about a window that has closed, and the honest move is to leave it alone rather
782    /// than to bill the difference to somebody else. A POSITIVE correction is always applied — it
783    /// is new information about tokens nobody has counted yet, the same shape as `prompt_tokens`
784    /// arriving at completion.
785    fn fold_completion(&self, rec: &ReqRecord) {
786        self.interval_prompt_tokens
787            .fetch_add(u64::from(rec.prompt_tokens), Ordering::Relaxed);
788        let correction = i64::from(rec.gen_tokens) - rec.deltas as i64;
789        if correction > 0 {
790            self.bump_gen(correction);
791        } else if correction < 0 && rec.window == self.window() {
792            // Retract at most what this request itself put into the window that is still open.
793            let retractable = rec.deltas_in_window.min(i64::MAX as u64) as i64;
794            self.bump_gen(-correction.abs().min(retractable));
795        }
796        self.interval_completed.fetch_add(1, Ordering::Relaxed);
797        self.lifetime.fold_completion(rec);
798    }
799
800    /// Fold one request that ended in an error. Its partial deltas are already counted; there is no
801    /// [`ChatOutcome`] to reconcile against, so nothing is corrected.
802    fn fold_failure(&self) {
803        self.interval_completed.fetch_add(1, Ordering::Relaxed);
804        self.interval_failed.fetch_add(1, Ordering::Relaxed);
805        self.lifetime.fold_failure();
806    }
807
808    /// Take the interval counters (resetting them to zero) and sample the gauges. `elapsed` is the
809    /// REAL time since the last drain, not the nominal period — a tick that ran late must not
810    /// inflate the rate it reports.
811    fn drain(&self, elapsed: Duration) -> StatsWindow {
812        // Close the current window BEFORE taking the counters: from here on, a completion whose
813        // deltas landed in the old window can no longer retract them (see `fold_completion`).
814        self.window.fetch_add(1, Ordering::Relaxed);
815        StatsWindow {
816            elapsed,
817            prompt_tokens: self.interval_prompt_tokens.swap(0, Ordering::Relaxed),
818            gen_tokens: self.interval_gen_tokens.swap(0, Ordering::Relaxed).max(0) as u64,
819            completed: self.interval_completed.swap(0, Ordering::Relaxed),
820            failed: self.interval_failed.swap(0, Ordering::Relaxed),
821            active: self.active.load(Ordering::Relaxed),
822            queued: self.queued.load(Ordering::Relaxed),
823            busy_slots: 0,
824            total_slots: 0,
825        }
826    }
827}
828
829/// One interval's drained counters — the whole input to one periodic log line.
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
831struct StatsWindow {
832    elapsed: Duration,
833    prompt_tokens: u64,
834    gen_tokens: u64,
835    completed: u64,
836    failed: u64,
837    active: u64,
838    queued: u64,
839    /// Slot permits held across every hosted model — KV slot occupancy.
840    busy_slots: u64,
841    /// Slot permits in existence across every hosted model (the sum of `--parallel N`).
842    total_slots: u64,
843}
844
845impl StatsWindow {
846    /// Was there anything to report? An interval in which the server did nothing at all emits NO
847    /// line — the periodic report is activity-only, deliberately not a heartbeat, so an idle server
848    /// leaves a clean log. A request that is mid-generation counts as activity (`active > 0`) even
849    /// when it has produced no token yet, so a long single request still reports every interval it
850    /// spans.
851    fn has_activity(&self) -> bool {
852        self.prompt_tokens > 0
853            || self.gen_tokens > 0
854            || self.completed > 0
855            || self.active > 0
856            || self.queued > 0
857    }
858
859    /// Prompt tokens ingested per WALL second of the interval.
860    ///
861    /// This is the server's aggregate ingest throughput, NOT one model's prefill speed: the
862    /// denominator is the interval, including the time the server spent decoding or idle. The
863    /// per-request completion line carries the other number (that request's `prompt_tokens / TTFT`),
864    /// and the two are supposed to differ — one answers "how much is this box doing", the other
865    /// "how fast is this model".
866    fn prefill_tps(&self) -> f64 {
867        per_second(self.prompt_tokens, self.elapsed)
868    }
869
870    /// Tokens generated per WALL second of the interval — aggregate across every in-flight request.
871    /// Same scope note as [`Self::prefill_tps`].
872    fn decode_tps(&self) -> f64 {
873        per_second(self.gen_tokens, self.elapsed)
874    }
875}
876
877/// `n` per second over `d`. A zero (or absurdly small) window yields 0.0 rather than an infinity —
878/// a log line reading `inf` is worse than one reading 0.
879fn per_second(n: u64, d: Duration) -> f64 {
880    let secs = d.as_secs_f64();
881    if secs > 0.0 {
882        n as f64 / secs
883    } else {
884        0.0
885    }
886}
887
888/// RAII gauge for [`ServeStats::queued`]: a request waiting for a slot permit. Dropped the moment
889/// the permit is acquired (or the acquire fails during shutdown).
890///
891/// A guard rather than a matching `fetch_sub` because there are three ways out of the wait — got
892/// the permit, the semaphore closed, the task was dropped — and a gauge that leaks on one of them
893/// reads as a permanently-queued request forever after.
894struct QueuedGuard(Arc<ServeStats>);
895
896impl QueuedGuard {
897    fn new(stats: Arc<ServeStats>) -> Self {
898        stats.queued.fetch_add(1, Ordering::Relaxed);
899        Self(stats)
900    }
901}
902
903impl Drop for QueuedGuard {
904    fn drop(&mut self) {
905        self.0.queued.fetch_sub(1, Ordering::Relaxed);
906    }
907}
908
909/// RAII gauge for [`ServeStats::active`]: a request holding a slot permit and generating. Moved
910/// INTO the blocking task alongside the permit, so it is released on exactly the same events the
911/// permit is — including an unwinding panic inside the decode closure.
912struct ActiveGuard(Arc<ServeStats>);
913
914impl ActiveGuard {
915    fn new(stats: Arc<ServeStats>) -> Self {
916        stats.active.fetch_add(1, Ordering::Relaxed);
917        Self(stats)
918    }
919}
920
921impl Drop for ActiveGuard {
922    fn drop(&mut self) {
923        self.0.active.fetch_sub(1, Ordering::Relaxed);
924    }
925}
926
927/// The per-request tally kept INSIDE the generation, as plain locals in the blocking task. It is
928/// folded into [`ServeStats`] once, at completion — the request's own timing needs no sharing, and
929/// making it shared would put a second atomic (or worse) on the decode path for nothing.
930#[derive(Debug)]
931struct ReqTally {
932    started: Instant,
933    /// When the FIRST delta arrived: the boundary between prefill and decode. `None` means the
934    /// generation produced nothing.
935    first_delta: Option<Instant>,
936    /// Text deltas seen (content + reasoning). Reconciled against the real token count at the end.
937    deltas: u64,
938    /// The [`ServeStats`] window `deltas_in_window` is counted against.
939    window: u64,
940    /// Deltas this request has contributed to `window` — i.e. how much of the still-open interval
941    /// is this request's, and therefore the most a completion correction may retract from it (B24).
942    deltas_in_window: u64,
943}
944
945impl ReqTally {
946    fn new() -> Self {
947        Self {
948            started: Instant::now(),
949            first_delta: None,
950            deltas: 0,
951            window: 0,
952            deltas_in_window: 0,
953        }
954    }
955
956    /// Called from the generator's `on_delta` callback for a TEXT delta. A few increments, one
957    /// relaxed atomic load and one relaxed atomic add — no lock, no allocation, nothing that can
958    /// block the decode loop.
959    ///
960    /// The load is what keeps `deltas_in_window` honest across a drain: a reporter tick between two
961    /// deltas moves the window, and this request's share of the new one restarts at zero. The load
962    /// and the add are not atomic together, so a drain landing exactly between them can misplace a
963    /// single token; that is one token on an interval line, and closing it would mean a lock on the
964    /// decode path, which is the one thing this whole structure exists to avoid.
965    fn on_text_delta(&mut self, stats: &ServeStats) {
966        if self.first_delta.is_none() {
967            self.first_delta = Some(Instant::now());
968        }
969        let w = stats.window();
970        if w != self.window {
971            self.window = w;
972            self.deltas_in_window = 0;
973        }
974        self.deltas += 1;
975        self.deltas_in_window += 1;
976        stats.bump_gen(1);
977    }
978
979    /// Close the tally out against the generator's authoritative counts.
980    fn finish(&self, outcome: ChatOutcome, finish: Finish) -> ReqRecord {
981        let total = self.started.elapsed();
982        // TTFT is the prefill boundary. With no delta at all (an empty completion) there is no
983        // boundary to draw, so the whole request counts as prefill and decode time is zero.
984        let prefill = self
985            .first_delta
986            .map_or(total, |t| t.saturating_duration_since(self.started));
987        ReqRecord {
988            // The tokens this request actually PREFILLED: what its prefill time was spent on, and
989            // what the throughput counters have always summed. A cached prefix cost nothing.
990            prompt_tokens: outcome.prompt_tokens.saturating_sub(outcome.cached_tokens),
991            gen_tokens: outcome.completion_tokens,
992            deltas: self.deltas,
993            window: self.window,
994            deltas_in_window: self.deltas_in_window,
995            prefill,
996            decode: total.saturating_sub(prefill),
997            total,
998            finish,
999        }
1000    }
1001}
1002
1003/// One finished request, as the completion log line and [`ServeStats::fold_completion`] see it.
1004#[derive(Debug, Clone, Copy)]
1005struct ReqRecord {
1006    prompt_tokens: u32,
1007    gen_tokens: u32,
1008    deltas: u64,
1009    /// The stats window this request's last deltas landed in — see [`ServeStats::fold_completion`].
1010    window: u64,
1011    /// How many of `deltas` were counted into `window`.
1012    deltas_in_window: u64,
1013    /// Time to the first delta — the prefill.
1014    prefill: Duration,
1015    /// From the first delta to the end — the decode.
1016    decode: Duration,
1017    total: Duration,
1018    finish: Finish,
1019}
1020
1021impl ReqRecord {
1022    /// THIS request's prefill speed: prompt tokens over its time-to-first-delta. A per-request
1023    /// number, unlike [`StatsWindow::prefill_tps`].
1024    fn prefill_tps(&self) -> f64 {
1025        per_second(u64::from(self.prompt_tokens), self.prefill)
1026    }
1027
1028    /// THIS request's decode speed: generated tokens over the time after the first delta.
1029    fn decode_tps(&self) -> f64 {
1030        per_second(u64::from(self.gen_tokens), self.decode)
1031    }
1032}
1033
1034/// Emit one request's completion line at INFO. The counterpart to the arrival line
1035/// ([`log_request_start`]), joined to it by `req`.
1036fn log_request_done(req_id: u64, model: &str, stream: bool, rec: &ReqRecord) {
1037    tracing::info!(
1038        req = req_id,
1039        model,
1040        stream,
1041        prompt_tokens = rec.prompt_tokens,
1042        gen_tokens = rec.gen_tokens,
1043        prefill_tps = format_args!("{:.1}", rec.prefill_tps()),
1044        decode_tps = format_args!("{:.1}", rec.decode_tps()),
1045        total_ms = format_args!("{:.0}", rec.total.as_secs_f64() * 1000.0),
1046        finish = rec.finish.as_str(),
1047        "request done"
1048    );
1049}
1050
1051/// Emit one request's arrival line at INFO.
1052///
1053/// `prompt_chars` and not prompt TOKENS, and that is a real limitation rather than an oversight:
1054/// the tokenizer lives behind [`ChatGenerator`], so at arrival the server genuinely does not know
1055/// how many tokens the messages are. The true count is on the completion line, from
1056/// [`ChatOutcome`]; the char count is the arrival-time proxy for "how big is this".
1057///
1058/// **No prompt text, ever.** Counts only. Putting user prompt text into an operator's logs is a
1059/// privacy decision that has been made in the negative — do not add a preview here, not even
1060/// truncated, not even behind a flag.
1061fn log_request_start(
1062    req_id: u64,
1063    route: &'static str,
1064    model: &str,
1065    messages: usize,
1066    prompt_chars: usize,
1067    max_tokens: Option<u32>,
1068    stream: bool,
1069) {
1070    tracing::info!(
1071        req = req_id,
1072        route,
1073        model,
1074        messages,
1075        prompt_chars,
1076        max_tokens = ?max_tokens,
1077        stream,
1078        "request start"
1079    );
1080}
1081
1082/// The configured period for the periodic throughput line, or `None` when it is switched OFF.
1083///
1084/// `serve.stats_interval_secs` (`INFR_SERVE_STATS_SECS`), where `0` means "no periodic line" —
1085/// the same "0 disables" grammar as [`request_timeout`], and for the same reason: an operator
1086/// piping this server's logs somewhere expensive needs a way to say no from the environment, over
1087/// a config file that said yes.
1088fn stats_interval(cfg: &Config) -> Option<Duration> {
1089    let secs = cfg.serve.stats_interval_secs;
1090    (secs > 0).then(|| Duration::from_secs(secs))
1091}
1092
1093/// The periodic throughput reporter: drain the interval counters every `period` and, IF anything
1094/// happened, log one line.
1095///
1096/// **Shutdown.** It polls the same process-wide latch [`shutdown_latched`] does, at the same 50 ms
1097/// granularity, so a Ctrl-C ends it at the next poll rather than up to a full period later — and it
1098/// is a plain tokio task, which cannot hold the process open by itself: when `serve_state` returns
1099/// the runtime drops and the task goes with it. It emits one FINAL drain on the way out so the
1100/// tokens generated in the last partial interval are not silently dropped.
1101async fn stats_reporter(state: AppState, period: Duration) {
1102    const POLL: Duration = Duration::from_millis(50);
1103    let mut last = Instant::now();
1104    loop {
1105        tokio::time::sleep(POLL).await;
1106        let shutting_down = infr_core::shutdown::shutdown_requested();
1107        if !shutting_down && last.elapsed() < period {
1108            continue;
1109        }
1110        let mut window = state.stats.drain(last.elapsed());
1111        (window.busy_slots, window.total_slots) = state.slot_occupancy();
1112        last = Instant::now();
1113        if window.has_activity() {
1114            tracing::info!(
1115                interval_s = format_args!("{:.1}", window.elapsed.as_secs_f64()),
1116                prefill_tps = format_args!("{:.1}", window.prefill_tps()),
1117                decode_tps = format_args!("{:.1}", window.decode_tps()),
1118                gen_tokens = window.gen_tokens,
1119                prompt_tokens = window.prompt_tokens,
1120                completed = window.completed,
1121                failed = window.failed,
1122                active = window.active,
1123                queued = window.queued,
1124                kv_slots = format_args!("{}/{}", window.busy_slots, window.total_slots),
1125                "serve stats"
1126            );
1127        }
1128        if shutting_down {
1129            return;
1130        }
1131    }
1132}
1133
1134// ---------------------------------------------------------------------------
1135// App state
1136// ---------------------------------------------------------------------------
1137
1138/// One hosted model: its wire id, its generator, and its OWN admission semaphore.
1139///
1140/// `engine` is an `Option<Arc<dyn ChatGenerator>>` so an entry can exist without a live model (the
1141/// headless test/`/v1/models` state). It is an `Arc`, NOT an `Arc<Mutex<_>>`: generation runs
1142/// concurrently and the generator synchronises itself (see [`ChatGenerator`]'s `&self` contract).
1143///
1144/// `slots` is PER-MODEL admission control — one permit per KV slot (`--parallel N`). A request
1145/// takes a permit for the whole of its generation and returns it at the end, so at most N generate
1146/// concurrently on THAT model and the N+1'th QUEUES (tokio's semaphore is FIFO) rather than being
1147/// rejected. Per-model (not global) is the point of the multi-model server: a model on the discrete
1148/// GPU and a model on the iGPU each admit their own N independently — one busy model never starves
1149/// another that lives on a different device.
1150#[derive(Clone)]
1151struct ModelEntry {
1152    id: Arc<str>,
1153    engine: Option<Arc<dyn ChatGenerator>>,
1154    slots: Arc<Semaphore>,
1155    /// How many permits `slots` was created with (`--parallel N`, floored at 1). `Semaphore` reports
1156    /// how many are AVAILABLE but not how many exist, and occupancy is the difference — so the
1157    /// capacity has to be remembered here or the periodic line cannot say `2/4`.
1158    capacity: usize,
1159}
1160
1161impl ModelEntry {
1162    fn new(id: &str, engine: Option<Arc<dyn ChatGenerator>>, n_parallel: usize) -> Self {
1163        let capacity = n_parallel.max(1);
1164        Self {
1165            id: Arc::from(id),
1166            engine,
1167            slots: Arc::new(Semaphore::new(capacity)),
1168            capacity,
1169        }
1170    }
1171
1172    /// Slot permits held right now: what the semaphore is NOT handing out, which is exactly the
1173    /// set of this model's generations in flight.
1174    fn busy(&self) -> usize {
1175        self.capacity - self.slots.available_permits().min(self.capacity)
1176    }
1177}
1178
1179/// Shared server state — a non-empty, ordered set of hosted `ModelEntry`s. A request is routed to
1180/// the entry whose `id` matches its `model` field; an unknown/empty `model` falls to the DEFAULT
1181/// (the first entry). The single-model server is just the one-entry case, so its behaviour — and the
1182/// hot path — is byte-identical to before this became multi-model.
1183#[derive(Clone)]
1184pub struct AppState {
1185    /// Invariant: non-empty. `models[0]` is the default route.
1186    models: Arc<Vec<ModelEntry>>,
1187    /// The resolved process configuration. The handler reads `serve.api_key` and
1188    /// `serve.max_tokens_cap` off it instead of the environment; it is an EXPLICIT constructor
1189    /// parameter on every entry point that can host a real model, so an embedder cannot silently
1190    /// end up with auth disabled by forgetting to pass one.
1191    cfg: Arc<Config>,
1192    /// Server-wide request/throughput counters (B10). Shared with the periodic reporter task
1193    /// [`stats_reporter`] that `serve_state` spawns; a state built for tests simply has no reporter
1194    /// draining it.
1195    stats: Arc<ServeStats>,
1196    /// When this state was built, for `/status`'s uptime.
1197    started: Instant,
1198}
1199
1200impl AppState {
1201    /// Wrap a single loaded generator for production use with `n_parallel` concurrent slots — the
1202    /// single-model server (the overwhelming common case). Equivalent to a one-entry
1203    /// [`multi`](Self::multi).
1204    pub fn new(
1205        generator: Arc<dyn ChatGenerator>,
1206        model_id: impl Into<String>,
1207        n_parallel: usize,
1208        cfg: Arc<Config>,
1209    ) -> Self {
1210        Self {
1211            models: Arc::new(vec![ModelEntry::new(
1212                &model_id.into(),
1213                Some(generator),
1214                n_parallel,
1215            )]),
1216            cfg,
1217            stats: Arc::default(),
1218            started: Instant::now(),
1219        }
1220    }
1221
1222    /// Host SEVERAL models at once, each with its OWN generator and per-model slot count. Each
1223    /// `(model_id, generator, n_parallel)` becomes a routable entry; the FIRST is the default route
1224    /// (used for a request with an unknown or empty `model`). This is the multi-device host: pass a
1225    /// generator pinned to each physical GPU and the server routes by model name — see `infr multi`.
1226    ///
1227    /// Panics if `entries` is empty (the state invariant is a non-empty model set); the CLI never
1228    /// calls it with none.
1229    pub fn multi(entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>, cfg: Arc<Config>) -> Self {
1230        assert!(
1231            !entries.is_empty(),
1232            "AppState::multi needs at least one model"
1233        );
1234        let models = entries
1235            .into_iter()
1236            .map(|(id, gen, n)| ModelEntry::new(&id, Some(gen), n))
1237            .collect();
1238        Self {
1239            models: Arc::new(models),
1240            cfg,
1241            stats: Arc::default(),
1242            started: Instant::now(),
1243        }
1244    }
1245
1246    /// No-engine state — for /health, /v1/models, and serialisation tests. Takes the config too,
1247    /// so an auth/cap test drives `serve.*` through a `Config` value rather than the environment
1248    /// (R7).
1249    pub fn headless(model_id: impl Into<String>, cfg: Arc<Config>) -> Self {
1250        Self {
1251            models: Arc::new(vec![ModelEntry::new(&model_id.into(), None, 1)]),
1252            cfg,
1253            stats: Arc::default(),
1254            started: Instant::now(),
1255        }
1256    }
1257
1258    /// KV slot occupancy across every hosted model: `(busy, total)` permits.
1259    fn slot_occupancy(&self) -> (u64, u64) {
1260        self.models.iter().fold((0, 0), |(busy, total), m| {
1261            (busy + m.busy() as u64, total + m.capacity as u64)
1262        })
1263    }
1264
1265    /// Route a request's `model` field to a hosted entry: an exact id match, else the default
1266    /// (first) entry — mirroring OpenAI servers, which never 404 on the model name. Returns a clone
1267    /// of the entry's `Arc` handles (cheap) so the caller owns them across the `spawn_blocking`.
1268    fn route(&self, requested: &str) -> ModelEntry {
1269        self.models
1270            .iter()
1271            .find(|m| &*m.id == requested)
1272            .unwrap_or(&self.models[0])
1273            .clone()
1274    }
1275}
1276
1277// ---------------------------------------------------------------------------
1278// Router
1279// ---------------------------------------------------------------------------
1280
1281/// Build the axum [`Router`].  Extracted so tests can call it with a [`AppState::headless`] state.
1282pub fn build_router(state: AppState) -> Router {
1283    Router::new()
1284        .route("/health", get(health_handler))
1285        .route("/v1/models", get(models_handler))
1286        .route("/metrics", get(metrics::metrics_handler))
1287        .route("/status", get(status::status_handler))
1288        .route(
1289            "/v1/chat/completions",
1290            post(chat_completions_handler)
1291                .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
1292        )
1293        .with_state(state)
1294}
1295
1296/// [`auth_gate`] as a layer, for the route that takes a body. A handler's extractors all run
1297/// before its first statement, so a check inside the handler comes AFTER the JSON body has been
1298/// buffered and parsed; an unauthenticated client could make the server do that work up to the
1299/// body limit, or hold the request open by never finishing its body. As a layer it runs on the
1300/// headers alone.
1301async fn require_auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
1302    if let Some(denied) = auth_gate(&state.cfg, req.headers()) {
1303        return denied;
1304    }
1305    next.run(req).await
1306}
1307
1308// ---------------------------------------------------------------------------
1309// Server entry point
1310// ---------------------------------------------------------------------------
1311
1312/// Start the OpenAI-compatible server bound to `addr`, serving `engine` under `model_id` with
1313/// `n_parallel` concurrent generation slots (`--parallel N`).
1314pub async fn serve(
1315    generator: Arc<dyn ChatGenerator>,
1316    model_id: String,
1317    addr: SocketAddr,
1318    n_parallel: usize,
1319    cfg: Arc<Config>,
1320) -> anyhow::Result<()> {
1321    serve_state(AppState::new(generator, model_id, n_parallel, cfg), addr).await
1322}
1323
1324/// Start the server hosting SEVERAL models at once, each routed by its `model_id` and admitted with
1325/// its own `n_parallel` slot count (`entries[0]` is the default route). This is the multi-device
1326/// host (`infr multi`): each generator can be pinned to a different physical GPU, and the server
1327/// dispatches a request to the generator for the model it names. Graceful shutdown drains EVERY
1328/// model's in-flight requests before any backend drops (the axum layer stops accepting, then each
1329/// generation returns at its next abort poll — see `shutdown_latched`); when `serve_multi`
1330/// returns, the runtime drops and every backend's device is destroyed in turn.
1331pub async fn serve_multi(
1332    entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>,
1333    addr: SocketAddr,
1334    cfg: Arc<Config>,
1335) -> anyhow::Result<()> {
1336    serve_state(AppState::multi(entries, cfg), addr).await
1337}
1338
1339/// Bind + run the axum server over a fully-built [`AppState`] (single- or multi-model). The one
1340/// place the listener, the graceful-shutdown latch, and `axum::serve` live.
1341async fn serve_state(state: AppState, addr: SocketAddr) -> anyhow::Result<()> {
1342    let n_models = state.models.len();
1343    // The periodic throughput reporter (B10), unless `serve.stats_interval_secs` is 0. It reads the
1344    // SAME shutdown latch the drain path does, and it is aborted here as well: whichever way the
1345    // server ends, no task is left ticking.
1346    let reporter = stats_interval(&state.cfg)
1347        .map(|period| tokio::spawn(stats_reporter(state.clone(), period)));
1348    let router = build_router(state);
1349    let listener = tokio::net::TcpListener::bind(addr).await?;
1350    tracing::info!(%addr, %n_models, "infr-server listening");
1351    let served = axum::serve(listener, router)
1352        .with_graceful_shutdown(shutdown_latched())
1353        .await;
1354    if let Some(h) = reporter {
1355        h.abort();
1356    }
1357    served?;
1358    Ok(())
1359}
1360
1361/// Resolves once the process-wide shutdown latch is set (SIGINT/SIGTERM — see
1362/// [`infr_core::shutdown`]), which is `axum`'s cue to stop accepting connections and let the
1363/// in-flight ones finish. The requests themselves see the SAME latch through the decode loop's
1364/// abort poll, so each one stops issuing new GPU work at its next token/chunk boundary, drains what
1365/// it already submitted, and returns what it had — then `serve` returns, the runtime drops, the
1366/// engine drops, and the Vulkan device is destroyed properly. No `process::exit` anywhere on this
1367/// path: exiting under a live submit is the bug this whole mechanism exists to prevent.
1368///
1369/// A POLL (50 ms) rather than `tokio::signal::ctrl_c`, on purpose: the CLI already owns SIGINT and
1370/// SIGTERM via `sigaction`, and `tokio::signal` would install its OWN handler over the top of it —
1371/// last writer wins, and the loser's semantics (in this case, "drain the GPU") silently vanish. One
1372/// handler, one latch, everything downstream reads the latch.
1373async fn shutdown_latched() {
1374    while !infr_core::shutdown::shutdown_requested() {
1375        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1376    }
1377    tracing::info!("shutdown requested — draining in-flight requests");
1378}
1379
1380// ---------------------------------------------------------------------------
1381// Handlers
1382// ---------------------------------------------------------------------------
1383
1384/// Deliberately UNAUTHENTICATED, even when `serve.api_key` is configured. A load balancer, a
1385/// container orchestrator or an uptime probe has to reach this without holding the operator's
1386/// bearer token, and the response is a bare 200 with no body: it discloses nothing about the model
1387/// set, the config, or the machine. Every route that DOES disclose something is gated — see
1388/// [`auth_gate`].
1389async fn health_handler() -> StatusCode {
1390    StatusCode::OK
1391}
1392
1393/// The hosted model list — GATED by the same bearer check as `/v1/chat/completions`.
1394///
1395/// This endpoint enumerates every model id the process is serving. With `serve.api_key` set the
1396/// operator has said the server is not open to whoever can reach the port, and an unauthenticated
1397/// caller must not be able to inventory what is hosted (which names to try, how many devices are
1398/// behind it, which private fine-tune is loaded) — that is reconnaissance, and it used to be free.
1399///
1400/// Returns a [`Response`] rather than `Json<ModelsResponse>` purely so the 401 can share the body
1401/// shape the chat handler returns; the 200 body is byte-identical to what it has always been.
1402/// With auth DISABLED (the default) [`auth_gate`] returns `None` and this is the same open endpoint
1403/// as before — the localhost experience does not change.
1404async fn models_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
1405    if let Some(denied) = auth_gate(&state.cfg, &headers) {
1406        return denied;
1407    }
1408    Json(ModelsResponse {
1409        object: "list",
1410        data: state
1411            .models
1412            .iter()
1413            .map(|m| ModelCard {
1414                id: m.id.to_string(),
1415                object: "model",
1416                owned_by: "local",
1417            })
1418            .collect(),
1419    })
1420    .into_response()
1421}
1422
1423/// Bearer auth for this route is [`require_auth`], layered in front of it by [`build_router`].
1424async fn chat_completions_handler(
1425    State(state): State<AppState>,
1426    body: Result<Json<ChatRequest>, JsonRejection>,
1427) -> Response {
1428    let Json(req) = match body {
1429        Ok(j) => j,
1430        Err(e) => return body_rejection(e),
1431    };
1432    let mut params = match GenParams::from_request(&req) {
1433        Ok(p) => p,
1434        Err(e) => return param_error(Some(e.param), e.message),
1435    };
1436    // Cap an absurd explicit budget so one request can't pin a slot forever. Unset stays unset.
1437    params.max_tokens = clamp_max_tokens(params.max_tokens, max_tokens_cap(&state.cfg));
1438    let messages: Vec<ChatMessage> = req.messages.iter().map(dto_to_engine).collect();
1439    // Pass the request's `tools` array THROUGH as a Value (moved into the blocking task) — no
1440    // Value→string→Value round-trip (audit finding 6).
1441    let tools: Option<serde_json::Value> = req.tools.clone();
1442    // A PRESENT-but-malformed forced tool_choice is a 400, not a silent downgrade to "auto".
1443    let tool_choice: Option<String> = match req.tool_choice.as_ref() {
1444        None | Some(serde_json::Value::Null) => None,
1445        Some(v) => match tool_choice_str(v) {
1446            Ok(tc) => tc,
1447            Err(e) => return param_error(Some(e.param), e.message),
1448        },
1449    };
1450    // …and a WELL-FORMED forced choice the server cannot honour is a 400 too: the constraint
1451    // builder ignores `tool_choice` entirely when `tools` is absent, so without this the request
1452    // would quietly generate ordinary text instead (B22).
1453    if let Err(e) = validate_tool_choice(tool_choice.as_deref(), tools.as_ref()) {
1454        return param_error(Some(e.param), e.message);
1455    }
1456
1457    // Route to the hosted model named in the request (exact id), else the default (first) entry.
1458    // The response `model` field echoes the entry ACTUALLY served, not the raw request string, so a
1459    // client that omitted/mis-named the model sees which one answered.
1460    let entry = state.route(&req.model);
1461    let model_id = entry.id.to_string();
1462    let ctx = ReqCtx {
1463        id: next_req_id(),
1464        cid: make_id(),
1465        model_id,
1466        created: unix_ts(),
1467        // Resolved HERE, once, so both paths see the same policy and neither reaches for the config
1468        // from inside a blocking task. `None` (the default) = no deadline, exactly as before.
1469        deadline: request_timeout(&state.cfg),
1470        stream: req.stream,
1471        include_usage: req.stream_options.as_ref().is_some_and(|o| o.include_usage),
1472        stats: state.stats.clone(),
1473    };
1474    log_request_start(
1475        ctx.id,
1476        "/v1/chat/completions",
1477        &ctx.model_id,
1478        messages.len(),
1479        messages.iter().map(|m| m.content.len()).sum(),
1480        params.max_tokens,
1481        ctx.stream,
1482    );
1483
1484    if ctx.stream {
1485        streaming(entry, messages, tools, tool_choice, params, ctx).await
1486    } else {
1487        non_streaming(entry, messages, tools, tool_choice, params, ctx).await
1488    }
1489}
1490
1491/// Everything about one in-flight request that is not its messages: identity (the log's `req` and
1492/// the wire's `chatcmpl-…`), the reply framing, the deadline policy, and the shared counters.
1493///
1494/// It exists because [`streaming`] and [`non_streaming`] took nine positional arguments and the
1495/// instrumentation wanted three more — at which point the next `String` inserted in the wrong slot
1496/// is a bug the compiler cannot see.
1497struct ReqCtx {
1498    /// Log-only, monotonic. See [`next_req_id`].
1499    id: u64,
1500    /// The client-facing completion id (`chatcmpl-…`).
1501    cid: String,
1502    /// The model that ACTUALLY answered, echoed on the wire.
1503    model_id: String,
1504    created: i64,
1505    deadline: Option<Duration>,
1506    stream: bool,
1507    /// `stream_options.include_usage`: end the stream with a `usage` chunk.
1508    include_usage: bool,
1509    stats: Arc<ServeStats>,
1510}
1511
1512// ---------------------------------------------------------------------------
1513// Non-streaming path
1514// ---------------------------------------------------------------------------
1515
1516async fn non_streaming(
1517    entry: ModelEntry,
1518    messages: Vec<ChatMessage>,
1519    tools: Option<serde_json::Value>,
1520    tool_choice: Option<String>,
1521    params: GenParams,
1522    ctx: ReqCtx,
1523) -> Response {
1524    let ReqCtx {
1525        id: req_id,
1526        cid,
1527        model_id,
1528        created,
1529        deadline,
1530        stream,
1531        include_usage: _,
1532        stats,
1533    } = ctx;
1534    // Wait for a free slot ON THIS MODEL. With `--parallel N`, the (N+1)'th concurrent request to
1535    // this model queues HERE — in the async runtime, holding no thread — and is admitted FIFO as
1536    // soon as one of that model's generations finishes. A different model's slots are independent.
1537    // The guard is what the periodic line's `queued` counts; it drops however the wait ends.
1538    let queued = QueuedGuard::new(stats.clone());
1539    let Ok(permit) = entry.slots.clone().acquire_owned().await else {
1540        stats.fold_failure();
1541        tracing::warn!(req = req_id, "rejected — server shutting down");
1542        return json_error(
1543            StatusCode::SERVICE_UNAVAILABLE,
1544            "server shutting down".into(),
1545        );
1546    };
1547    drop(queued);
1548    let active = ActiveGuard::new(stats.clone());
1549    let engine_arc = entry.engine.clone();
1550    let cid_blk = cid.clone();
1551    let stats_blk = stats.clone();
1552
1553    // Per-request abort latch. It lives OUT here, not inside the closure, so the deadline below can
1554    // reach it: the generator polls it in its decode loop, and that poll is the only way to stop a
1555    // `spawn_blocking` task early.
1556    let cancel = Arc::new(AtomicBool::new(false));
1557    let cancel_blk = cancel.clone();
1558    // A client that hangs up is noticed by hyper, which DROPS this handler future — and with it
1559    // this guard, which latches the abort so the generation stops and frees its slot instead of
1560    // running to `max_tokens` for nobody. On a normal return it latches a generation that has
1561    // already ended, which nothing reads.
1562    let _hangup = CancelOnDrop(cancel.clone());
1563
1564    let mut handle = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
1565        // The permit is MOVED into the blocking task and dropped when it ends: a slot is held for
1566        // exactly the generation, and the next queued request is admitted the moment it frees. The
1567        // `active` gauge rides along with it, so the two can never disagree.
1568        let _permit = permit;
1569        let _active = active;
1570        let Some(engine) = engine_arc else {
1571            anyhow::bail!("no engine loaded");
1572        };
1573
1574        let mut reasoning = String::new();
1575        let mut content = String::new();
1576        let mut tool_calls: Vec<OAIToolCall> = Vec::new();
1577        // Per-request tally: plain locals, folded into the shared counters once at the end.
1578        let mut tally = ReqTally::new();
1579
1580        let outcome = engine.chat(
1581            &messages,
1582            tools.as_ref(),
1583            tool_choice.as_deref(),
1584            &params,
1585            &cancel_blk,
1586            &mut |delta| match delta {
1587                Delta::Reasoning(t) => {
1588                    tally.on_text_delta(&stats_blk);
1589                    reasoning.push_str(&t);
1590                }
1591                Delta::Content(t) => {
1592                    tally.on_text_delta(&stats_blk);
1593                    content.push_str(&t);
1594                }
1595                Delta::ToolCall { name, arguments } => {
1596                    let idx = tool_calls.len();
1597                    tool_calls.push(OAIToolCall {
1598                        index: idx,
1599                        id: tool_call_id(&cid_blk, idx),
1600                        kind: "function",
1601                        function: OAIFunction { name, arguments },
1602                    });
1603                }
1604            },
1605        )?;
1606
1607        Ok((reasoning, content, tool_calls, outcome, tally))
1608    });
1609
1610    // The deadline, and the ONE thing about it that is easy to get wrong.
1611    //
1612    // `tokio::time::timeout(d, handle).await` returning `Err` and being propagated to the client is
1613    // NOT a fix: the blocking task is not cancellable, so it would keep decoding, keep holding its
1614    // `OwnedSemaphorePermit`, and the `--parallel` slot — the entire reason for having a deadline —
1615    // would stay occupied while we reported failure. So the timeout is used only to WAKE US: on
1616    // expiry we latch the abort flag the generator polls and then go back to awaiting the SAME
1617    // join. The task ends at its next token boundary, the permit drops, and we still have every
1618    // delta it produced before then, which is what the client gets.
1619    //
1620    // No watchdog TASK on this path (unlike [`streaming`]): the handler is already awaiting the
1621    // join, so the timer can live inside its own future. Nothing to spawn means nothing to tear
1622    // down — the `Timeout` future is dropped by the `.await` that resolves it, whichever way it
1623    // went, and a request that finishes in 5 ms under an hour-long deadline leaves nothing behind.
1624    let mut deadline_hit = false;
1625    let joined = match deadline {
1626        None => handle.await,
1627        Some(d) => match tokio::time::timeout(d, &mut handle).await {
1628            Ok(joined) => joined,
1629            Err(_elapsed) => {
1630                deadline_hit = true;
1631                cancel.store(true, Ordering::Relaxed);
1632                tracing::warn!(
1633                    req = req_id,
1634                    timeout_s = d.as_secs(),
1635                    "request deadline hit — returning the partial completion"
1636                );
1637                handle.await
1638            }
1639        },
1640    };
1641    let result = joined.map_err(anyhow::Error::from).and_then(|r| r);
1642
1643    match result {
1644        Err(e) => {
1645            stats.fold_failure();
1646            tracing::warn!(req = req_id, error = %e, "request failed");
1647            match e.downcast_ref::<ContextLengthExceeded>() {
1648                Some(c) => (StatusCode::BAD_REQUEST, Json(context_length_body(c))).into_response(),
1649                None => json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
1650            }
1651        }
1652        Ok((reasoning, content, tool_calls, outcome, tally)) => {
1653            // A deadline hit is a TRUNCATION, not a failure: the client keeps the partial reply
1654            // (a 500 would throw away work it can use) and `finish_reason` says "length", which is
1655            // OpenAI's reason for a completion that ran out of budget.
1656            //
1657            // It has to be decided here because the generator cannot know. From inside the decode
1658            // loop, the latch we set is indistinguishable from any other abort, so it reports a
1659            // clean `Finish::Stop` — and "stop" tells the client the model finished its thought,
1660            // which would be a lie. Only the handler that armed the deadline knows it fired.
1661            //
1662            // A tool call still wins, as it does for every other reason: the call was emitted
1663            // whole, and a client that gets `tool_calls` can act on it.
1664            let finish = if !tool_calls.is_empty() {
1665                Finish::ToolCalls
1666            } else if deadline_hit {
1667                Finish::Length
1668            } else {
1669                outcome.finish
1670            };
1671            // Fold the request's tallies in ONCE, here, and log its completion line.
1672            let rec = tally.finish(outcome, finish);
1673            stats.fold_completion(&rec);
1674            log_request_done(req_id, &model_id, stream, &rec);
1675            Json(ChatCompletionResponse {
1676                id: cid,
1677                object: "chat.completion",
1678                created,
1679                model: model_id,
1680                choices: vec![CompletionChoice {
1681                    index: 0,
1682                    message: AssistantMessage {
1683                        role: "assistant",
1684                        content: if content.is_empty() {
1685                            None
1686                        } else {
1687                            Some(content.clone())
1688                        },
1689                        reasoning_content: if reasoning.is_empty() {
1690                            None
1691                        } else {
1692                            Some(reasoning)
1693                        },
1694                        tool_calls: if tool_calls.is_empty() {
1695                            None
1696                        } else {
1697                            Some(tool_calls)
1698                        },
1699                    },
1700                    finish_reason: finish.as_str().into(),
1701                }],
1702                usage: UsageInfo::from_outcome(&outcome),
1703            })
1704            .into_response()
1705        }
1706    }
1707}
1708
1709// ---------------------------------------------------------------------------
1710// Streaming path (SSE)
1711// ---------------------------------------------------------------------------
1712
1713async fn streaming(
1714    entry: ModelEntry,
1715    messages: Vec<ChatMessage>,
1716    tools: Option<serde_json::Value>,
1717    tool_choice: Option<String>,
1718    params: GenParams,
1719    ctx: ReqCtx,
1720) -> Response {
1721    let ReqCtx {
1722        id: req_id,
1723        cid,
1724        model_id,
1725        created,
1726        deadline,
1727        stream,
1728        include_usage,
1729        stats,
1730    } = ctx;
1731    // UNBOUNDED on purpose. The generator's `on_delta` callback is invoked from inside the decode
1732    // loop — which, under `--parallel N`, is holding the GPU baton. A bounded channel would make a
1733    // slow (or stalled) SSE client apply backpressure straight into that callback, so ONE
1734    // non-draining client would block the GPU step it is inside of and stall every OTHER sequence
1735    // behind it: precisely the head-of-line blocking this whole change exists to remove. Decoupling
1736    // the socket from the decode loop costs a queue whose depth is bounded anyway by `max_tokens`
1737    // (a few thousand short strings, worst case), which is the right trade.
1738    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
1739
1740    // Same per-model admission gate as the non-streaming path — the (N+1)'th concurrent stream to
1741    // this model queues here. Taken BEFORE the SSE response is returned, so a queued client simply
1742    // waits for its first byte rather than being handed an open-but-silent stream.
1743    let queued = QueuedGuard::new(stats.clone());
1744    let Ok(permit) = entry.slots.clone().acquire_owned().await else {
1745        stats.fold_failure();
1746        tracing::warn!(req = req_id, "rejected — server shutting down");
1747        return json_error(
1748            StatusCode::SERVICE_UNAVAILABLE,
1749            "server shutting down".into(),
1750        );
1751    };
1752    drop(queued);
1753    let active = ActiveGuard::new(stats.clone());
1754    let engine_arc = entry.engine.clone();
1755    // Clone sender + strings for use inside the on_delta callback closure.
1756    let tx_cb = tx.clone();
1757    let cid_cb = cid.clone();
1758    let model_cb = model_id.clone();
1759    let stats_cb = stats.clone();
1760
1761    // Per-request abort latch: set when the client disconnects and polled by the generator's
1762    // decode loop so it stops promptly and frees the GPU slot instead of running to `max_tokens`
1763    // into a dead socket (audit finding 2). A failed `send` below notices the hang-up only at the
1764    // next delta; [`cancel_on_hangup`] notices it as it happens — during a long prefill, or while
1765    // the stop matcher holds output back, no delta is being sent at all.
1766    let cancel = Arc::new(AtomicBool::new(false));
1767    let cancel_cb = cancel.clone();
1768    let hangup_done = cancel_on_hangup(&tx, cancel.clone());
1769
1770    // Wall-clock deadline. Unlike the non-streaming path, nothing here awaits the generation's join
1771    // — the SSE response is returned as soon as the stream exists — so the timer needs its own
1772    // task, and that task needs an off switch. [`arm_deadline`] hands back a sender whose DROP is
1773    // that switch; it is moved into the blocking closure below, so the watchdog dies with the
1774    // generation (normally or by panic) instead of accumulating one sleeper per request.
1775    //
1776    // `deadline_hit` is separate from `cancel` because `cancel` is ALSO latched by a client
1777    // disconnect, and the finish chunk must not report a timeout as a hangup or vice versa.
1778    let deadline_hit = Arc::new(AtomicBool::new(false));
1779    let deadline_hit_cb = deadline_hit.clone();
1780    let done_tx = deadline.map(|d| arm_deadline(d, cancel.clone(), deadline_hit.clone()));
1781
1782    tokio::task::spawn_blocking(move || {
1783        // Held for exactly this generation; freed for the next queued request on return. The
1784        // `active` gauge is released by the same return (or unwind).
1785        let _permit = permit;
1786        let _active = active;
1787        // Disarms the deadline watchdog when this task ends — see [`arm_deadline`]. `None` when no
1788        // deadline was configured, in which case there is no watchdog to disarm.
1789        let _done_tx = done_tx;
1790        // Likewise ends the hang-up watcher, whose sender clone would otherwise hold the stream
1791        // open.
1792        let _hangup_done = hangup_done;
1793        // Closes the stream exactly once, however this closure ends. It emits `[DONE]` always, and
1794        // — unless `settled()` says a terminal frame already went out — reports the generation as a
1795        // failure. Both matter on an unwinding panic, which skips every arm below (B23).
1796        let mut done = DoneGuard {
1797            tx: tx.clone(),
1798            req_id,
1799            stats: stats.clone(),
1800            settled: false,
1801        };
1802
1803        // First chunk: role delta (mirrors the Python shim's opening chunk).
1804        let _ = tx.send(Ok(sse_chunk(
1805            &cid,
1806            &model_id,
1807            created,
1808            DeltaPayload {
1809                role: Some("assistant".into()),
1810                ..Default::default()
1811            },
1812            None,
1813        )));
1814
1815        let Some(engine) = engine_arc else {
1816            // `fail` sends the error frame, folds the statistic and logs; `DoneGuard` then closes
1817            // the stream with `[DONE]`.
1818            done.fail("no engine loaded");
1819            return;
1820        };
1821
1822        let mut tc_index = 0usize;
1823        let mut saw_tool_call = false;
1824        // Per-request tally: plain locals inside the generation, folded in once below.
1825        let mut tally = ReqTally::new();
1826
1827        let res = engine.chat(
1828            &messages,
1829            tools.as_ref(),
1830            tool_choice.as_deref(),
1831            &params,
1832            &cancel_cb,
1833            &mut |delta| {
1834                let payload = match delta {
1835                    Delta::Reasoning(t) => {
1836                        tally.on_text_delta(&stats_cb);
1837                        DeltaPayload {
1838                            reasoning_content: Some(t),
1839                            ..Default::default()
1840                        }
1841                    }
1842                    Delta::Content(t) => {
1843                        tally.on_text_delta(&stats_cb);
1844                        DeltaPayload {
1845                            content: Some(t),
1846                            ..Default::default()
1847                        }
1848                    }
1849                    Delta::ToolCall { name, arguments } => {
1850                        let tc = OAIToolCall {
1851                            index: tc_index,
1852                            id: tool_call_id(&cid_cb, tc_index),
1853                            kind: "function",
1854                            function: OAIFunction { name, arguments },
1855                        };
1856                        tc_index += 1;
1857                        saw_tool_call = true;
1858                        DeltaPayload {
1859                            tool_calls: Some(vec![tc]),
1860                            ..Default::default()
1861                        }
1862                    }
1863                };
1864                // A failed send means the receiver (the client's stream) is gone. Latch the abort so
1865                // the decode loop stops at its next poll and returns the slot.
1866                if tx_cb
1867                    .send(Ok(sse_chunk(&cid_cb, &model_cb, created, payload, None)))
1868                    .is_err()
1869                {
1870                    cancel_cb.store(true, Ordering::Relaxed);
1871                }
1872            },
1873        );
1874
1875        match res {
1876            Ok(outcome) => {
1877                // Same honesty rule as the non-streaming path: the generator saw only an abort and
1878                // reports `Stop`, so the deadline has to relabel it "length" — the budget ran out,
1879                // the model did not finish. A tool call still wins.
1880                let finish = if saw_tool_call {
1881                    Finish::ToolCalls
1882                } else if deadline_hit_cb.load(Ordering::Relaxed) {
1883                    Finish::Length
1884                } else {
1885                    outcome.finish
1886                };
1887                // Finish chunk: empty delta + finish_reason.
1888                let _ = tx.send(Ok(sse_chunk(
1889                    &cid,
1890                    &model_id,
1891                    created,
1892                    DeltaPayload::default(),
1893                    Some(finish.as_str().into()),
1894                )));
1895                if include_usage {
1896                    let _ = tx.send(Ok(sse_usage_chunk(&cid, &model_id, created, &outcome)));
1897                }
1898                // Fold the request's tallies in ONCE, here, and log its completion line. The finish
1899                // chunk above IS this stream's terminal frame, so the guard must not also report a
1900                // failure when it drops.
1901                let rec = tally.finish(outcome, finish);
1902                stats.fold_completion(&rec);
1903                log_request_done(req_id, &model_id, stream, &rec);
1904                done.settled();
1905            }
1906            Err(e) => {
1907                // A mid-stream failure is NOT a clean `stop` — the error frame lets the client tell
1908                // this apart from success (matching the non-streaming 500). `[DONE]` still follows,
1909                // via `DoneGuard` (audit finding 1). An over-long prompt carries the same typed error
1910                // the non-streaming path answers with a 400, so a client can tell it from a crash.
1911                match e.downcast_ref::<ContextLengthExceeded>() {
1912                    Some(c) => done.fail_with(context_length_body(c), &c.message),
1913                    None => done.fail(&e.to_string()),
1914                }
1915            }
1916        }
1917        // `DoneGuard` drops here (or on an unwinding panic). It sends `[DONE]`, and if nothing
1918        // above settled the stream it first reports the request as failed (B23).
1919    });
1920
1921    // Bridge the mpsc receiver to an async Stream for axum's Sse.
1922    let stream = futures_util::stream::unfold(rx, |mut rx| async move {
1923        rx.recv().await.map(|item| (item, rx))
1924    });
1925
1926    Sse::new(stream).into_response()
1927}
1928
1929// ---------------------------------------------------------------------------
1930// Private helpers
1931// ---------------------------------------------------------------------------
1932
1933/// Closes the SSE stream exactly once when it drops, from the normal end of the generation OR from
1934/// an unwinding panic inside the decode closure.
1935///
1936/// Two jobs, and the second one exists because the first was not enough:
1937///
1938/// 1. `[DONE]` is ALWAYS the final frame. A strict SSE client blocks until it sees the sentinel, so
1939///    a swallowed panic must never leave it unsent (audit finding 1).
1940/// 2. A generation that never reached its terminal frame is reported AS A FAILURE — error frame,
1941///    `fold_failure`, and a `warn!` carrying the `req` id.
1942///
1943/// The streaming path discards its `spawn_blocking` join handle, so a panic in
1944/// `ChatGenerator::chat` unwinds past the `match res` and the `Err` arm never runs. Before this
1945/// guard owned the failure path, the wire showed the role chunk and then `[DONE]` with no error
1946/// frame and no terminal `finish_reason` — indistinguishable from a short success — while
1947/// `interval_failed` AND `interval_completed` both stayed zero, so the throughput line under-
1948/// reported the failure and the completion at once (backlog B23, proved).
1949///
1950/// [`Self::settled`] is what separates the two cases. Every path that produces its own terminal
1951/// frame calls it; anything that unwinds or returns early does not, and the guard speaks for it.
1952/// A flag rather than `std::thread::panicking()` because an early `return` is not a panic and still
1953/// leaves the stream unterminated.
1954struct DoneGuard {
1955    tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
1956    /// The request id, so the failure this guard reports joins its `request start` line.
1957    req_id: u64,
1958    stats: Arc<ServeStats>,
1959    /// Set by [`Self::settled`] once a terminal frame is out and the tallies are folded.
1960    settled: bool,
1961}
1962
1963impl DoneGuard {
1964    /// The generation reached a terminal frame and folded its own tallies — the guard should send
1965    /// nothing but `[DONE]`.
1966    fn settled(&mut self) {
1967        self.settled = true;
1968    }
1969
1970    /// Report this request as failed, exactly once: terminal error frame, `fold_failure`, `warn!`.
1971    ///
1972    /// The ONE place a streaming failure is recorded, so the wire frame, the statistic and the log
1973    /// line cannot drift apart or be emitted twice. Called explicitly by the paths that know why
1974    /// they failed, and by [`Drop`] for the paths that never got the chance.
1975    fn fail(&mut self, msg: &str) {
1976        self.fail_with(error_body(msg, "server_error"), msg);
1977    }
1978
1979    /// [`Self::fail`] with an error body other than the generic `server_error` one; `msg` is what
1980    /// the log line says.
1981    fn fail_with(&mut self, body: serde_json::Value, msg: &str) {
1982        if self.settled {
1983            return;
1984        }
1985        self.settled = true;
1986        // A failed send just means the client is already gone; the accounting still has to be
1987        // right, so the fold and the log are NOT conditional on it.
1988        let _ = self.tx.send(Ok(sse_error_event(&body)));
1989        self.stats.fold_failure();
1990        tracing::warn!(req = self.req_id, error = msg, "request failed");
1991    }
1992}
1993
1994impl Drop for DoneGuard {
1995    fn drop(&mut self) {
1996        self.fail("internal error: generation ended without a terminal frame");
1997        let _ = self.tx.send(Ok(Event::default().data("[DONE]")));
1998    }
1999}
2000
2001/// The OpenAI error envelope — `{"error": {"message": .., "type": ..}}` — that every failure this
2002/// server reports is wrapped in, whether it leaves as an HTTP body or as an SSE frame.
2003///
2004/// This is a WIRE format: clients (the OpenAI SDKs, `curl | jq .error.message`) match on the outer
2005/// key and on `type`, and two tests pin the shape. It was spelled out inline at three call sites,
2006/// two of which were character-for-character identical; the third ([`param_error`]) adds `param` and
2007/// `code` on top rather than being a different envelope. Building the common two fields here means
2008/// a renamed key cannot reach only some of the responses.
2009fn error_body(msg: &str, ty: &str) -> serde_json::Value {
2010    serde_json::json!({"error": {"message": msg, "type": ty}})
2011}
2012
2013/// A terminal SSE error frame: `data: {"error":{...}}`. Distinguishable from a normal
2014/// `chat.completion.chunk` and from `[DONE]`, so a client can tell a mid-stream failure apart from a
2015/// clean completion (audit finding 1).
2016fn sse_error_event(body: &serde_json::Value) -> Event {
2017    Event::default().data(body.to_string())
2018}
2019
2020/// Serialize a delta payload into an SSE event carrying a `chat.completion.chunk`.
2021fn sse_chunk(
2022    cid: &str,
2023    model: &str,
2024    created: i64,
2025    delta: DeltaPayload,
2026    finish_reason: Option<String>,
2027) -> Event {
2028    let chunk = ChatCompletionChunk {
2029        id: cid.to_owned(),
2030        object: "chat.completion.chunk",
2031        created,
2032        model: model.to_owned(),
2033        choices: vec![ChunkChoice {
2034            index: 0,
2035            delta,
2036            finish_reason,
2037        }],
2038        usage: None,
2039    };
2040    Event::default()
2041        .json_data(chunk)
2042        .expect("ChatCompletionChunk always serializes")
2043}
2044
2045/// The `stream_options.include_usage` chunk: the whole request's `usage`, and an empty `choices`
2046/// array, sent after the finish chunk and before `[DONE]`.
2047fn sse_usage_chunk(cid: &str, model: &str, created: i64, outcome: &ChatOutcome) -> Event {
2048    let chunk = ChatCompletionChunk {
2049        id: cid.to_owned(),
2050        object: "chat.completion.chunk",
2051        created,
2052        model: model.to_owned(),
2053        choices: Vec::new(),
2054        usage: Some(UsageInfo::from_outcome(outcome)),
2055    };
2056    Event::default()
2057        .json_data(chunk)
2058        .expect("ChatCompletionChunk always serializes")
2059}
2060
2061fn json_error(status: StatusCode, msg: String) -> Response {
2062    (status, Json(error_body(&msg, "server_error"))).into_response()
2063}
2064
2065/// An `invalid_request_error` — the request is at fault and resending it unchanged will not help.
2066/// `param` names the offending field and `code` is OpenAI's machine-readable reason, where there
2067/// is one (`null` otherwise).
2068///
2069/// Two fields on top of the shared [`error_body`], and they are deliberately absent from the
2070/// server-error responses rather than emitted as nulls there: `param` only means something when a
2071/// specific request field is at fault, and OpenAI's own 5xx bodies carry neither. `code` is
2072/// present even when null because SDKs read `error.code` on a 4xx. Appending them keeps the key
2073/// order (`message`, `type`, `param`, `code`) the responses have always had; `serde_json`'s
2074/// `preserve_order` makes that order observable on the wire.
2075fn invalid_request(
2076    status: StatusCode,
2077    param: Option<&str>,
2078    code: Option<&str>,
2079    msg: String,
2080) -> Response {
2081    (status, Json(invalid_request_body(param, code, &msg))).into_response()
2082}
2083
2084/// The body of [`invalid_request`], for the SSE error frame as well as the HTTP response.
2085fn invalid_request_body(param: Option<&str>, code: Option<&str>, msg: &str) -> serde_json::Value {
2086    let mut body = error_body(msg, "invalid_request_error");
2087    body["error"]["param"] = serde_json::json!(param);
2088    body["error"]["code"] = serde_json::json!(code);
2089    body
2090}
2091
2092/// The over-long-prompt error, identical on both paths: a `400` body, or a streamed error frame.
2093fn context_length_body(c: &ContextLengthExceeded) -> serde_json::Value {
2094    invalid_request_body(
2095        Some("messages"),
2096        Some("context_length_exceeded"),
2097        &c.message,
2098    )
2099}
2100
2101/// A body the JSON extractor refused. Malformed JSON and wrong field types are a `400` (not axum's
2102/// default `422`, which no OpenAI client expects); a body over the size limit keeps its `413` and a
2103/// missing JSON content type its `415`, because those say something a client can fix differently.
2104fn body_rejection(e: JsonRejection) -> Response {
2105    let status = match e.status() {
2106        s @ (StatusCode::PAYLOAD_TOO_LARGE | StatusCode::UNSUPPORTED_MEDIA_TYPE) => s,
2107        _ => StatusCode::BAD_REQUEST,
2108    };
2109    invalid_request(status, None, None, e.body_text())
2110}
2111
2112/// OpenAI-shaped 400 for a bad request parameter (`invalid_request_error`, with the offending
2113/// `param` named). NOT a clamp and NOT a panic — see [`GenParams::from_request`].
2114fn param_error(param: Option<&str>, msg: String) -> Response {
2115    invalid_request(StatusCode::BAD_REQUEST, param, None, msg)
2116}
2117
2118/// Process-monotonic tie-breaker so two requests in the SAME millisecond (routine under
2119/// `--parallel N`) never mint the same completion `id` — which also keeps the tool-call ids
2120/// [`tool_call_id`] derives from it distinct (audit finding 4).
2121static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
2122
2123fn make_id() -> String {
2124    let ms = SystemTime::now()
2125        .duration_since(UNIX_EPOCH)
2126        .unwrap_or_default()
2127        .as_millis();
2128    let seq = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
2129    format!("chatcmpl-{ms}-{seq}")
2130}
2131
2132/// Length of a tool-call id, and its alphabet below: the shape Mistral's chat template demands of
2133/// every replayed `tool_calls[].id` (it `raise_exception`s on anything else), which OpenAI clients
2134/// treat as an opaque string. One shape for every model keeps a replayed id valid whichever
2135/// template renders the next turn.
2136const TOOL_CALL_ID_LEN: usize = 9;
2137const TOOL_CALL_ID_ALPHABET: &[u8] =
2138    b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2139
2140/// The wire id of the `idx`-th tool call in completion `cid`: a hash of the pair, spelled in
2141/// [`TOOL_CALL_ID_ALPHABET`]. Deterministic, so the streaming and non-streaming paths agree, and
2142/// distinct across completions because `cid` is (see [`make_id`]).
2143fn tool_call_id(cid: &str, idx: usize) -> String {
2144    use std::hash::{DefaultHasher, Hash, Hasher};
2145    let mut h = DefaultHasher::new();
2146    (cid, idx).hash(&mut h);
2147    let mut n = h.finish();
2148    let base = TOOL_CALL_ID_ALPHABET.len() as u64;
2149    (0..TOOL_CALL_ID_LEN)
2150        .map(|_| {
2151            let c = TOOL_CALL_ID_ALPHABET[(n % base) as usize] as char;
2152            n /= base;
2153            c
2154        })
2155        .collect()
2156}
2157
2158/// Default ceiling for `max_tokens`/`max_completion_tokens` when `INFR_MAX_TOKENS_CAP` is unset —
2159/// generous (128k) but finite, so one request cannot pin a slot for an absurd budget.
2160const DEFAULT_MAX_TOKENS_CAP: u32 = 131_072;
2161
2162/// The configured `max_tokens` ceiling: `serve.max_tokens_cap` (`INFR_MAX_TOKENS_CAP`) if a
2163/// positive integer, else [`DEFAULT_MAX_TOKENS_CAP`]. Read per-request off the borrowed `Config`
2164/// the [`AppState`] owns (this used to be a per-request `std::env::var`).
2165///
2166/// The `> 0` guard stays HERE, at the accessor (R5): the env layer already drops a non-positive
2167/// `INFR_MAX_TOKENS_CAP`, but a config FILE can name the same field, and "must be a positive
2168/// integer, else the default" is this knob's grammar whatever layer supplied it.
2169fn max_tokens_cap(cfg: &Config) -> u32 {
2170    let cap = cfg.serve.max_tokens_cap;
2171    if cap > 0 {
2172        cap
2173    } else {
2174        DEFAULT_MAX_TOKENS_CAP
2175    }
2176}
2177
2178/// Clamp an explicit `max_tokens` to `cap`. `None` (unset) passes through untouched — the generator
2179/// keeps applying its own `INFR_MAX_NEW` default, so behaviour is unchanged for requests that don't
2180/// ask for a budget. Only an absurdly large EXPLICIT value is capped (audit finding 5).
2181fn clamp_max_tokens(requested: Option<u32>, cap: u32) -> Option<u32> {
2182    requested.map(|v| v.min(cap))
2183}
2184
2185/// The configured per-request wall-clock deadline, or `None` for "unbounded" — which is the
2186/// DEFAULT (`serve.request_timeout_secs` = 0) and today's behaviour.
2187///
2188/// `0` and unset are the same thing on purpose: the knob's whole grammar is "seconds, or 0 for no
2189/// deadline", so an operator can disarm a deadline a config file set by exporting
2190/// `INFR_REQUEST_TIMEOUT_SECS=0` — a `None`-only spelling could not express that from the
2191/// environment (see the env layer's note on why this knob is NOT `.filter(|v| v > 0)`).
2192///
2193/// Why a deadline exists at all: nothing else bounds how long one request may occupy a `--parallel`
2194/// slot. `max_tokens_cap` bounds TOKENS, and its 128k default is many hours on a slow model. Why it
2195/// is OFF by default: firing mid-generation truncates a legitimate long reply, and only the operator
2196/// knows their model's token rate.
2197fn request_timeout(cfg: &Config) -> Option<Duration> {
2198    let secs = cfg.serve.request_timeout_secs;
2199    (secs > 0).then(|| Duration::from_secs(secs))
2200}
2201
2202/// Arm a wall-clock deadline over a generation that OUTLIVES the handler — i.e. the streaming path,
2203/// where the SSE response is returned immediately and the `spawn_blocking` task keeps producing
2204/// into a channel with nobody awaiting its join.
2205///
2206/// **It sets the generator's abort latch; it does not cancel anything.** `spawn_blocking` tasks are
2207/// NOT cancellable: `tokio::time::timeout` around a `JoinHandle` only stops the caller waiting —
2208/// the blocking thread runs on, still holding its `OwnedSemaphorePermit`, so the slot the deadline
2209/// exists to reclaim is exactly the thing that is not reclaimed. Latching `cancel` instead drives
2210/// the mechanism the decode loop already polls (see [`ChatGenerator::chat`]): the generator stops at
2211/// its next token boundary, returns normally, and the permit drops on the way out.
2212///
2213/// `hit` is a SECOND flag rather than a re-read of `cancel`, because `cancel` is also latched by a
2214/// client disconnect — the finish reason must say "the budget ran out", not "the socket died". It
2215/// is stored BEFORE `cancel` so a decode loop that observes the abort and returns instantly still
2216/// finds the label set.
2217///
2218/// **Teardown.** The returned [`oneshot::Sender`](tokio::sync::oneshot::Sender) is the "generation
2219/// finished" signal: move it into the blocking task and let it DROP there. A dropped sender
2220/// resolves the receiver (with `Err`), the `select!` takes that arm, and the watchdog task ends —
2221/// so a server that has served a million requests holds zero sleeping tasks. Drop is the right
2222/// trigger rather than an explicit `send`: it also fires while UNWINDING from a panic inside the
2223/// decode closure, which an explicit send at the end of the happy path would skip, leaking one task
2224/// per panicking request. (`JoinHandle::abort` would work too, but the handler would then have to
2225/// own and remember to abort a handle across two exit paths; a value whose destructor IS the signal
2226/// cannot be forgotten.)
2227fn arm_deadline(
2228    d: Duration,
2229    cancel: Arc<AtomicBool>,
2230    hit: Arc<AtomicBool>,
2231) -> tokio::sync::oneshot::Sender<()> {
2232    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
2233    tokio::spawn(async move {
2234        tokio::select! {
2235            _ = tokio::time::sleep(d) => {
2236                hit.store(true, Ordering::Relaxed);
2237                cancel.store(true, Ordering::Relaxed);
2238                tracing::warn!(timeout_s = d.as_secs(), "request deadline hit — aborting generation");
2239            }
2240            _ = done_rx => {}
2241        }
2242    });
2243    done_tx
2244}
2245
2246/// Latch `cancel` the moment the streaming client hangs up, i.e. when the SSE receiver `tx` feeds
2247/// is dropped — not at the next delta, which may be a whole prefill away.
2248///
2249/// Same teardown shape as [`arm_deadline`]: the returned sender is the "generation finished"
2250/// signal, moved into the blocking task and dropped there (also on unwind). The watcher holds a
2251/// clone of `tx`, and the SSE stream only ends once every sender is gone, so it MUST end with the
2252/// generation or a finished stream would never close.
2253fn cancel_on_hangup(
2254    tx: &tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
2255    cancel: Arc<AtomicBool>,
2256) -> tokio::sync::oneshot::Sender<()> {
2257    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
2258    let tx = tx.clone();
2259    tokio::spawn(async move {
2260        tokio::select! {
2261            _ = tx.closed() => cancel.store(true, Ordering::Relaxed),
2262            _ = done_rx => {}
2263        }
2264    });
2265    done_tx
2266}
2267
2268/// Latches its flag when dropped — the non-streaming handler's hang-up signal (see [`non_streaming`]).
2269struct CancelOnDrop(Arc<AtomicBool>);
2270
2271impl Drop for CancelOnDrop {
2272    fn drop(&mut self) {
2273        self.0.store(true, Ordering::Relaxed);
2274    }
2275}
2276
2277/// Optional bearer-token gate. `expected` is the configured API key (`INFR_API_KEY`), or `None`
2278/// when auth is DISABLED — in which case every request is allowed (default; preserves existing
2279/// localhost usage). When a key IS configured, the request must carry
2280/// `Authorization: Bearer <key>` with a matching token (audit finding 5).
2281///
2282/// The token comparison is CONSTANT TIME ([`subtle::ConstantTimeEq`]), not `==`. `str`/`[u8]`
2283/// equality bails out at the first differing byte, so the time to answer a request grows with how
2284/// many leading bytes of the key the attacker guessed right. Against a server reachable over a
2285/// network that is a byte-at-a-time oracle: guess byte 0 (256 tries), keep the value that answers
2286/// measurably slower, move to byte 1 — the key falls in time linear in its length instead of
2287/// exponential. `ct_eq` folds `|=` over the XOR of every byte pair and only then collapses the
2288/// accumulator to a `Choice`, so the answer costs the same whether the token differs in the first
2289/// byte or the last. It is used rather than a hand-rolled loop because "no early exit" also has to
2290/// survive the optimizer, which is exactly what `subtle` is written (and volatile-fenced) to do.
2291///
2292/// LENGTH IS STILL LEAKED — `ct_eq` short-circuits when the slices differ in length, so a wrong
2293/// token of the wrong length is rejected faster than a wrong token of the right one. That is an
2294/// ACCEPTED trade, not an oversight: an attacker learns only how many bytes to send, which does
2295/// not narrow the search of the CONTENT in any useful way (a 32-byte random key still has 32 bytes
2296/// of entropy to guess), and the alternatives — hashing both sides first, or padding to a fixed
2297/// buffer — buy nothing an operator can spend. What must not leak is a per-byte signal, and that
2298/// is what the fold removes.
2299fn authorize(expected: Option<&str>, auth_header: Option<&str>) -> bool {
2300    match expected {
2301        None => true,
2302        Some(key) => auth_header
2303            .and_then(|h| {
2304                h.strip_prefix("Bearer ")
2305                    .or_else(|| h.strip_prefix("bearer "))
2306            })
2307            .map(str::trim)
2308            .is_some_and(|tok| bool::from(tok.as_bytes().ct_eq(key.as_bytes()))),
2309    }
2310}
2311
2312/// The optional bearer gate every PROTECTED route runs first: `Some(401)` when the request must be
2313/// refused, `None` when it may proceed.
2314///
2315/// Enforced ONLY when `serve.api_key` (`INFR_API_KEY`) is configured; with no key this returns
2316/// `None` for everything, so the default localhost server stays open exactly as it was.
2317///
2318/// It exists as ONE function because the gate is a policy, not a line of handler code: when
2319/// `/v1/models` was left ungated, an unauthenticated caller could still enumerate every hosted
2320/// model id off a server whose operator had set a key. A second handler spelling the check inline
2321/// is how that happens again, and a third would drift on the message or the status. The 401 body is
2322/// the shared [`error_body`] envelope, so it deserializes the same as every other failure this
2323/// server reports.
2324///
2325/// `/health` deliberately does NOT call this — see [`health_handler`].
2326fn auth_gate(cfg: &Config, headers: &HeaderMap) -> Option<Response> {
2327    let key = configured_api_key(cfg)?;
2328    let auth = headers.get("authorization").and_then(|v| v.to_str().ok());
2329    // OpenAI's own 401: the request is at fault (`invalid_request_error`), not the server.
2330    (!authorize(Some(key), auth)).then(|| {
2331        invalid_request(
2332            StatusCode::UNAUTHORIZED,
2333            None,
2334            Some("invalid_api_key"),
2335            "missing or invalid Authorization bearer token".into(),
2336        )
2337    })
2338}
2339
2340/// The configured API key, or `None` when `serve.api_key` (`INFR_API_KEY`) is unset OR EMPTY —
2341/// auth disabled.
2342///
2343/// The empty-string filter is load-bearing and is NOT the `is_ok()` presence grammar every other
2344/// knob uses: `INFR_API_KEY=` means "no auth", not "auth with the empty key". The env
2345/// layer already maps an empty value to `Some(None)`; the filter is kept here as well so a config
2346/// FILE saying `api_key = ""` means the same thing (this used to read the `INFR_API_KEY`
2347/// variable from the process environment and apply the same filter).
2348fn configured_api_key(cfg: &Config) -> Option<&str> {
2349    cfg.serve
2350        .api_key
2351        .as_deref()
2352        .filter(|k: &&str| !k.is_empty())
2353}
2354
2355fn unix_ts() -> i64 {
2356    SystemTime::now()
2357        .duration_since(UNIX_EPOCH)
2358        .unwrap_or_default()
2359        .as_secs() as i64
2360}
2361
2362/// Flatten a DTO `content` field (string OR content-part array) to a plain `String`.
2363///
2364/// Mirrors the Python shim's `normalize_messages`: only `"text"` parts are kept.
2365pub fn flatten_content(v: &Option<serde_json::Value>) -> String {
2366    match v {
2367        None | Some(serde_json::Value::Null) => String::new(),
2368        Some(serde_json::Value::String(s)) => s.clone(),
2369        Some(serde_json::Value::Array(parts)) => parts
2370            .iter()
2371            .filter_map(|p| {
2372                if p.get("type")?.as_str()? == "text" {
2373                    p.get("text")?.as_str().map(str::to_owned)
2374                } else {
2375                    None
2376                }
2377            })
2378            .collect::<Vec<_>>()
2379            .join(""),
2380        Some(other) => other.to_string(),
2381    }
2382}
2383
2384fn dto_to_engine(dto: &ChatMessageDto) -> ChatMessage {
2385    ChatMessage {
2386        role: dto.role.clone(),
2387        content: flatten_content(&dto.content),
2388        tool_calls: dto.tool_calls.as_ref().and_then(parse_oai_tool_calls),
2389        tool_call_id: dto.tool_call_id.clone(),
2390        name: dto.name.clone(),
2391    }
2392}
2393
2394/// Convert an inbound OpenAI `tool_calls` array (`[{function:{name, arguments}}]`, where `arguments`
2395/// is a JSON STRING) into engine [`ToolCall`]s with `arguments` parsed to a `Value`. Returns `None`
2396/// if the field isn't a non-empty array of valid calls.
2397fn parse_oai_tool_calls(v: &serde_json::Value) -> Option<Vec<ToolCall>> {
2398    let arr = v.as_array()?;
2399    let calls: Vec<ToolCall> = arr
2400        .iter()
2401        .filter_map(|c| {
2402            let f = c.get("function")?;
2403            let name = f.get("name")?.as_str()?.to_owned();
2404            let arguments = match f.get("arguments") {
2405                Some(serde_json::Value::String(s)) => {
2406                    serde_json::from_str(s).unwrap_or(serde_json::Value::String(s.clone()))
2407                }
2408                Some(other) => other.clone(),
2409                None => serde_json::Value::Object(serde_json::Map::new()),
2410            };
2411            let id = c.get("id").and_then(|v| v.as_str()).map(str::to_owned);
2412            Some(ToolCall {
2413                name,
2414                arguments,
2415                id,
2416            })
2417        })
2418        .collect();
2419    (!calls.is_empty()).then_some(calls)
2420}
2421
2422// ---------------------------------------------------------------------------
2423// Tests
2424// ---------------------------------------------------------------------------
2425
2426#[cfg(test)]
2427mod tests {
2428    use super::*;
2429    use axum::{body::Body, http::Request};
2430    use http_body_util::BodyExt;
2431    use tower::ServiceExt;
2432
2433    /// Router backed by a headless state — no Engine, so /health and /v1/models work
2434    /// but /v1/chat/completions would return 500.  That's fine: we never call it here.
2435    fn test_router() -> Router {
2436        build_router(AppState::headless(
2437            "test-model",
2438            Arc::new(Config::default()),
2439        ))
2440    }
2441
2442    // --- HTTP endpoint tests (no Engine required) ---------------------------
2443
2444    #[tokio::test]
2445    async fn test_health_returns_200() {
2446        let resp = test_router()
2447            .oneshot(
2448                Request::builder()
2449                    .uri("/health")
2450                    .body(Body::empty())
2451                    .unwrap(),
2452            )
2453            .await
2454            .unwrap();
2455        assert_eq!(resp.status(), StatusCode::OK);
2456    }
2457
2458    #[tokio::test]
2459    async fn test_models_returns_200_with_expected_shape() {
2460        let resp = test_router()
2461            .oneshot(
2462                Request::builder()
2463                    .uri("/v1/models")
2464                    .body(Body::empty())
2465                    .unwrap(),
2466            )
2467            .await
2468            .unwrap();
2469        assert_eq!(resp.status(), StatusCode::OK);
2470
2471        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
2472        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2473
2474        assert_eq!(json["object"], "list");
2475        let card = &json["data"][0];
2476        assert_eq!(card["id"], "test-model");
2477        assert_eq!(card["object"], "model");
2478        assert_eq!(card["owned_by"], "local");
2479    }
2480
2481    /// What a test generator with nothing to say about its device reports.
2482    fn cpu_status() -> GeneratorStatus {
2483        GeneratorStatus {
2484            backend: "cpu",
2485            device: None,
2486            ctx_per_slot: None,
2487            memory: None,
2488        }
2489    }
2490
2491    /// A stub generator that streams back exactly one content delta naming the model it belongs to,
2492    /// so a routing test can prove WHICH generator answered.
2493    pub(crate) struct EchoGen(pub(crate) &'static str);
2494    impl ChatGenerator for EchoGen {
2495        fn status(&self) -> GeneratorStatus {
2496            GeneratorStatus {
2497                backend: "vulkan",
2498                device: Some(format!("dev-{}", self.0)),
2499                ctx_per_slot: Some(4096),
2500                memory: Some(DeviceMemory {
2501                    total_bytes: 8 << 30,
2502                    available_bytes: 6 << 30,
2503                    live: true,
2504                    unified: false,
2505                }),
2506            }
2507        }
2508
2509        fn chat(
2510            &self,
2511            _messages: &[ChatMessage],
2512            _tools: Option<&serde_json::Value>,
2513            _tool_choice: Option<&str>,
2514            _params: &GenParams,
2515            _cancel: &Arc<AtomicBool>,
2516            on_delta: &mut dyn FnMut(Delta),
2517        ) -> anyhow::Result<ChatOutcome> {
2518            on_delta(Delta::Content(format!("from:{}", self.0)));
2519            Ok(ChatOutcome {
2520                finish: Finish::Stop,
2521                prompt_tokens: 3,
2522                completion_tokens: 2,
2523                cached_tokens: 0,
2524            })
2525        }
2526    }
2527
2528    fn multi_router() -> Router {
2529        let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
2530        let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
2531        build_router(AppState::multi(
2532            vec![("alpha".into(), a, 2), ("beta".into(), b, 2)],
2533            Arc::new(Config::default()),
2534        ))
2535    }
2536
2537    #[tokio::test]
2538    async fn multi_models_are_all_listed() {
2539        let resp = multi_router()
2540            .oneshot(
2541                Request::builder()
2542                    .uri("/v1/models")
2543                    .body(Body::empty())
2544                    .unwrap(),
2545            )
2546            .await
2547            .unwrap();
2548        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
2549        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2550        let ids: Vec<&str> = json["data"]
2551            .as_array()
2552            .unwrap()
2553            .iter()
2554            .map(|c| c["id"].as_str().unwrap())
2555            .collect();
2556        assert_eq!(ids, vec!["alpha", "beta"]);
2557    }
2558
2559    /// A request naming `beta` must be answered by beta's generator; an unknown name falls to the
2560    /// default (first-listed `alpha`). This is the whole multi-model routing contract.
2561    async fn chat_model_field(router: Router, requested: &str) -> (String, String) {
2562        let body =
2563            format!(r#"{{"model":"{requested}","messages":[{{"role":"user","content":"hi"}}]}}"#);
2564        let resp = router
2565            .oneshot(
2566                Request::builder()
2567                    .method("POST")
2568                    .uri("/v1/chat/completions")
2569                    .header("content-type", "application/json")
2570                    .body(Body::from(body))
2571                    .unwrap(),
2572            )
2573            .await
2574            .unwrap();
2575        assert_eq!(resp.status(), StatusCode::OK);
2576        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
2577        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2578        (
2579            json["model"].as_str().unwrap().to_string(),
2580            json["choices"][0]["message"]["content"]
2581                .as_str()
2582                .unwrap()
2583                .to_string(),
2584        )
2585    }
2586
2587    #[tokio::test]
2588    async fn request_routes_to_named_model() {
2589        let (model, content) = chat_model_field(multi_router(), "beta").await;
2590        assert_eq!(model, "beta");
2591        assert_eq!(content, "from:beta");
2592    }
2593
2594    #[tokio::test]
2595    async fn unknown_model_falls_to_default() {
2596        let (model, content) = chat_model_field(multi_router(), "does-not-exist").await;
2597        assert_eq!(model, "alpha");
2598        assert_eq!(content, "from:alpha");
2599    }
2600
2601    // --- ChatRequest serde round-trip tests --------------------------------
2602
2603    #[test]
2604    fn chat_request_string_content_deserializes() {
2605        let raw = r#"{"model":"m","messages":[{"role":"user","content":"hello"}]}"#;
2606        let req: ChatRequest = serde_json::from_str(raw).unwrap();
2607        assert_eq!(req.messages[0].role, "user");
2608        assert_eq!(flatten_content(&req.messages[0].content), "hello");
2609        assert!(!req.stream);
2610        assert!(req.tools.is_none());
2611        assert!(req.max_tokens.is_none());
2612    }
2613
2614    #[test]
2615    fn chat_request_array_content_deserializes_and_flattens() {
2616        let raw = r#"{
2617            "model": "m",
2618            "messages": [{
2619                "role": "user",
2620                "content": [
2621                    {"type":"text","text":"hello"},
2622                    {"type":"image_url","image_url":{"url":"data:..."}},
2623                    {"type":"text","text":" world"}
2624                ]
2625            }]
2626        }"#;
2627        let req: ChatRequest = serde_json::from_str(raw).unwrap();
2628        // Only text parts are concatenated; image_url is discarded.
2629        assert_eq!(flatten_content(&req.messages[0].content), "hello world");
2630    }
2631
2632    #[test]
2633    fn chat_request_stream_flag() {
2634        let raw = r#"{"model":"m","messages":[],"stream":true}"#;
2635        let req: ChatRequest = serde_json::from_str(raw).unwrap();
2636        assert!(req.stream);
2637    }
2638
2639    #[test]
2640    fn chat_request_with_tools_and_max_tokens() {
2641        let raw = r#"{
2642            "model":"m","messages":[],
2643            "tools":[{"type":"function","function":{"name":"bash","description":"run bash"}}],
2644            "max_tokens":512
2645        }"#;
2646        let req: ChatRequest = serde_json::from_str(raw).unwrap();
2647        // The whole array arrives as sent: it is handed to the chat template verbatim, so a field
2648        // lost or reshaped here is a tool the model is never told about.
2649        assert_eq!(
2650            req.tools,
2651            Some(serde_json::json!([
2652                {"type": "function", "function": {"name": "bash", "description": "run bash"}}
2653            ]))
2654        );
2655        assert_eq!(req.max_tokens, Some(512));
2656        assert_eq!(req.max_completion_tokens, None);
2657        assert_eq!(req.tool_choice, None);
2658        assert!(req.messages.is_empty());
2659    }
2660
2661    #[test]
2662    fn chat_message_dto_with_tool_call_id_and_name() {
2663        let raw = r#"{"role":"tool","content":"result","tool_call_id":"tc_1","name":"bash"}"#;
2664        let msg: ChatMessageDto = serde_json::from_str(raw).unwrap();
2665        assert_eq!(msg.tool_call_id.as_deref(), Some("tc_1"));
2666        assert_eq!(msg.name.as_deref(), Some("bash"));
2667    }
2668
2669    /// A replayed assistant `tool_calls[].id` survives into the engine message, so the chat
2670    /// template can pair it with the `tool` result's `tool_call_id`.
2671    #[test]
2672    fn replayed_tool_call_keeps_its_id() {
2673        let raw = r#"{"role":"assistant","content":null,"tool_calls":[
2674            {"id":"a1B2c3D4e","type":"function",
2675             "function":{"name":"bash","arguments":"{\"cmd\":\"ls\"}"}},
2676            {"type":"function","function":{"name":"noid","arguments":"{}"}}]}"#;
2677        let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(raw).unwrap());
2678        let calls = msg.tool_calls.expect("two calls parse");
2679        assert_eq!(calls[0].id.as_deref(), Some("a1B2c3D4e"));
2680        assert_eq!(calls[0].arguments, serde_json::json!({"cmd": "ls"}));
2681        assert_eq!(calls[1].id, None);
2682    }
2683
2684    /// The ids `serve` hands out are ones every supported template accepts when the client replays
2685    /// them: Mistral's requires exactly nine alphanumerics. They are distinct per call and per
2686    /// completion, and the same (cid, index) always yields the same id.
2687    #[test]
2688    fn minted_tool_call_ids_are_template_safe_and_distinct() {
2689        let mut seen = std::collections::HashSet::new();
2690        for _ in 0..1000 {
2691            let cid = make_id();
2692            for idx in 0..4 {
2693                let id = tool_call_id(&cid, idx);
2694                assert_eq!(id.len(), TOOL_CALL_ID_LEN, "{id}");
2695                assert!(id.bytes().all(|b| b.is_ascii_alphanumeric()), "{id}");
2696                assert!(seen.insert(id.clone()), "duplicate tool-call id {id}");
2697                assert_eq!(id, tool_call_id(&cid, idx));
2698            }
2699        }
2700    }
2701
2702    // --- Non-streaming response serialization tests ------------------------
2703
2704    #[test]
2705    fn chat_completion_response_stop_serializes() {
2706        let resp = ChatCompletionResponse {
2707            id: "chatcmpl-test".into(),
2708            object: "chat.completion",
2709            created: 1000,
2710            model: "test-model".into(),
2711            choices: vec![CompletionChoice {
2712                index: 0,
2713                message: AssistantMessage {
2714                    role: "assistant",
2715                    content: Some("hello".into()),
2716                    reasoning_content: None,
2717                    tool_calls: None,
2718                },
2719                finish_reason: "stop".into(),
2720            }],
2721            usage: UsageInfo {
2722                prompt_tokens: 10,
2723                completion_tokens: 5,
2724                total_tokens: 15,
2725                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
2726            },
2727        };
2728        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
2729        assert_eq!(v["object"], "chat.completion");
2730        assert_eq!(v["choices"][0]["finish_reason"], "stop");
2731        assert_eq!(v["choices"][0]["message"]["role"], "assistant");
2732        assert_eq!(v["choices"][0]["message"]["content"], "hello");
2733        // skip_serializing_if = None → field absent in JSON → serde_json gives Null on access
2734        assert!(v["choices"][0]["message"]["reasoning_content"].is_null());
2735        assert!(v["choices"][0]["message"]["tool_calls"].is_null());
2736    }
2737
2738    #[test]
2739    fn chat_completion_response_with_reasoning_content() {
2740        let resp = ChatCompletionResponse {
2741            id: "id".into(),
2742            object: "chat.completion",
2743            created: 0,
2744            model: "m".into(),
2745            choices: vec![CompletionChoice {
2746                index: 0,
2747                message: AssistantMessage {
2748                    role: "assistant",
2749                    content: Some("answer".into()),
2750                    reasoning_content: Some("I thought about it".into()),
2751                    tool_calls: None,
2752                },
2753                finish_reason: "stop".into(),
2754            }],
2755            usage: UsageInfo {
2756                prompt_tokens: 0,
2757                completion_tokens: 0,
2758                total_tokens: 0,
2759                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
2760            },
2761        };
2762        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
2763        assert_eq!(
2764            v["choices"][0]["message"]["reasoning_content"],
2765            "I thought about it"
2766        );
2767        assert_eq!(v["choices"][0]["message"]["content"], "answer");
2768    }
2769
2770    #[test]
2771    fn chat_completion_response_tool_calls_finish_reason() {
2772        let resp = ChatCompletionResponse {
2773            id: "id".into(),
2774            object: "chat.completion",
2775            created: 0,
2776            model: "m".into(),
2777            choices: vec![CompletionChoice {
2778                index: 0,
2779                message: AssistantMessage {
2780                    role: "assistant",
2781                    content: None,
2782                    reasoning_content: None,
2783                    tool_calls: Some(vec![OAIToolCall {
2784                        index: 0,
2785                        id: "call_0".into(),
2786                        kind: "function",
2787                        function: OAIFunction {
2788                            name: "bash".into(),
2789                            arguments: r#"{"command":"ls"}"#.into(),
2790                        },
2791                    }]),
2792                },
2793                finish_reason: "tool_calls".into(),
2794            }],
2795            usage: UsageInfo {
2796                prompt_tokens: 0,
2797                completion_tokens: 0,
2798                total_tokens: 0,
2799                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
2800            },
2801        };
2802        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
2803        assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");
2804        let tc = &v["choices"][0]["message"]["tool_calls"][0];
2805        assert_eq!(tc["type"], "function");
2806        assert_eq!(tc["function"]["name"], "bash");
2807        assert_eq!(tc["function"]["arguments"], r#"{"command":"ls"}"#);
2808        assert_eq!(tc["index"], 0);
2809        // content: None serializes as null
2810        assert!(v["choices"][0]["message"]["content"].is_null());
2811    }
2812
2813    // --- Streaming chunk serialization tests --------------------------------
2814
2815    #[test]
2816    fn streaming_chunk_role_delta() {
2817        let chunk = ChatCompletionChunk {
2818            id: "id".into(),
2819            object: "chat.completion.chunk",
2820            created: 0,
2821            model: "m".into(),
2822            choices: vec![ChunkChoice {
2823                index: 0,
2824                delta: DeltaPayload {
2825                    role: Some("assistant".into()),
2826                    ..Default::default()
2827                },
2828                finish_reason: None,
2829            }],
2830            usage: None,
2831        };
2832        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
2833        assert_eq!(v["object"], "chat.completion.chunk");
2834        assert_eq!(v["choices"][0]["delta"]["role"], "assistant");
2835        // Other delta fields absent
2836        assert!(v["choices"][0]["delta"]["content"].is_null());
2837        assert!(v["choices"][0]["delta"]["reasoning_content"].is_null());
2838        assert!(v["choices"][0]["delta"]["tool_calls"].is_null());
2839        assert!(v["choices"][0]["finish_reason"].is_null());
2840    }
2841
2842    #[test]
2843    fn streaming_chunk_content_delta() {
2844        let chunk = ChatCompletionChunk {
2845            id: "id".into(),
2846            object: "chat.completion.chunk",
2847            created: 0,
2848            model: "m".into(),
2849            choices: vec![ChunkChoice {
2850                index: 0,
2851                delta: DeltaPayload {
2852                    content: Some("hello".into()),
2853                    ..Default::default()
2854                },
2855                finish_reason: None,
2856            }],
2857            usage: None,
2858        };
2859        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
2860        assert_eq!(v["choices"][0]["delta"]["content"], "hello");
2861        assert!(v["choices"][0]["delta"]["role"].is_null());
2862    }
2863
2864    #[test]
2865    fn streaming_chunk_reasoning_content_delta() {
2866        let chunk = ChatCompletionChunk {
2867            id: "id".into(),
2868            object: "chat.completion.chunk",
2869            created: 0,
2870            model: "m".into(),
2871            choices: vec![ChunkChoice {
2872                index: 0,
2873                delta: DeltaPayload {
2874                    reasoning_content: Some("thinking...".into()),
2875                    ..Default::default()
2876                },
2877                finish_reason: None,
2878            }],
2879            usage: None,
2880        };
2881        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
2882        assert_eq!(v["choices"][0]["delta"]["reasoning_content"], "thinking...");
2883        assert!(v["choices"][0]["delta"]["content"].is_null());
2884    }
2885
2886    #[test]
2887    fn streaming_chunk_tool_call_delta() {
2888        let chunk = ChatCompletionChunk {
2889            id: "id".into(),
2890            object: "chat.completion.chunk",
2891            created: 0,
2892            model: "m".into(),
2893            choices: vec![ChunkChoice {
2894                index: 0,
2895                delta: DeltaPayload {
2896                    tool_calls: Some(vec![OAIToolCall {
2897                        index: 0,
2898                        id: "call_0".into(),
2899                        kind: "function",
2900                        function: OAIFunction {
2901                            name: "bash".into(),
2902                            arguments: r#"{"cmd":"ls"}"#.into(),
2903                        },
2904                    }]),
2905                    ..Default::default()
2906                },
2907                finish_reason: None,
2908            }],
2909            usage: None,
2910        };
2911        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
2912        let tc = &v["choices"][0]["delta"]["tool_calls"][0];
2913        assert_eq!(tc["index"], 0);
2914        assert_eq!(tc["type"], "function");
2915        assert_eq!(tc["function"]["name"], "bash");
2916    }
2917
2918    #[test]
2919    fn streaming_chunk_finish_reason() {
2920        let chunk = ChatCompletionChunk {
2921            id: "id".into(),
2922            object: "chat.completion.chunk",
2923            created: 0,
2924            model: "m".into(),
2925            choices: vec![ChunkChoice {
2926                index: 0,
2927                delta: DeltaPayload::default(), // empty delta {}
2928                finish_reason: Some("stop".into()),
2929            }],
2930            usage: None,
2931        };
2932        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
2933        assert_eq!(v["choices"][0]["finish_reason"], "stop");
2934        // Empty delta: all fields None → absent in JSON
2935        assert!(v["choices"][0]["delta"]["content"].is_null());
2936        assert!(v["choices"][0]["delta"]["role"].is_null());
2937    }
2938
2939    // --- /v1/models serialization test ------------------------------------
2940
2941    #[test]
2942    fn models_response_serializes() {
2943        let resp = ModelsResponse {
2944            object: "list",
2945            data: vec![ModelCard {
2946                id: "my-model".into(),
2947                object: "model",
2948                owned_by: "local",
2949            }],
2950        };
2951        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
2952        assert_eq!(v["object"], "list");
2953        assert_eq!(v["data"][0]["id"], "my-model");
2954        assert_eq!(v["data"][0]["object"], "model");
2955        assert_eq!(v["data"][0]["owned_by"], "local");
2956    }
2957
2958    // --- sampling param plumbing -------------------------------------------
2959
2960    fn req(raw: &str) -> ChatRequest {
2961        serde_json::from_str(raw).unwrap()
2962    }
2963
2964    #[test]
2965    fn absent_sampling_fields_stay_none() {
2966        // The whole point of Option-everything: a request that says nothing must not override the
2967        // process defaults (INFR_TEMP/TOP_K/TOP_P), i.e. today's behavior is preserved exactly.
2968        let p = GenParams::from_request(&req(
2969            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
2970        ))
2971        .unwrap();
2972        assert_eq!(p, GenParams::default());
2973    }
2974
2975    #[test]
2976    fn sampling_fields_parse() {
2977        let p = GenParams::from_request(&req(
2978            r#"{"model":"m","messages":[],"temperature":0.0,"top_p":0.9,"top_k":40,"seed":42,
2979                "presence_penalty":0.5,"frequency_penalty":-0.25,"repeat_penalty":1.1,
2980                "stop":["\n\n","END"]}"#,
2981        ))
2982        .unwrap();
2983        assert_eq!(p.temperature, Some(0.0));
2984        assert_eq!(p.top_p, Some(0.9));
2985        assert_eq!(p.top_k, Some(40));
2986        assert_eq!(p.seed, Some(42));
2987        assert_eq!(p.presence_penalty, Some(0.5));
2988        assert_eq!(p.frequency_penalty, Some(-0.25));
2989        assert_eq!(p.repeat_penalty, Some(1.1));
2990        assert_eq!(p.stop, vec!["\n\n".to_string(), "END".to_string()]);
2991    }
2992
2993    #[test]
2994    fn unknown_fields_are_ignored_not_rejected() {
2995        let p = GenParams::from_request(&req(
2996            r#"{"model":"m","messages":[],"n":1,"user":"bob","logit_bias":{},"logprobs":true}"#,
2997        ))
2998        .unwrap();
2999        assert_eq!(p, GenParams::default());
3000    }
3001
3002    #[test]
3003    fn max_completion_tokens_is_preferred_alias() {
3004        let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"max_tokens":10}"#))
3005            .unwrap();
3006        assert_eq!(p.max_tokens, Some(10));
3007        let p = GenParams::from_request(&req(
3008            r#"{"model":"m","messages":[],"max_completion_tokens":20}"#,
3009        ))
3010        .unwrap();
3011        assert_eq!(p.max_tokens, Some(20));
3012        // Both present: the new name wins.
3013        let p = GenParams::from_request(&req(
3014            r#"{"model":"m","messages":[],"max_tokens":10,"max_completion_tokens":20}"#,
3015        ))
3016        .unwrap();
3017        assert_eq!(p.max_tokens, Some(20));
3018    }
3019
3020    #[test]
3021    fn stop_accepts_a_bare_string() {
3022        let p =
3023            GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":"\n"}"#)).unwrap();
3024        assert_eq!(p.stop, vec!["\n".to_string()]);
3025    }
3026
3027    #[test]
3028    fn empty_stop_strings_are_dropped() {
3029        // An empty stop would match at position 0 of every step — kill it at the door.
3030        let p =
3031            GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":["",""]}"#)).unwrap();
3032        assert!(p.stop.is_empty());
3033    }
3034
3035    #[test]
3036    fn invalid_values_are_param_errors_not_clamps() {
3037        for (raw, param) in [
3038            (
3039                r#"{"model":"m","messages":[],"temperature":-1}"#,
3040                "temperature",
3041            ),
3042            (
3043                r#"{"model":"m","messages":[],"temperature":3}"#,
3044                "temperature",
3045            ),
3046            (r#"{"model":"m","messages":[],"top_p":5}"#, "top_p"),
3047            (r#"{"model":"m","messages":[],"top_k":-2}"#, "top_k"),
3048            (
3049                r#"{"model":"m","messages":[],"presence_penalty":-3}"#,
3050                "presence_penalty",
3051            ),
3052            (
3053                r#"{"model":"m","messages":[],"frequency_penalty":9}"#,
3054                "frequency_penalty",
3055            ),
3056            (
3057                r#"{"model":"m","messages":[],"repeat_penalty":0}"#,
3058                "repeat_penalty",
3059            ),
3060            (r#"{"model":"m","messages":[],"stop":[1,2]}"#, "stop"),
3061            (
3062                r#"{"model":"m","messages":[],"stop":["a","b","c","d","e"]}"#,
3063                "stop",
3064            ),
3065        ] {
3066            let e = GenParams::from_request(&req(raw)).unwrap_err();
3067            assert_eq!(e.param, param, "{raw}");
3068        }
3069    }
3070
3071    #[tokio::test]
3072    async fn bad_temperature_returns_openai_shaped_400() {
3073        let resp = test_router()
3074            .oneshot(
3075                Request::builder()
3076                    .method("POST")
3077                    .uri("/v1/chat/completions")
3078                    .header("content-type", "application/json")
3079                    .body(Body::from(
3080                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":-1}"#,
3081                    ))
3082                    .unwrap(),
3083            )
3084            .await
3085            .unwrap();
3086        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
3087        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3088        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3089        assert_eq!(v["error"]["type"], "invalid_request_error");
3090        assert_eq!(v["error"]["param"], "temperature");
3091    }
3092
3093    // --- StopMatcher: the token-boundary case -------------------------------
3094
3095    /// Drive a matcher over a token sequence, returning (emitted text, hit).
3096    fn run_stops(stops: &[&str], pieces: &[&str]) -> (String, bool) {
3097        let mut m = StopMatcher::new(stops.iter().map(|s| s.to_string()).collect());
3098        let mut out = String::new();
3099        for p in pieces {
3100            out.push_str(&m.push(p));
3101            if m.hit() {
3102                break;
3103            }
3104        }
3105        if !m.hit() {
3106            out.push_str(&m.flush());
3107        }
3108        (out, m.hit())
3109    }
3110
3111    #[test]
3112    fn stop_within_one_token_fires_and_is_excluded() {
3113        let (out, hit) = run_stops(&["END"], &["hello ", "END", " more"]);
3114        assert!(hit);
3115        assert_eq!(out, "hello ");
3116    }
3117
3118    #[test]
3119    fn stop_split_across_two_tokens_still_fires() {
3120        // THE boundary case: "END" arrives as "E" + "ND". It must fire, and the partial "E" must
3121        // NEVER have been emitted.
3122        let (out, hit) = run_stops(&["END"], &["hello ", "E", "ND", " more"]);
3123        assert!(hit, "a stop split across tokens must fire");
3124        assert_eq!(out, "hello ", "no partial stop prefix may leak");
3125    }
3126
3127    #[test]
3128    fn stop_split_across_three_tokens_still_fires() {
3129        let (out, hit) = run_stops(&["<|done|>"], &["a", "<|", "do", "ne", "|>", "b"]);
3130        assert!(hit);
3131        assert_eq!(out, "a");
3132    }
3133
3134    #[test]
3135    fn double_newline_stop_split_across_tokens() {
3136        let (out, hit) = run_stops(&["\n\n"], &["line", "\n", "\n", "next"]);
3137        assert!(hit);
3138        assert_eq!(out, "line");
3139    }
3140
3141    #[test]
3142    fn stop_prefix_that_does_not_complete_is_eventually_emitted() {
3143        // "E" looked like the start of "END" but turned out to be "Every" — it must still be
3144        // delivered, exactly once, in order.
3145        let (out, hit) = run_stops(&["END"], &["E", "very", " day"]);
3146        assert!(!hit);
3147        assert_eq!(out, "Every day");
3148    }
3149
3150    #[test]
3151    fn held_prefix_is_flushed_at_end_of_generation() {
3152        // Generation ends while the matcher still holds a partial prefix -> flush must emit it.
3153        let (out, hit) = run_stops(&["END"], &["done E"]);
3154        assert!(!hit);
3155        assert_eq!(out, "done E");
3156    }
3157
3158    #[test]
3159    fn multiple_stops_take_the_earliest_match() {
3160        let (out, hit) = run_stops(&["World", "lo"], &["hel", "lo World"]);
3161        assert!(hit);
3162        assert_eq!(out, "hel");
3163    }
3164
3165    #[test]
3166    fn no_stops_is_a_passthrough() {
3167        let (out, hit) = run_stops(&[], &["a", "b", "c"]);
3168        assert!(!hit);
3169        assert_eq!(out, "abc");
3170        assert!(!StopMatcher::new(vec![]).is_active());
3171    }
3172
3173    #[test]
3174    fn multibyte_stop_split_mid_codepoint_is_safe() {
3175        // Pieces are always whole UTF-8, but a stop's own bytes may straddle them: "→END" arriving
3176        // as "→" + "END". Must fire without panicking on a char boundary.
3177        let (out, hit) = run_stops(&["→END"], &["x", "→", "END", "y"]);
3178        assert!(hit);
3179        assert_eq!(out, "x");
3180    }
3181
3182    #[test]
3183    fn nothing_is_emitted_after_a_hit() {
3184        let mut m = StopMatcher::new(vec!["END".into()]);
3185        assert_eq!(m.push("aEND"), "a");
3186        assert!(m.hit());
3187        assert_eq!(m.push("more"), "");
3188        assert_eq!(m.flush(), "");
3189    }
3190
3191    // --- finish_reason ------------------------------------------------------
3192
3193    #[test]
3194    fn finish_reason_strings() {
3195        assert_eq!(Finish::Stop.as_str(), "stop");
3196        assert_eq!(Finish::Length.as_str(), "length");
3197        assert_eq!(Finish::ToolCalls.as_str(), "tool_calls");
3198    }
3199
3200    // --- flatten_content unit tests ----------------------------------------
3201
3202    #[test]
3203    fn flatten_content_string_value() {
3204        let v = Some(serde_json::Value::String("hello world".into()));
3205        assert_eq!(flatten_content(&v), "hello world");
3206    }
3207
3208    #[test]
3209    fn flatten_content_array_skips_non_text_parts() {
3210        let v = Some(serde_json::json!([
3211            {"type": "text",      "text": "hello"},
3212            {"type": "image_url", "image_url": {"url": "http://x"}},
3213            {"type": "text",      "text": " world"}
3214        ]));
3215        assert_eq!(flatten_content(&v), "hello world");
3216    }
3217
3218    #[test]
3219    fn flatten_content_none_gives_empty_string() {
3220        assert_eq!(flatten_content(&None), "");
3221    }
3222
3223    #[test]
3224    fn flatten_content_null_json_gives_empty_string() {
3225        // An assistant tool-call message legally has `content: null` — it must flatten to "" (not the
3226        // literal "null", which would inject a stray word into the prompt).
3227        assert_eq!(flatten_content(&Some(serde_json::Value::Null)), "");
3228    }
3229
3230    /// CHARACTERIZATION TEST — pins current behaviour, does not ask for a change.
3231    ///
3232    /// OpenAI's schema says `content` is a string or an array of content parts. A number, a
3233    /// bool or an object is a client bug. `flatten_content`'s fallback arm renders such a value
3234    /// with `Value::to_string()` (its JSON form) and feeds that to the prompt rather than
3235    /// erroring or dropping it. That leniency is DELIBERATE: a chat request that is merely
3236    /// sloppily typed still produces a sensible completion instead of a 400, and the rendered
3237    /// form is at least visible to the user in the echoed prompt rather than silently vanishing.
3238    ///
3239    /// It is pinned here because nothing else pins it: the arm is a one-liner a future refactor
3240    /// could plausibly "tidy" into `String::new()` or a rejection, silently changing what every
3241    /// such request produces. If this test fails, the change was intentional or it was not —
3242    /// decide, don't just re-bless.
3243    ///
3244    /// Note the exact rendering: `Value::to_string` is compact JSON, so a string INSIDE an
3245    /// object keeps its quotes, and `null` never reaches this arm (it is handled above).
3246    #[test]
3247    fn flatten_content_non_string_renders_json_leniently() {
3248        use serde_json::json;
3249        assert_eq!(flatten_content(&Some(json!(42))), "42");
3250        assert_eq!(flatten_content(&Some(json!(-1.5))), "-1.5");
3251        assert_eq!(flatten_content(&Some(json!(true))), "true");
3252        assert_eq!(flatten_content(&Some(json!(false))), "false");
3253        assert_eq!(flatten_content(&Some(json!({"a": 1}))), r#"{"a":1}"#);
3254        assert_eq!(
3255            flatten_content(&Some(json!({"a": "b", "c": [1, 2]}))),
3256            r#"{"a":"b","c":[1,2]}"#
3257        );
3258    }
3259
3260    // --- make_id uniqueness (audit finding 4) ------------------------------
3261
3262    #[test]
3263    fn make_id_is_unique_across_rapid_calls() {
3264        // Two completions minted in the same millisecond (routine under --parallel N) must NOT
3265        // collide — the monotonic suffix guarantees it even when the ms component is identical.
3266        let n = 10_000;
3267        let ids: std::collections::HashSet<String> = (0..n).map(|_| make_id()).collect();
3268        assert_eq!(ids.len(), n, "make_id produced a collision");
3269    }
3270
3271    // --- usage totals (audit finding 3) ------------------------------------
3272
3273    #[test]
3274    fn usage_total_is_prompt_plus_completion() {
3275        // The real fix: total == prompt + completion, from real counts, not content.len()/4.
3276        let outcome = ChatOutcome {
3277            finish: Finish::Stop,
3278            prompt_tokens: 17,
3279            completion_tokens: 5,
3280            cached_tokens: 0,
3281        };
3282        let usage = UsageInfo::from_outcome(&outcome);
3283        assert_eq!(usage.total_tokens, 22);
3284        assert_eq!(
3285            usage.total_tokens,
3286            usage.prompt_tokens + usage.completion_tokens
3287        );
3288    }
3289
3290    /// End-to-end: the non-streaming handler must surface the generator's REAL counts (EchoGen
3291    /// reports 3 prompt + 2 completion), not a byte-length estimate.
3292    #[tokio::test]
3293    async fn non_streaming_usage_comes_from_generator() {
3294        let resp = multi_router()
3295            .oneshot(
3296                Request::builder()
3297                    .method("POST")
3298                    .uri("/v1/chat/completions")
3299                    .header("content-type", "application/json")
3300                    .body(Body::from(
3301                        r#"{"model":"alpha","messages":[{"role":"user","content":"hi"}]}"#,
3302                    ))
3303                    .unwrap(),
3304            )
3305            .await
3306            .unwrap();
3307        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3308        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3309        assert_eq!(v["usage"]["prompt_tokens"], 3);
3310        assert_eq!(v["usage"]["completion_tokens"], 2);
3311        assert_eq!(v["usage"]["total_tokens"], 5);
3312    }
3313
3314    // --- tool_choice parsing (audit finding 6) -----------------------------
3315
3316    #[test]
3317    fn tool_choice_string_passes_through() {
3318        assert_eq!(
3319            tool_choice_str(&serde_json::json!("required")).unwrap(),
3320            Some("required".to_string())
3321        );
3322        assert_eq!(
3323            tool_choice_str(&serde_json::json!("auto")).unwrap(),
3324            Some("auto".to_string())
3325        );
3326    }
3327
3328    /// B22: a forced `tool_choice` the server cannot honour is a 400, not free text.
3329    ///
3330    /// `OaiRenderer::tool_constraint` returns `None` as soon as `tools` is absent — without reading
3331    /// `tool_choice` at all — and `run_chat` treats that as "generate normally". So every case
3332    /// below used to produce ordinary assistant text while the client believed it had forced a
3333    /// call.
3334    #[test]
3335    fn a_forced_tool_choice_needs_tools_that_can_satisfy_it() {
3336        let tools = serde_json::json!([{"function": {"name": "bash"}}]);
3337
3338        // Rejected: nothing to call.
3339        for choice in ["required", "bash"] {
3340            assert!(
3341                validate_tool_choice(Some(choice), None).is_err(),
3342                "{choice:?} with no tools must 400"
3343            );
3344            assert!(
3345                validate_tool_choice(Some(choice), Some(&serde_json::json!([]))).is_err(),
3346                "{choice:?} with an empty tools array must 400"
3347            );
3348        }
3349        // Rejected: names no tool that was offered. This is the case that built `{"anyOf": []}`.
3350        assert!(validate_tool_choice(Some("bogus"), Some(&tools)).is_err());
3351
3352        // Accepted: policies that are satisfiable without tools, and a name that is present.
3353        assert!(validate_tool_choice(Some("auto"), None).is_ok());
3354        assert!(
3355            validate_tool_choice(Some("none"), None).is_ok(),
3356            "`none` asks for no tool call, which needs no tools"
3357        );
3358        assert!(validate_tool_choice(None, None).is_ok());
3359        assert!(validate_tool_choice(Some("required"), Some(&tools)).is_ok());
3360        assert!(validate_tool_choice(Some("bash"), Some(&tools)).is_ok());
3361    }
3362
3363    /// The same rule over HTTP, so the wire really returns 400 and names the offending parameter.
3364    #[tokio::test]
3365    async fn forced_tool_choice_without_tools_is_a_400() {
3366        let resp = multi_router()
3367            .oneshot(
3368                Request::builder()
3369                    .method("POST")
3370                    .uri("/v1/chat/completions")
3371                    .header("content-type", "application/json")
3372                    .body(Body::from(
3373                        r#"{"model":"a","messages":[{"role":"user","content":"hi"}],"tool_choice":"required"}"#,
3374                    ))
3375                    .unwrap(),
3376            )
3377            .await
3378            .unwrap();
3379        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
3380        let v = body_json(resp).await;
3381        assert_eq!(v["error"]["param"], "tool_choice");
3382        assert_eq!(v["error"]["type"], "invalid_request_error");
3383    }
3384
3385    #[test]
3386    fn tool_choice_named_function_forces_that_tool() {
3387        let v = serde_json::json!({"type":"function","function":{"name":"bash"}});
3388        assert_eq!(tool_choice_str(&v).unwrap(), Some("bash".to_string()));
3389    }
3390
3391    #[test]
3392    fn tool_choice_object_without_name_is_an_error_not_auto() {
3393        // The bug: a forced-tool object lacking function.name silently downgraded to "auto". It must
3394        // now be a 400 (ParamError), distinguishable from ABSENT (which the caller maps to None).
3395        let v = serde_json::json!({"type":"function","function":{}});
3396        let e = tool_choice_str(&v).unwrap_err();
3397        assert_eq!(e.param, "tool_choice");
3398        let v = serde_json::json!({"type":"function"});
3399        assert!(tool_choice_str(&v).is_err());
3400    }
3401
3402    #[test]
3403    fn tool_choice_wrong_shape_is_an_error() {
3404        assert!(tool_choice_str(&serde_json::json!(42)).is_err());
3405        assert!(tool_choice_str(&serde_json::json!(["auto"])).is_err());
3406    }
3407
3408    // --- max_tokens clamp (audit finding 5) --------------------------------
3409
3410    #[test]
3411    fn max_tokens_clamps_absurd_values_but_passes_unset_and_normal() {
3412        // Unset stays unset — the generator keeps applying its own INFR_MAX_NEW default (behaviour
3413        // unchanged for requests that don't ask for a budget).
3414        assert_eq!(clamp_max_tokens(None, 1000), None);
3415        // A sane value under the cap is untouched.
3416        assert_eq!(clamp_max_tokens(Some(512), 1000), Some(512));
3417        // An absurd value is capped, not rejected.
3418        assert_eq!(clamp_max_tokens(Some(10_000_000), 1000), Some(1000));
3419        // Exactly the cap passes.
3420        assert_eq!(clamp_max_tokens(Some(1000), 1000), Some(1000));
3421    }
3422
3423    // --- optional bearer auth (audit finding 5) ----------------------------
3424
3425    #[test]
3426    fn auth_disabled_allows_everything() {
3427        // No key configured (None) => open, regardless of what the client sends.
3428        assert!(authorize(None, None));
3429        assert!(authorize(None, Some("Bearer whatever")));
3430        assert!(authorize(None, Some("garbage")));
3431    }
3432
3433    #[test]
3434    fn auth_enabled_requires_matching_bearer() {
3435        let key = Some("s3cret");
3436        // Correct token (either capitalisation of the scheme) => allowed.
3437        assert!(authorize(key, Some("Bearer s3cret")));
3438        assert!(authorize(key, Some("bearer s3cret")));
3439        // Wrong token, missing header, or malformed scheme => denied.
3440        assert!(!authorize(key, Some("Bearer wrong")));
3441        assert!(!authorize(key, None));
3442        assert!(!authorize(key, Some("s3cret")));
3443        assert!(!authorize(key, Some("Basic s3cret")));
3444    }
3445
3446    /// The constant-time swap is a comparison, not a hash or a prefix check — so pin the two
3447    /// mistakes a hand-rolled "no early exit" loop typically makes.
3448    ///
3449    /// 1. SAME-LENGTH tokens must still be decided on CONTENT. A fold that ORs XORs together is
3450    ///    easy to get wrong in the direction of always-equal (e.g. accumulating `&=`, or seeding
3451    ///    the accumulator with the wrong identity), and same-length pairs are the only case where
3452    ///    that bug is invisible to the length check.
3453    /// 2. A correct PREFIX must be rejected. `ct_eq` answers `false` on a length mismatch, but a
3454    ///    zip-based loop silently compares only `min(len)` bytes and would accept `"s3c"` for
3455    ///    `"s3cret"` — the exact shape an attacker walks a key out with.
3456    #[test]
3457    fn auth_compares_full_token_not_a_prefix() {
3458        let key = Some("s3cret");
3459        // Same length as the wrong token below, and correct => allowed.
3460        assert!(authorize(key, Some("Bearer s3cret")));
3461        // Same length, differs only in the LAST byte => denied.
3462        assert!(!authorize(key, Some("Bearer s3creT")));
3463        // Same length, differs only in the FIRST byte => denied.
3464        assert!(!authorize(key, Some("Bearer S3cret")));
3465        // Correct prefix, short => denied (never "equal so far, therefore equal").
3466        assert!(!authorize(key, Some("Bearer s3c")));
3467        assert!(!authorize(key, Some("Bearer s")));
3468        assert!(!authorize(key, Some("Bearer ")));
3469        // Correct prefix, long => denied.
3470        assert!(!authorize(key, Some("Bearer s3cretx")));
3471        // The header's `str::trim` still runs before the compare (surrounding whitespace is not
3472        // part of the token), so a padded correct token is accepted and a padded wrong one is not.
3473        assert!(authorize(key, Some("Bearer   s3cret  ")));
3474        assert!(!authorize(key, Some("Bearer   s3cre  ")));
3475    }
3476
3477    // --- the `serve.*` knobs, driven through a `Config` (R7: never the environment) ------
3478
3479    /// `serve.api_key` decides whether auth is on, and the EMPTY string still means OFF — the
3480    /// grammar `INFR_API_KEY=` has always had. Getting this backwards would turn an empty
3481    /// key into a credential every request has to guess, so it is asserted explicitly.
3482    #[test]
3483    fn configured_api_key_reads_the_config_and_empty_still_means_no_auth() {
3484        let mut cfg = Config::default();
3485        assert_eq!(configured_api_key(&cfg), None, "unset => auth disabled");
3486
3487        cfg.serve.api_key = Some(String::new());
3488        assert_eq!(configured_api_key(&cfg), None, "empty => auth DISABLED");
3489
3490        cfg.serve.api_key = Some("hunter2".into());
3491        assert_eq!(configured_api_key(&cfg), Some("hunter2"));
3492        // …and a configured key really does gate the request.
3493        assert!(authorize(configured_api_key(&cfg), Some("Bearer hunter2")));
3494        assert!(!authorize(configured_api_key(&cfg), None));
3495    }
3496
3497    /// `serve.max_tokens_cap` feeds the clamp, and a non-positive value falls back to the shipped
3498    /// default rather than clamping every request to zero.
3499    #[test]
3500    fn max_tokens_cap_reads_the_config_and_rejects_non_positive() {
3501        let mut cfg = Config::default();
3502        assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
3503
3504        cfg.serve.max_tokens_cap = 4096;
3505        assert_eq!(max_tokens_cap(&cfg), 4096);
3506        assert_eq!(
3507            clamp_max_tokens(Some(10_000), max_tokens_cap(&cfg)),
3508            Some(4096)
3509        );
3510
3511        cfg.serve.max_tokens_cap = 0;
3512        assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
3513    }
3514
3515    /// End to end through the router: a state built with `serve.api_key` set answers 401 without a
3516    /// bearer token and gets past auth with one. Proves the handler reads the state's config, not
3517    /// the process environment.
3518    #[tokio::test]
3519    async fn configured_api_key_gates_the_chat_endpoint() {
3520        let mut cfg = Config::default();
3521        cfg.serve.api_key = Some("s3cret".into());
3522        let state = AppState::headless("test-model", Arc::new(cfg));
3523        let body = r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}]}"#;
3524        let req = |auth: Option<&str>| {
3525            let mut b = Request::builder()
3526                .method("POST")
3527                .uri("/v1/chat/completions")
3528                .header("content-type", "application/json");
3529            if let Some(a) = auth {
3530                b = b.header("authorization", a);
3531            }
3532            b.body(Body::from(body)).unwrap()
3533        };
3534        let resp = build_router(state.clone())
3535            .oneshot(req(None))
3536            .await
3537            .unwrap();
3538        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
3539        // With the right token the request gets PAST auth (headless => 500 from the missing
3540        // engine, which is exactly "not 401").
3541        let resp = build_router(state)
3542            .oneshot(req(Some("Bearer s3cret")))
3543            .await
3544            .unwrap();
3545        assert_ne!(resp.status(), StatusCode::UNAUTHORIZED);
3546    }
3547
3548    /// `/v1/models` enumerates what the process is hosting, so a configured key must gate it too —
3549    /// otherwise anyone who can reach the port learns every model id for free, on a server whose
3550    /// operator explicitly said it is not open. `/health` must stay OPEN through the same config: a
3551    /// load balancer holds no bearer token, and a bare 200 discloses nothing.
3552    #[tokio::test]
3553    async fn configured_api_key_gates_models_but_never_health() {
3554        let mut cfg = Config::default();
3555        cfg.serve.api_key = Some("s3cret".into());
3556        let state = AppState::headless("test-model", Arc::new(cfg));
3557        let get = |uri: &str, auth: Option<&str>| {
3558            let mut b = Request::builder().uri(uri);
3559            if let Some(a) = auth {
3560                b = b.header("authorization", a);
3561            }
3562            b.body(Body::empty()).unwrap()
3563        };
3564
3565        // No bearer => 401, in the same envelope the chat handler returns.
3566        let resp = build_router(state.clone())
3567            .oneshot(get("/v1/models", None))
3568            .await
3569            .unwrap();
3570        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
3571        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3572        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3573        assert_eq!(v["error"]["type"], "invalid_request_error");
3574        assert_eq!(v["error"]["code"], "invalid_api_key");
3575        assert_eq!(
3576            v["error"]["message"],
3577            "missing or invalid Authorization bearer token"
3578        );
3579        // …and the model list did NOT leak into the error body.
3580        assert!(
3581            !String::from_utf8_lossy(&bytes).contains("test-model"),
3582            "a 401 must not disclose the model set: {bytes:?}"
3583        );
3584
3585        // Wrong bearer => still 401.
3586        let resp = build_router(state.clone())
3587            .oneshot(get("/v1/models", Some("Bearer wrong")))
3588            .await
3589            .unwrap();
3590        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
3591
3592        // Right bearer => the unchanged 200 body.
3593        let resp = build_router(state.clone())
3594            .oneshot(get("/v1/models", Some("Bearer s3cret")))
3595            .await
3596            .unwrap();
3597        assert_eq!(resp.status(), StatusCode::OK);
3598        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3599        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3600        assert_eq!(v["object"], "list");
3601        assert_eq!(v["data"][0]["id"], "test-model");
3602        assert_eq!(v["data"][0]["object"], "model");
3603        assert_eq!(v["data"][0]["owned_by"], "local");
3604
3605        // /health is open both ways.
3606        for auth in [None, Some("Bearer s3cret")] {
3607            let resp = build_router(state.clone())
3608                .oneshot(get("/health", auth))
3609                .await
3610                .unwrap();
3611            assert_eq!(resp.status(), StatusCode::OK, "auth={auth:?}");
3612        }
3613    }
3614
3615    // --- per-request wall-clock deadline ------------------------------------
3616
3617    /// `serve.request_timeout_secs` is OFF (unbounded) by default, and `0` explicitly means the
3618    /// same thing — a deadline truncates legitimate long replies, so it is opt-in only.
3619    #[test]
3620    fn request_timeout_is_off_by_default_and_zero_means_unbounded() {
3621        let mut cfg = Config::default();
3622        assert_eq!(request_timeout(&cfg), None, "default => no deadline");
3623
3624        cfg.serve.request_timeout_secs = 0;
3625        assert_eq!(request_timeout(&cfg), None, "0 => no deadline");
3626
3627        cfg.serve.request_timeout_secs = 300;
3628        assert_eq!(request_timeout(&cfg), Some(Duration::from_secs(300)));
3629    }
3630
3631    /// A generator that never stops on its own: it emits one delta and then polls `cancel` until
3632    /// something latches it — exactly the shape of a real decode loop, and the only way to test
3633    /// that the deadline reaches the abort mechanism rather than just abandoning the join. Returns
3634    /// `Finish::Stop`, because that is what a real generator reports when it is aborted: it cannot
3635    /// tell WHY the flag was set, which is why the handler has to relabel.
3636    struct LoopGen;
3637    impl ChatGenerator for LoopGen {
3638        fn status(&self) -> GeneratorStatus {
3639            cpu_status()
3640        }
3641
3642        fn chat(
3643            &self,
3644            _messages: &[ChatMessage],
3645            _tools: Option<&serde_json::Value>,
3646            _tool_choice: Option<&str>,
3647            _params: &GenParams,
3648            cancel: &Arc<AtomicBool>,
3649            on_delta: &mut dyn FnMut(Delta),
3650        ) -> anyhow::Result<ChatOutcome> {
3651            on_delta(Delta::Content("partial".into()));
3652            while !cancel.load(Ordering::Relaxed) {
3653                std::thread::sleep(Duration::from_millis(2));
3654            }
3655            Ok(ChatOutcome {
3656                finish: Finish::Stop,
3657                prompt_tokens: 3,
3658                completion_tokens: 1,
3659                cached_tokens: 0,
3660            })
3661        }
3662    }
3663
3664    /// One entry hosting `gen`, routed as `"m"` — the handler-level fixture the deadline tests
3665    /// need, since `non_streaming`/`streaming` take a `ModelEntry` and a deadline directly (the
3666    /// knob is in whole SECONDS, so driving these through the router could not stay sub-second).
3667    fn deadline_entry(generator: Arc<dyn ChatGenerator>) -> ModelEntry {
3668        AppState::new(generator, "m", 1, Arc::new(Config::default())).route("m")
3669    }
3670
3671    /// The per-request context the two generation paths take, with a fresh (undrained) stats sink —
3672    /// the handler builds this from the request; a test that calls `streaming`/`non_streaming`
3673    /// directly has to build its own.
3674    fn test_ctx(deadline: Option<Duration>, stream: bool) -> ReqCtx {
3675        ReqCtx {
3676            id: next_req_id(),
3677            cid: "cid".into(),
3678            model_id: "m".into(),
3679            created: 0,
3680            deadline,
3681            stream,
3682            include_usage: false,
3683            stats: Arc::default(),
3684        }
3685    }
3686
3687    fn user_msg() -> Vec<ChatMessage> {
3688        vec![ChatMessage {
3689            role: "user".into(),
3690            content: "hi".into(),
3691            tool_calls: None,
3692            tool_call_id: None,
3693            name: None,
3694        }]
3695    }
3696
3697    async fn body_json(resp: Response) -> serde_json::Value {
3698        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3699        serde_json::from_slice(&bytes).unwrap()
3700    }
3701
3702    /// The non-streaming deadline: it fires, the client still gets what was generated, and the
3703    /// finish reason is `length` — NOT a 500, and not the `stop` the generator itself reported.
3704    #[tokio::test]
3705    async fn non_streaming_deadline_returns_partial_content_as_length() {
3706        let started = std::time::Instant::now();
3707        let resp = non_streaming(
3708            deadline_entry(Arc::new(LoopGen)),
3709            user_msg(),
3710            None,
3711            None,
3712            GenParams::default(),
3713            test_ctx(Some(Duration::from_millis(150)), false),
3714        )
3715        .await;
3716        assert_eq!(resp.status(), StatusCode::OK, "a deadline is not a failure");
3717        let v = body_json(resp).await;
3718        assert_eq!(v["choices"][0]["finish_reason"], "length");
3719        assert_eq!(
3720            v["choices"][0]["message"]["content"], "partial",
3721            "the partial completion must survive the deadline"
3722        );
3723        // The handler kept awaiting the join after latching the abort, so by the time it answered
3724        // the blocking task had really ended — and with it, its slot permit.
3725        assert!(
3726            started.elapsed() < Duration::from_secs(5),
3727            "the deadline did not stop the generator"
3728        );
3729    }
3730
3731    /// The permit is genuinely back: the entry admits `--parallel 1` at a time, so a SECOND request
3732    /// on the same entry can only be served if the first one's blocking task actually ended. If the
3733    /// deadline had merely timed out the join and left the task running, this would hang.
3734    #[tokio::test]
3735    async fn deadline_frees_the_slot_for_the_next_request() {
3736        let entry = deadline_entry(Arc::new(LoopGen));
3737        for _ in 0..2 {
3738            let resp = non_streaming(
3739                entry.clone(),
3740                user_msg(),
3741                None,
3742                None,
3743                GenParams::default(),
3744                test_ctx(Some(Duration::from_millis(100)), false),
3745            )
3746            .await;
3747            assert_eq!(
3748                body_json(resp).await["choices"][0]["finish_reason"],
3749                "length"
3750            );
3751        }
3752        assert_eq!(
3753            entry.slots.available_permits(),
3754            1,
3755            "the slot must be back after a deadline hit"
3756        );
3757    }
3758
3759    /// A request that finishes well inside its deadline is untouched: real content, the
3760    /// generator's OWN finish reason, and no relabelling.
3761    #[tokio::test]
3762    async fn generation_inside_the_deadline_is_untouched() {
3763        let resp = non_streaming(
3764            deadline_entry(Arc::new(EchoGen("alpha"))),
3765            user_msg(),
3766            None,
3767            None,
3768            GenParams::default(),
3769            test_ctx(Some(Duration::from_secs(30)), false),
3770        )
3771        .await;
3772        let v = body_json(resp).await;
3773        assert_eq!(v["choices"][0]["finish_reason"], "stop");
3774        assert_eq!(v["choices"][0]["message"]["content"], "from:alpha");
3775    }
3776
3777    /// The streaming deadline: the deltas already sent are kept, the finish chunk says `length`,
3778    /// and `[DONE]` still closes the stream.
3779    #[tokio::test]
3780    async fn streaming_deadline_finishes_with_length() {
3781        let resp = streaming(
3782            deadline_entry(Arc::new(LoopGen)),
3783            user_msg(),
3784            None,
3785            None,
3786            GenParams::default(),
3787            test_ctx(Some(Duration::from_millis(150)), true),
3788        )
3789        .await;
3790        assert_eq!(resp.status(), StatusCode::OK);
3791        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3792        let text = String::from_utf8(bytes.to_vec()).unwrap();
3793        assert!(text.contains("partial"), "partial content lost: {text}");
3794        assert!(
3795            text.contains("\"finish_reason\":\"length\""),
3796            "a deadline hit must finish as `length`: {text}"
3797        );
3798        assert!(
3799            !text.contains("\"finish_reason\":\"stop\""),
3800            "the generator's `stop` must not reach the wire: {text}"
3801        );
3802        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
3803    }
3804
3805    /// The watchdog must not outlive its request. Dropping the "generation finished" sender — which
3806    /// is what the blocking task does when it returns, or unwinds — has to end the timer task, or a
3807    /// long-lived server accumulates one sleeping task per request. Asserted by waiting PAST the
3808    /// deadline and finding the flags still clear.
3809    #[tokio::test]
3810    async fn dropping_the_done_signal_disarms_the_watchdog() {
3811        let cancel = Arc::new(AtomicBool::new(false));
3812        let hit = Arc::new(AtomicBool::new(false));
3813        let done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
3814        drop(done_tx); // the generation finished first
3815        tokio::time::sleep(Duration::from_millis(200)).await;
3816        assert!(
3817            !cancel.load(Ordering::Relaxed) && !hit.load(Ordering::Relaxed),
3818            "a disarmed watchdog must never fire"
3819        );
3820
3821        // …and one that is NOT disarmed does fire, on both flags (so the finish reason can tell a
3822        // deadline apart from a client disconnect, which latches only `cancel`).
3823        let cancel = Arc::new(AtomicBool::new(false));
3824        let hit = Arc::new(AtomicBool::new(false));
3825        let _done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
3826        tokio::time::sleep(Duration::from_millis(200)).await;
3827        assert!(cancel.load(Ordering::Relaxed) && hit.load(Ordering::Relaxed));
3828    }
3829
3830    // --- finish-reason mapping: Err is an error frame, never `stop` (finding 1) ---
3831
3832    /// A generator whose `chat` fails mid-stream. The streaming path must NOT relabel this as a
3833    /// clean `stop`; it must emit a terminal error frame, then `[DONE]`.
3834    struct FailGen;
3835    impl ChatGenerator for FailGen {
3836        fn status(&self) -> GeneratorStatus {
3837            cpu_status()
3838        }
3839
3840        fn chat(
3841            &self,
3842            _messages: &[ChatMessage],
3843            _tools: Option<&serde_json::Value>,
3844            _tool_choice: Option<&str>,
3845            _params: &GenParams,
3846            _cancel: &Arc<AtomicBool>,
3847            on_delta: &mut dyn FnMut(Delta),
3848        ) -> anyhow::Result<ChatOutcome> {
3849            on_delta(Delta::Content("partial".into()));
3850            anyhow::bail!("boom mid-stream")
3851        }
3852    }
3853
3854    #[tokio::test]
3855    async fn streaming_error_emits_error_frame_not_stop() {
3856        let g: Arc<dyn ChatGenerator> = Arc::new(FailGen);
3857        let router = build_router(AppState::new(g, "m", 1, Arc::new(Config::default())));
3858        let resp = router
3859            .oneshot(
3860                Request::builder()
3861                    .method("POST")
3862                    .uri("/v1/chat/completions")
3863                    .header("content-type", "application/json")
3864                    .body(Body::from(
3865                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
3866                    ))
3867                    .unwrap(),
3868            )
3869            .await
3870            .unwrap();
3871        assert_eq!(resp.status(), StatusCode::OK);
3872        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3873        let text = String::from_utf8(bytes.to_vec()).unwrap();
3874        // A terminal error frame is present, the stream is closed with [DONE], and NO finish chunk
3875        // ever claimed a clean "stop".
3876        assert!(text.contains("\"error\""), "missing error frame: {text}");
3877        assert!(
3878            text.contains("boom mid-stream"),
3879            "error message lost: {text}"
3880        );
3881        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
3882        assert!(
3883            !text.contains("\"finish_reason\":\"stop\""),
3884            "an Err must not report a clean stop: {text}"
3885        );
3886    }
3887
3888    /// A generator whose `chat` PANICS mid-stream, which is not the same as returning `Err`: the
3889    /// unwind skips every arm of the `match res` below it, so before B23 the only thing that ran
3890    /// was `DoneGuard`'s `[DONE]`.
3891    struct PanicGen;
3892    impl ChatGenerator for PanicGen {
3893        fn status(&self) -> GeneratorStatus {
3894            cpu_status()
3895        }
3896
3897        fn chat(
3898            &self,
3899            _messages: &[ChatMessage],
3900            _tools: Option<&serde_json::Value>,
3901            _tool_choice: Option<&str>,
3902            _params: &GenParams,
3903            _cancel: &Arc<AtomicBool>,
3904            on_delta: &mut dyn FnMut(Delta),
3905        ) -> anyhow::Result<ChatOutcome> {
3906            on_delta(Delta::Content("partial".into()));
3907            panic!("boom: generator panicked mid-stream")
3908        }
3909    }
3910
3911    /// B23: a panicking generator must terminate the stream like a FAILURE, not like a success.
3912    ///
3913    /// The bug this pins is one of omission, so assert on what was missing: an error frame, and a
3914    /// `failed` count. Both were absent while `[DONE]` was present, which is precisely what made a
3915    /// panic indistinguishable from a short completion on the wire.
3916    #[tokio::test]
3917    async fn streaming_panic_is_reported_as_a_failure() {
3918        let g: Arc<dyn ChatGenerator> = Arc::new(PanicGen);
3919        let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
3920        let stats = state.stats.clone();
3921        let router = build_router(state);
3922        // The panic is expected and its message lands in this test's captured output. No
3923        // `set_hook` to hide it: the hook is process-global and would also swallow the backtrace
3924        // of any test panicking on another thread meanwhile.
3925        let resp = router
3926            .oneshot(
3927                Request::builder()
3928                    .method("POST")
3929                    .uri("/v1/chat/completions")
3930                    .header("content-type", "application/json")
3931                    .body(Body::from(
3932                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
3933                    ))
3934                    .unwrap(),
3935            )
3936            .await
3937            .unwrap();
3938        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3939        let text = String::from_utf8(bytes.to_vec()).unwrap();
3940
3941        assert!(
3942            text.contains("\"error\""),
3943            "a panicking generator must still put a terminal error frame on the wire: {text}"
3944        );
3945        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
3946        assert!(
3947            !text.contains("\"finish_reason\":\"stop\""),
3948            "a panic must never look like a clean stop: {text}"
3949        );
3950
3951        let w = stats.drain(Duration::from_secs(1));
3952        assert_eq!(w.failed, 1, "the panic must be counted as a failure");
3953        assert_eq!(
3954            w.completed, 1,
3955            "a failure is still a completed request for the interval line"
3956        );
3957        assert_eq!(w.active, 0, "the slot gauge must be released by the unwind");
3958    }
3959
3960    /// The abort-on-disconnect decision, unit-tested without a socket: when the SSE `send` returns
3961    /// Err (receiver dropped), the callback must latch the per-request cancel flag. Full
3962    /// disconnect→GPU-slot-release is integration-only (needs a live generator + real client drop).
3963    #[test]
3964    fn send_failure_latches_the_cancel_flag() {
3965        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
3966        let cancel = AtomicBool::new(false);
3967        drop(rx); // simulate the client disconnecting: the receiver is gone.
3968        if tx.send(Ok(Event::default().data("x"))).is_err() {
3969            cancel.store(true, Ordering::Relaxed);
3970        }
3971        assert!(
3972            cancel.load(Ordering::Relaxed),
3973            "a failed send must latch the abort flag so the decode loop stops"
3974        );
3975    }
3976
3977    // --- request / throughput logging (B10) ---------------------------------
3978
3979    /// A finished request, spelled out so a test can fold one in without running a generator.
3980    ///
3981    /// Defaults to "all of its deltas are in window 0, which is still open" — the ordinary case
3982    /// where no drain intervened. [`rec_in_window`] is for the case that does.
3983    fn rec(prompt: u32, gen: u32, deltas: u64) -> ReqRecord {
3984        rec_in_window(prompt, gen, deltas, 0, deltas)
3985    }
3986
3987    /// A finished request whose deltas landed in a specific stats window — the B24 shape.
3988    fn rec_in_window(
3989        prompt: u32,
3990        gen: u32,
3991        deltas: u64,
3992        window: u64,
3993        deltas_in_window: u64,
3994    ) -> ReqRecord {
3995        ReqRecord {
3996            prompt_tokens: prompt,
3997            gen_tokens: gen,
3998            deltas,
3999            window,
4000            deltas_in_window,
4001            prefill: Duration::from_millis(100),
4002            decode: Duration::from_millis(400),
4003            total: Duration::from_millis(500),
4004            finish: Finish::Stop,
4005        }
4006    }
4007
4008    /// **The whole point of the periodic line.** Its numbers must describe the INTERVAL, so a drain
4009    /// has to leave the counters at zero — a cumulative counter would turn every rate into an
4010    /// average-since-boot, which looks plausible and is useless.
4011    ///
4012    /// Asserted by three consecutive intervals of the SAME wall length with DIFFERENT work in them:
4013    /// busy, half as busy, idle. Per-interval, the rates must go 10 → 5 → 0. Cumulative, they would
4014    /// go 10 → 15 → 15 (or 10 → 7.5 → 5 as an average), i.e. they could never fall — which is the
4015    /// exact failure this pins.
4016    #[test]
4017    fn stats_windows_cover_the_interval_and_never_accumulate() {
4018        let stats = ServeStats::default();
4019        let window = Duration::from_secs(2);
4020
4021        for _ in 0..20 {
4022            stats.bump_gen(1);
4023        }
4024        stats.fold_completion(&rec(100, 20, 20));
4025        let busy = stats.drain(window);
4026        assert_eq!(
4027            (busy.prompt_tokens, busy.gen_tokens, busy.completed),
4028            (100, 20, 1)
4029        );
4030        assert!((busy.decode_tps() - 10.0).abs() < 1e-9, "{busy:?}");
4031        assert!((busy.prefill_tps() - 50.0).abs() < 1e-9, "{busy:?}");
4032
4033        for _ in 0..10 {
4034            stats.bump_gen(1);
4035        }
4036        stats.fold_completion(&rec(20, 10, 10));
4037        let quieter = stats.drain(window);
4038        assert_eq!((quieter.prompt_tokens, quieter.gen_tokens), (20, 10));
4039        assert!(
4040            (quieter.decode_tps() - 5.0).abs() < 1e-9,
4041            "the second interval must report only ITS OWN 10 tokens: {quieter:?}"
4042        );
4043        assert!(
4044            quieter.decode_tps() < busy.decode_tps() && quieter.prefill_tps() < busy.prefill_tps(),
4045            "half the work in the same wall time must report a LOWER rate: {busy:?} then {quieter:?}"
4046        );
4047
4048        let idle = stats.drain(window);
4049        assert_eq!(
4050            (idle.gen_tokens, idle.prompt_tokens, idle.completed),
4051            (0, 0, 0)
4052        );
4053        assert_eq!(idle.decode_tps(), 0.0);
4054        assert!(
4055            !idle.has_activity(),
4056            "an interval with nothing in it must emit no line: {idle:?}"
4057        );
4058    }
4059
4060    /// The live per-delta count is an ESTIMATE (a delta is a text piece, not necessarily a token);
4061    /// `ChatOutcome` is authoritative. Whichever way they disagree, the interval total must end up
4062    /// on the authoritative number.
4063    #[test]
4064    fn the_live_delta_count_is_reconciled_against_the_real_token_count() {
4065        // Generator emitted 3 pieces but really decoded 5 tokens.
4066        let under = ServeStats::default();
4067        for _ in 0..3 {
4068            under.bump_gen(1);
4069        }
4070        under.fold_completion(&rec(1, 5, 3));
4071        assert_eq!(under.drain(Duration::from_secs(1)).gen_tokens, 5);
4072
4073        // …and the other way: 6 pieces for 4 tokens.
4074        let over = ServeStats::default();
4075        for _ in 0..6 {
4076            over.bump_gen(1);
4077        }
4078        over.fold_completion(&rec(1, 4, 6));
4079        assert_eq!(over.drain(Duration::from_secs(1)).gen_tokens, 4);
4080    }
4081
4082    /// B24: a correction must never be paid for out of a DIFFERENT request's interval.
4083    ///
4084    /// The reconciliation above only works because nothing drains between the deltas and the
4085    /// completion. When a reporter tick lands in that gap the deltas have already been published,
4086    /// and the retraction used to come out of whatever was generating next.
4087    #[test]
4088    fn a_correction_never_retracts_another_requests_tokens() {
4089        let s = ServeStats::default();
4090
4091        // Request A emits two deltas, and the reporter ticks before A finishes.
4092        let mut a = ReqTally::new();
4093        a.on_text_delta(&s);
4094        a.on_text_delta(&s);
4095        let w1 = s.drain(Duration::from_secs(1));
4096        assert_eq!(w1.gen_tokens, 2, "the open window had A's two deltas");
4097
4098        // Request B is now generating and puts three real tokens into the new window.
4099        let mut b = ReqTally::new();
4100        for _ in 0..3 {
4101            b.on_text_delta(&s);
4102        }
4103
4104        // A completes: it really produced ONE token, so its live estimate was 1 too high. That
4105        // overcount is in a window that has already been reported and cannot be taken back.
4106        s.fold_completion(&a.finish(
4107            ChatOutcome {
4108                finish: Finish::Stop,
4109                prompt_tokens: 1,
4110                completion_tokens: 1,
4111                cached_tokens: 0,
4112            },
4113            Finish::Stop,
4114        ));
4115
4116        let w2 = s.drain(Duration::from_secs(1));
4117        assert_eq!(
4118            w2.gen_tokens, 3,
4119            "B's three tokens must survive A's correction — the −1 belongs to a closed window"
4120        );
4121    }
4122
4123    /// The other half of B24: while the window is still open, a correction DOES apply — clamped to
4124    /// this request's own contribution, so it can never dig into tokens it did not put there.
4125    #[test]
4126    fn a_correction_applies_within_the_open_window_and_is_clamped_to_its_own_deltas() {
4127        let s = ServeStats::default();
4128        let mut a = ReqTally::new();
4129        for _ in 0..4 {
4130            a.on_text_delta(&s);
4131        }
4132        // No drain: A's deltas are still in the open window, so its −2 lands.
4133        s.fold_completion(&a.finish(
4134            ChatOutcome {
4135                finish: Finish::Stop,
4136                prompt_tokens: 1,
4137                completion_tokens: 2,
4138                cached_tokens: 0,
4139            },
4140            Finish::Stop,
4141        ));
4142        assert_eq!(s.drain(Duration::from_secs(1)).gen_tokens, 2);
4143
4144        // A request claiming FEWER tokens than it has deltas in this window can still only retract
4145        // what it contributed: 1 delta here, so a −3 becomes −1 and the other request keeps its 5.
4146        let s = ServeStats::default();
4147        let mut c = ReqTally::new();
4148        c.on_text_delta(&s);
4149        for _ in 0..5 {
4150            s.bump_gen(1); // another request's tokens, same window
4151        }
4152        let mut r = c.finish(
4153            ChatOutcome {
4154                finish: Finish::Stop,
4155                prompt_tokens: 0,
4156                completion_tokens: 0,
4157                cached_tokens: 0,
4158            },
4159            Finish::Stop,
4160        );
4161        r.deltas = 4; // pretend 4 deltas were seen, only 1 of them in this window
4162        s.fold_completion(&r);
4163        assert_eq!(
4164            s.drain(Duration::from_secs(1)).gen_tokens,
4165            5,
4166            "the retraction is capped at this request's own contribution to the window"
4167        );
4168    }
4169
4170    /// Activity-only, and what counts as activity. A request that is mid-generation has produced no
4171    /// completed tokens yet, but the server is plainly busy — so `active`/`queued` alone must be
4172    /// enough to emit a line, or a single long generation would log nothing until it ended. An
4173    /// interval with none of it emits nothing: there is no idle heartbeat, by decision.
4174    #[test]
4175    fn in_flight_requests_are_activity_and_an_empty_interval_is_not() {
4176        let stats = Arc::new(ServeStats::default());
4177        let w = Duration::from_secs(1);
4178        assert!(!stats.drain(w).has_activity(), "idle must be silent");
4179
4180        let generating = ActiveGuard::new(stats.clone());
4181        assert!(
4182            stats.drain(w).has_activity(),
4183            "a generation in flight is activity even before it yields a token"
4184        );
4185        drop(generating);
4186        assert!(!stats.drain(w).has_activity());
4187
4188        let waiting = QueuedGuard::new(stats.clone());
4189        assert!(
4190            stats.drain(w).has_activity(),
4191            "a request queued for a slot is activity"
4192        );
4193        drop(waiting);
4194        assert!(!stats.drain(w).has_activity());
4195    }
4196
4197    /// The gauges are RAII, so the interesting case is the abnormal exit: a guard dropped while
4198    /// unwinding must still put the gauge back, or one panicking request leaves the server looking
4199    /// permanently busy.
4200    #[test]
4201    fn the_active_gauge_is_released_by_an_unwinding_panic() {
4202        let stats = Arc::new(ServeStats::default());
4203        let inner = stats.clone();
4204        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
4205            let _active = ActiveGuard::new(inner);
4206            panic!("decode closure blew up");
4207        }));
4208        assert!(caught.is_err(), "the panic must have happened");
4209        assert_eq!(stats.active.load(Ordering::Relaxed), 0);
4210    }
4211
4212    /// `serve.stats_interval_secs`: 5 s by default, `0` switches the periodic line OFF.
4213    #[test]
4214    fn stats_interval_defaults_to_five_seconds_and_zero_disables_it() {
4215        let mut cfg = Config::default();
4216        assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(5)));
4217        cfg.serve.stats_interval_secs = 0;
4218        assert_eq!(stats_interval(&cfg), None, "0 => no periodic line at all");
4219        cfg.serve.stats_interval_secs = 30;
4220        assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(30)));
4221    }
4222
4223    /// KV slot occupancy is `busy/total` across every hosted model — the number the periodic line
4224    /// reports. It has to count HELD permits, not available ones.
4225    #[tokio::test]
4226    async fn slot_occupancy_counts_held_permits_across_models() {
4227        let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
4228        let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
4229        let state = AppState::multi(
4230            vec![("alpha".into(), a, 3), ("beta".into(), b, 1)],
4231            Arc::new(Config::default()),
4232        );
4233        assert_eq!(state.slot_occupancy(), (0, 4));
4234        let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
4235        assert_eq!(state.slot_occupancy(), (1, 4));
4236        let held2 = state.models[1].slots.clone().acquire_owned().await.unwrap();
4237        assert_eq!(state.slot_occupancy(), (2, 4));
4238        drop(held);
4239        drop(held2);
4240        assert_eq!(state.slot_occupancy(), (0, 4));
4241    }
4242
4243    /// Request ids are a monotonic counter, NOT a clock reading: two requests admitted in the same
4244    /// millisecond must still be tellable apart in the log.
4245    #[test]
4246    fn request_ids_are_monotonic_and_distinct() {
4247        // STRICTLY increasing rather than dense: the counter is process-wide and the rest of the
4248        // suite is minting ids from other threads at the same time, so the gaps are the mechanism
4249        // working, not a failure. What must hold is that no id is ever reissued or reused.
4250        let ids: Vec<u64> = (0..1000).map(|_| next_req_id()).collect();
4251        assert!(
4252            ids.windows(2).all(|w| w[1] > w[0]),
4253            "ids must increase monotonically"
4254        );
4255        let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
4256        assert_eq!(unique.len(), ids.len(), "ids must never repeat");
4257    }
4258
4259    /// End to end through the real non-streaming path: the request's tallies reach the shared
4260    /// counters exactly once, with the generator's OWN token counts — `EchoGen` sends one delta but
4261    /// reports two completion tokens, so this also proves the reconciliation runs on the live path
4262    /// and not only in its unit test.
4263    #[tokio::test]
4264    async fn a_served_request_folds_its_counts_into_the_window() {
4265        let stats: Arc<ServeStats> = Arc::default();
4266        let ctx = ReqCtx {
4267            stats: stats.clone(),
4268            ..test_ctx(None, false)
4269        };
4270        let resp = non_streaming(
4271            deadline_entry(Arc::new(EchoGen("alpha"))),
4272            user_msg(),
4273            None,
4274            None,
4275            GenParams::default(),
4276            ctx,
4277        )
4278        .await;
4279        assert_eq!(resp.status(), StatusCode::OK);
4280        let w = stats.drain(Duration::from_secs(1));
4281        assert_eq!(
4282            (w.prompt_tokens, w.gen_tokens, w.completed, w.failed),
4283            (3, 2, 1, 0),
4284            "EchoGen reports prompt_tokens=3, completion_tokens=2 for one request: {w:?}"
4285        );
4286        assert_eq!(
4287            (w.active, w.queued),
4288            (0, 0),
4289            "both gauges must be back at zero once the request is answered"
4290        );
4291    }
4292
4293    /// A failed generation is still a completed request, and it is counted as a FAILURE — a server
4294    /// erroring on everything must not look idle.
4295    #[tokio::test]
4296    async fn a_failed_request_is_counted_as_a_failure() {
4297        let stats: Arc<ServeStats> = Arc::default();
4298        let ctx = ReqCtx {
4299            stats: stats.clone(),
4300            ..test_ctx(None, false)
4301        };
4302        let resp = non_streaming(
4303            deadline_entry(Arc::new(FailGen)),
4304            user_msg(),
4305            None,
4306            None,
4307            GenParams::default(),
4308            ctx,
4309        )
4310        .await;
4311        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
4312        let w = stats.drain(Duration::from_secs(1));
4313        assert_eq!((w.completed, w.failed), (1, 1), "{w:?}");
4314        assert!(
4315            w.has_activity(),
4316            "an interval of failures is not an idle one"
4317        );
4318    }
4319
4320    // --- wire contract: usage, context length, body rejections, hang-ups ----
4321
4322    /// POST `body` to the chat route of `router` with a JSON content type.
4323    async fn post_chat(router: Router, body: &str) -> Response {
4324        router
4325            .oneshot(
4326                Request::builder()
4327                    .method("POST")
4328                    .uri("/v1/chat/completions")
4329                    .header("content-type", "application/json")
4330                    .body(Body::from(body.to_owned()))
4331                    .unwrap(),
4332            )
4333            .await
4334            .unwrap()
4335    }
4336
4337    fn router_for(generator: Arc<dyn ChatGenerator>) -> Router {
4338        build_router(AppState::new(
4339            generator,
4340            "m",
4341            1,
4342            Arc::new(Config::default()),
4343        ))
4344    }
4345
4346    /// A generator whose prompt was mostly served from the KV prefix cache: 20 prompt tokens, 19
4347    /// of them cached, so only 1 was prefilled.
4348    struct CachedPrefixGen;
4349    impl ChatGenerator for CachedPrefixGen {
4350        fn status(&self) -> GeneratorStatus {
4351            cpu_status()
4352        }
4353
4354        fn chat(
4355            &self,
4356            _messages: &[ChatMessage],
4357            _tools: Option<&serde_json::Value>,
4358            _tool_choice: Option<&str>,
4359            _params: &GenParams,
4360            _cancel: &Arc<AtomicBool>,
4361            on_delta: &mut dyn FnMut(Delta),
4362        ) -> anyhow::Result<ChatOutcome> {
4363            on_delta(Delta::Content("ok".into()));
4364            Ok(ChatOutcome {
4365                finish: Finish::Stop,
4366                prompt_tokens: 20,
4367                completion_tokens: 1,
4368                cached_tokens: 19,
4369            })
4370        }
4371    }
4372
4373    /// B83: `usage.prompt_tokens` is the whole prompt and the cached part is reported under
4374    /// `prompt_tokens_details.cached_tokens` — while the throughput counters still count only the
4375    /// one token that was actually prefilled.
4376    #[tokio::test]
4377    async fn usage_counts_the_whole_prompt_and_reports_the_cached_part() {
4378        let g: Arc<dyn ChatGenerator> = Arc::new(CachedPrefixGen);
4379        let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
4380        let stats = state.stats.clone();
4381        let resp = post_chat(
4382            build_router(state),
4383            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
4384        )
4385        .await;
4386        let v = body_json(resp).await;
4387        assert_eq!(v["usage"]["prompt_tokens"], 20);
4388        assert_eq!(v["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
4389        assert_eq!(v["usage"]["total_tokens"], 21);
4390        let w = stats.drain(Duration::from_secs(1));
4391        assert_eq!(w.prompt_tokens, 1, "only the prefilled token is throughput");
4392    }
4393
4394    /// The SSE frames of a streamed response, `data:` payloads in order.
4395    async fn sse_frames(resp: Response) -> Vec<String> {
4396        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4397        String::from_utf8(bytes.to_vec())
4398            .unwrap()
4399            .lines()
4400            .filter_map(|l| l.strip_prefix("data: ").map(str::to_owned))
4401            .collect()
4402    }
4403
4404    /// B137: `stream_options.include_usage` ends the stream with one chunk carrying `usage` and an
4405    /// empty `choices` array, after the finish chunk and before `[DONE]`. Without the option, no
4406    /// chunk carries `usage`.
4407    #[tokio::test]
4408    async fn include_usage_ends_the_stream_with_a_usage_chunk() {
4409        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true,
4410                       "stream_options":{"include_usage":true}}"#;
4411        let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
4412        let n = frames.len();
4413        assert!(n >= 3, "{frames:?}");
4414        assert_eq!(frames[n - 1], "[DONE]");
4415        let usage: serde_json::Value = serde_json::from_str(&frames[n - 2]).unwrap();
4416        assert_eq!(usage["choices"], serde_json::json!([]), "{frames:?}");
4417        assert_eq!(usage["usage"]["prompt_tokens"], 20);
4418        assert_eq!(usage["usage"]["completion_tokens"], 1);
4419        assert_eq!(usage["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
4420        let finish: serde_json::Value = serde_json::from_str(&frames[n - 3]).unwrap();
4421        assert_eq!(finish["choices"][0]["finish_reason"], "stop", "{frames:?}");
4422
4423        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#;
4424        let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
4425        assert!(
4426            frames.iter().all(|f| !f.contains("\"usage\"")),
4427            "usage was not asked for: {frames:?}"
4428        );
4429    }
4430
4431    /// A generator whose prompt does not fit the context.
4432    struct OverflowGen;
4433    impl ChatGenerator for OverflowGen {
4434        fn status(&self) -> GeneratorStatus {
4435            cpu_status()
4436        }
4437
4438        fn chat(
4439            &self,
4440            _messages: &[ChatMessage],
4441            _tools: Option<&serde_json::Value>,
4442            _tool_choice: Option<&str>,
4443            _params: &GenParams,
4444            _cancel: &Arc<AtomicBool>,
4445            _on_delta: &mut dyn FnMut(Delta),
4446        ) -> anyhow::Result<ChatOutcome> {
4447            Err(ContextLengthExceeded {
4448                message: "too long".into(),
4449            }
4450            .into())
4451        }
4452    }
4453
4454    /// B86: an over-long prompt is the client's to fix — `400 context_length_exceeded`, which
4455    /// OpenAI clients act on, not the `500` they retry unchanged.
4456    #[tokio::test]
4457    async fn an_over_long_prompt_is_a_400_context_length_exceeded() {
4458        let resp = post_chat(
4459            router_for(Arc::new(OverflowGen)),
4460            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
4461        )
4462        .await;
4463        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4464        let v = body_json(resp).await;
4465        assert_eq!(v["error"]["type"], "invalid_request_error");
4466        assert_eq!(v["error"]["code"], "context_length_exceeded");
4467        assert_eq!(v["error"]["param"], "messages");
4468        assert_eq!(v["error"]["message"], "too long");
4469    }
4470
4471    /// B86 on a stream: the `200` is already out, so the over-long prompt arrives as the terminal
4472    /// error frame — carrying the same typed error as the non-streaming `400`, not a generic
4473    /// `server_error` a client cannot tell from a crash — and `[DONE]` still closes the stream.
4474    #[tokio::test]
4475    async fn an_over_long_prompt_on_a_stream_is_a_typed_error_frame() {
4476        let frames = sse_frames(
4477            post_chat(
4478                router_for(Arc::new(OverflowGen)),
4479                r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
4480            )
4481            .await,
4482        )
4483        .await;
4484        assert_eq!(
4485            frames.last().map(String::as_str),
4486            Some("[DONE]"),
4487            "{frames:?}"
4488        );
4489        let err: serde_json::Value = frames
4490            .iter()
4491            .filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
4492            .find(|v| v.get("error").is_some())
4493            .expect("an error frame");
4494        assert_eq!(err["error"]["type"], "invalid_request_error");
4495        assert_eq!(err["error"]["code"], "context_length_exceeded");
4496        assert_eq!(err["error"]["param"], "messages");
4497        assert_eq!(err["error"]["message"], "too long");
4498    }
4499
4500    /// B86: a body over the size limit is `413` and a body without a JSON content type `415` — not
4501    /// the `400` a malformed body gets — still in the OpenAI error envelope.
4502    #[tokio::test]
4503    async fn oversized_and_untyped_bodies_keep_their_status() {
4504        let huge = format!(
4505            r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
4506            "x".repeat(3 << 20)
4507        );
4508        let resp = post_chat(router_for(Arc::new(EchoGen("a"))), &huge).await;
4509        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
4510        assert_eq!(
4511            body_json(resp).await["error"]["type"],
4512            "invalid_request_error"
4513        );
4514
4515        let resp = router_for(Arc::new(EchoGen("a")))
4516            .oneshot(
4517                Request::builder()
4518                    .method("POST")
4519                    .uri("/v1/chat/completions")
4520                    .body(Body::from(
4521                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
4522                    ))
4523                    .unwrap(),
4524            )
4525            .await
4526            .unwrap();
4527        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
4528        assert_eq!(
4529            body_json(resp).await["error"]["type"],
4530            "invalid_request_error"
4531        );
4532
4533        // Malformed JSON stays a 400.
4534        let resp = post_chat(router_for(Arc::new(EchoGen("a"))), "{not json").await;
4535        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4536    }
4537
4538    /// B137: the bearer check runs on the headers, before the body is read. A client without a
4539    /// token whose body never finishes arriving still gets its 401 at once.
4540    #[tokio::test]
4541    async fn the_bearer_check_does_not_wait_for_the_body() {
4542        let mut cfg = Config::default();
4543        cfg.serve.api_key = Some("s3cret".into());
4544        let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
4545        let router = build_router(AppState::new(g, "m", 1, Arc::new(cfg)));
4546        let never = futures_util::stream::pending::<Result<axum::body::Bytes, std::io::Error>>();
4547        let resp = tokio::time::timeout(
4548            Duration::from_secs(2),
4549            router.oneshot(
4550                Request::builder()
4551                    .method("POST")
4552                    .uri("/v1/chat/completions")
4553                    .header("content-type", "application/json")
4554                    .body(Body::from_stream(never))
4555                    .unwrap(),
4556            ),
4557        )
4558        .await
4559        .expect("an unauthenticated request waited for its body")
4560        .unwrap();
4561        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4562    }
4563
4564    /// B137: `-1` is the "unset" sentinel llama.cpp-style clients send for `seed` and `max_tokens`;
4565    /// it is accepted as unset, and any other negative value is still refused.
4566    #[tokio::test]
4567    async fn minus_one_seed_and_max_tokens_mean_unset() {
4568        let p = GenParams::from_request(&req(
4569            r#"{"model":"m","messages":[],"seed":-1,"max_tokens":-1,"max_completion_tokens":-1}"#,
4570        ))
4571        .unwrap();
4572        assert_eq!((p.seed, p.max_tokens), (None, None));
4573        let p = GenParams::from_request(&req(
4574            r#"{"model":"m","messages":[],"seed":18446744073709551615,"max_tokens":7}"#,
4575        ))
4576        .unwrap();
4577        assert_eq!((p.seed, p.max_tokens), (Some(u64::MAX), Some(7)));
4578        for bad in [
4579            r#""seed":-2"#,
4580            r#""max_tokens":-5"#,
4581            r#""max_tokens":4294967296"#,
4582        ] {
4583            let raw = format!(r#"{{"model":"m","messages":[],{bad}}}"#);
4584            assert!(serde_json::from_str::<ChatRequest>(&raw).is_err(), "{bad}");
4585        }
4586
4587        let resp = post_chat(
4588            router_for(Arc::new(EchoGen("a"))),
4589            r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"seed":-1,"max_tokens":-1}"#,
4590        )
4591        .await;
4592        assert_eq!(resp.status(), StatusCode::OK);
4593    }
4594
4595    /// Sits in a "prefill" that emits nothing, polling `cancel` the way a real prefill loop does,
4596    /// and records whether the latch reached it. Bounded, so a broken hang-up path fails the test
4597    /// instead of hanging it.
4598    struct HangGen {
4599        entered: Arc<AtomicBool>,
4600        cancelled: Arc<AtomicBool>,
4601    }
4602    impl ChatGenerator for HangGen {
4603        fn status(&self) -> GeneratorStatus {
4604            cpu_status()
4605        }
4606
4607        fn chat(
4608            &self,
4609            _messages: &[ChatMessage],
4610            _tools: Option<&serde_json::Value>,
4611            _tool_choice: Option<&str>,
4612            _params: &GenParams,
4613            cancel: &Arc<AtomicBool>,
4614            _on_delta: &mut dyn FnMut(Delta),
4615        ) -> anyhow::Result<ChatOutcome> {
4616            self.entered.store(true, Ordering::Relaxed);
4617            let started = Instant::now();
4618            while started.elapsed() < Duration::from_secs(5) {
4619                if cancel.load(Ordering::Relaxed) {
4620                    self.cancelled.store(true, Ordering::Relaxed);
4621                    break;
4622                }
4623                std::thread::sleep(Duration::from_millis(2));
4624            }
4625            Ok(ChatOutcome {
4626                finish: Finish::Stop,
4627                prompt_tokens: 1,
4628                completion_tokens: 0,
4629                cached_tokens: 0,
4630            })
4631        }
4632    }
4633
4634    /// Wait (bounded) for `flag` to be set.
4635    async fn eventually(flag: &AtomicBool, within: Duration) -> bool {
4636        let started = Instant::now();
4637        while !flag.load(Ordering::Relaxed) {
4638            if started.elapsed() > within {
4639                return false;
4640            }
4641            tokio::time::sleep(Duration::from_millis(5)).await;
4642        }
4643        true
4644    }
4645
4646    /// Serve a [`HangGen`] on a real socket, send one chat request, hang up once the generation
4647    /// is running, and report whether the hang-up reached the generator's `cancel` latch.
4648    async fn hang_up_reaches_the_generator(stream: bool) -> bool {
4649        use tokio::io::AsyncWriteExt;
4650        let entered = Arc::new(AtomicBool::new(false));
4651        let cancelled = Arc::new(AtomicBool::new(false));
4652        let g: Arc<dyn ChatGenerator> = Arc::new(HangGen {
4653            entered: entered.clone(),
4654            cancelled: cancelled.clone(),
4655        });
4656        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4657        let addr = listener.local_addr().unwrap();
4658        let router = router_for(g);
4659        let server = tokio::spawn(async move { axum::serve(listener, router).await });
4660        let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
4661        let body = format!(
4662            r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
4663        );
4664        let head = format!(
4665            "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n\
4666             Content-Type: application/json\r\nContent-Length: {}\r\n\r\n",
4667            body.len()
4668        );
4669        sock.write_all(head.as_bytes()).await.unwrap();
4670        sock.write_all(body.as_bytes()).await.unwrap();
4671        assert!(
4672            eventually(&entered, Duration::from_secs(2)).await,
4673            "the generation never started"
4674        );
4675        drop(sock);
4676        let reached = eventually(&cancelled, Duration::from_secs(2)).await;
4677        server.abort();
4678        reached
4679    }
4680
4681    /// B85: a non-streaming client that hangs up mid-generation cancels it, so its slot is not
4682    /// held to `max_tokens` for nobody.
4683    #[tokio::test]
4684    async fn a_non_streaming_hang_up_cancels_the_generation() {
4685        assert!(hang_up_reaches_the_generator(false).await);
4686    }
4687
4688    /// B85: a streaming client that hangs up while nothing is being sent — a long prefill — cancels
4689    /// the generation at once, not at the next delta.
4690    #[tokio::test]
4691    async fn a_streaming_hang_up_during_prefill_cancels_the_generation() {
4692        assert!(hang_up_reaches_the_generator(true).await);
4693    }
4694}